[Tutor] string to list
Suppose i have this string: z = 'AT/CG' How do i get this list: zlist = ['A','T/C','G'] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] access class through indexing?
On 8/4/10, Dave Angel wrote: > Alex Hall wrote: >> On 8/4/10, Evert Rol wrote: >> >>> >>> That depends how you create the Pile of 52 cards: list(52) also doesn't >>> generate 52 (random) items. >>> If you override __init__ to accept an integer that generates the cards >>> for >>> you, this should work. >>> >> Here is my init, not half as pretty as yours, but it should work. >> Maybe this will explain the problem. >> >> def __init__(self, size, cards=None, fill=False): >> #creates a pile of cards. If "fill"==true, it will auto-fill the >> pile starting from the Ace of Clubs up through the King of Spades, >> stopping if it exceeds the size arg. >> #if the cards arg is not null, it will populate the pile with the >> cards in the list. >> self=[] >> if fill: #auto-fill, useful to generate a new, unshuffled deck >>for i in range(1, 14): >> for j in range(1, 5): >> self.append(Card(i, j)) >> #end for >>#end for >>self=self[:size] #keep only the amount specified >> elif cards is not None: #fill the pile with the cards >>for c in cards: >> self.append(c) >>#end for >> #end if >> #end def __init__ >> >> >> > You have two serious problems here, and maybe others, I didn't keep looking. > > Since you never call super(), the init of the base class never happens. > It may happen to work, since you're apparently willing to take its > default behavior, but I don't know. But even worse, you never even talk > to your own object. The first parameter to __init__() is a ref to the > actual object you're supposed to be initializing, and you immediately > overwrite it (self) with another object. As a result, everything else > you do in that method is thrown out when the method returns. Remove > that line > > self = [] That makes sense, and doing so has fixed everything. I am still not clear on the whole super() thing; I saw it in another project and tried to find out about it, but what I found was very confusing, and super() did not seem terribly important, so I did not pursue the matter further. Apparently it is important... > > DaveA > > -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] global exception handling?
> > But, the issue is, I have many places where I write to the database and > > would have to embed each of these in a try/except block. I can do that, > > but wondered if there is a "global" way to catch this 'database is locked' > > error? I found someone asking this sort of question online but it doesn't > > appear to be answered: > > http://bytes.com/topic/python/answers/799486-how-do-i-prevent-exceptions-stopping-execution-global-exception-handler > > I'm not sure why you would like to do that: your code assumes the database > interaction works fine, and based on that just continues it's normal flow. If > the database is locked, you'll need to do something to prevent your code > crashing further down, which is what you put in the except OperationalError: > block. I would assume that the error handling depends on where you are in the > code. > If you can always perform the same type of error handling, just create a > convenience function (possibly with the SQL statement as argument) that calls > the database and returns the results, and put the database call inside the > try: except: clause. Then you need to do this only once. Interesting, it didn't occur to me to do that. I may give it a try. Since I am making INSERTs and UPDATEs to the database from all over the application (in different modules), maybe I should put this error-handling convenience function in a module and import it into every other module, then I can just use it. Unfortunately, I'll still have to go back and find every instance of when I do INSERT or UPDATE to change this to use the convenience function, but it will still save me some keystrokes to fix the app. > A global way to catch the database-locked exception is just to put the try: > except OperationalError: around your complete code. Exceptions propagate all > the way to the function where your program started, and if you catch it > there, you will catch every OperationalError exception from anywhere in the > code. Of course, your program then always exits anyway, because you can't > return to the point where the the exception was thrown (or maybe you can, but > not that I'm aware of. I wouldn't recommend it though). That I really didn't know at all. But yes, if the program exits, that's not going to work. > > > p.s. *I use the nice program SQLite Database Browser and if I edit a > > > field in the database my Python app is accessing, click "Apply changes", > > > but I do *not* save the changes (that is, I do not click the disk icon), > > > when I go to write to that database from my Python app, I get a 'database > > > is locked' error. > Sounds like somewhat odd behaviour to me: "apply changes" for me means "apply > & commit", ie, it includes the save operation. Might > just be me. I guess "Apply changes" opens the database connection, but then > "save" performs the actual commit to the database, and > in the meantime the database is locked. I don't know, either, but I was glad to find a way to reproduce the problem so that I could anticipate it for potential users. Thanks for your help, Che ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] access class through indexing?
Alex Hall wrote: On 8/4/10, Evert Rol wrote: That depends how you create the Pile of 52 cards: list(52) also doesn't generate 52 (random) items. If you override __init__ to accept an integer that generates the cards for you, this should work. Here is my init, not half as pretty as yours, but it should work. Maybe this will explain the problem. def __init__(self, size, cards=None, fill=False): #creates a pile of cards. If "fill"==true, it will auto-fill the pile starting from the Ace of Clubs up through the King of Spades, stopping if it exceeds the size arg. #if the cards arg is not null, it will populate the pile with the cards in the list. self=[] if fill: #auto-fill, useful to generate a new, unshuffled deck for i in range(1, 14): for j in range(1, 5): self.append(Card(i, j)) #end for #end for self=self[:size] #keep only the amount specified elif cards is not None: #fill the pile with the cards for c in cards: self.append(c) #end for #end if #end def __init__ You have two serious problems here, and maybe others, I didn't keep looking. Since you never call super(), the init of the base class never happens. It may happen to work, since you're apparently willing to take its default behavior, but I don't know. But even worse, you never even talk to your own object. The first parameter to __init__() is a ref to the actual object you're supposed to be initializing, and you immediately overwrite it (self) with another object. As a result, everything else you do in that method is thrown out when the method returns. Remove that line self = [] DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] access class through indexing?
On Wed, Aug 4, 2010 at 5:28 PM, Alex Hall wrote: > Here is my init, not half as pretty as yours, but it should work. > Maybe this will explain the problem. > > def __init__(self, size, cards=None, fill=False): > #creates a pile of cards. If "fill"==true, it will auto-fill the > pile starting from the Ace of Clubs up through the King of Spades, > stopping if it exceeds the size arg. > #if the cards arg is not null, it will populate the pile with the > cards in the list. > self=[] > This is the problem. You cannot re-assign self inside the __init__ method (or any method, for that matter). Well, you can, but it doesn't do what you expect. All you're doing is shadowing the self that gets passed in to the function, not changing it. Just call list.__init__(self) to initialize self using the initialized from the list class. > if fill: #auto-fill, useful to generate a new, unshuffled deck > for i in range(1, 14): >for j in range(1, 5): > self.append(Card(i, j)) >#end for > #end for > self=self[:size] #keep only the amount specified > The same thing goes on here, you can't re-assign self. Instead, you can alter it in place by doing self[:] = self[:size]. That's called slice assignment. There's some discussion of this here: http://docs.python.org/release/2.5.2/ref/assignment.html and http://docs.python.org/library/stdtypes.html#mutable-sequence-types > elif cards is not None: #fill the pile with the cards > for c in cards: >self.append(c) > #end for > #end if > #end def __init__ > I don't have a Card class built, but here's an example that uses tuples instead: class Pile(list): def __init__(self, size=52, cards=None, fill=False): list.__init__(self) #Initialize self as an empty list if fill: for i in range(1, 14): for j in range(1, 5): self.append((i,j)) self[:] = self[:size] elif cards is not None: for c in cards: self.append(c) I think that supports all the same things you had in your example. -- Jerry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] access class through indexing?
On 4 Aug 2010, at 23:28 , Alex Hall wrote: > On 8/4/10, Evert Rol wrote: > Further to my questions about overriding builtin methods earlier, how > would I make a class able to be accessed and changed using index > notation? For example, take the following: > deck=CardPile(52) #creates a new deck of cards > print(len(deck)) #prints 52, thanks to my __len__ function > for c in deck: print c #also works thanks to __iter__ > print(deck[4]) #fails with a list index out of range error > How would I get the last one working? I tried __getattr__(self, i), > but it did not work. I want to be able to get an arbitrary item from > the "pile" of cards (which can be a deck, a hand, whatever), and/or > set an element. A "pile" is just a list of Card objects, so I would > only need to use sequence indexing, not mapping functions. > Implement __getitem__(self, key) (See http://docs.python.org/reference/datamodel.html#emulating-container-types ) If you want to support slicing (access like deck[0:10]), you'll need to handle getting a slice object as the key in addition to accepting an integer key. If a pile is really "just" a list of cards, you may want to look into inheriting from list instead of re-implementing all of the functionality on your own. >>> I tried this first, by typing >>> class Pile(list): >>> Doing this does not seem to work, though, since creating a pile of >>> size 52 results in a list of size 0, unless I include the __len__ >>> function. I thought putting (list) in my class definition would >>> automatically give me the functions of a list as well as anything I >>> wanted to implement, but that does not seem to be the case. >> >> That depends how you create the Pile of 52 cards: list(52) also doesn't >> generate 52 (random) items. >> If you override __init__ to accept an integer that generates the cards for >> you, this should work. > Here is my init, not half as pretty as yours, but it should work. > Maybe this will explain the problem. > > def __init__(self, size, cards=None, fill=False): > #creates a pile of cards. If "fill"==true, it will auto-fill the > pile starting from the Ace of Clubs up through the King of Spades, > stopping if it exceeds the size arg. > #if the cards arg is not null, it will populate the pile with the > cards in the list. > self=[] You declare self to be a list here (while somewhere before the def __init__, you'll have class Pile(list), meaning every self will be a Pile object. While self is an arbitrarily chosen name, it is assigned by the interpreter when calling the methods (I hope I'm saying that correctly). So when __init__(self, ...) is called, self is a Pile object, then you turn self into a list object, loosing its meaning. Don't reassign self (but you can do 'print self[:size]'. Then again, you probably don't need that inside your class. Try using your __init__, then at the end of the __init__ method, print type(self). That should be something like . Now do the same with the init below that uses super. You should get something like . > if fill: #auto-fill, useful to generate a new, unshuffled deck > for i in range(1, 14): >for j in range(1, 5): > self.append(Card(i, j)) >#end for > #end for > self=self[:size] #keep only the amount specified > elif cards is not None: #fill the pile with the cards > for c in cards: >self.append(c) > #end for > #end if > #end def __init__ > > >> Something like: >> >> class Pile(list): >>def __init__(self, *args, **kwargs): >>if len(args) == 1 and isinstance(args[0], (int, long)): >>args = ([Card(i) for i in xrange(args[0])],) >>super(Pile, self).__init__(*args, **kwargs) > Why call super here, if it is already my own __init__? It's just Good Practice to always call super, propagating any remaining arguments to the base class __init__ (hence the *args & **kwargs). Google for "Python super" and read a few of those hits. At first, it may make little sense, because there's a lot that can be said about it, but after a while, it'll become clearer. >> allows things like Pile(52), Pile([card1, card2, card3]), Pile(12)[0:3] etc. > Again, my init is not nearly so fancy, and I will have to look hard at > what you did to understand it, but they are the same in terms of class > structure/inheriting list attributes as far as I can see, except the > call to the super.__init__ method. If you're confused about the first line, I can image, but it's just a fancy way to find out if you initialize the Pile with a list of cards, or with a single integer argument. The *args & **kwargs, again, Google around a bit. In essence, these just capture extra argument (positional arguments, then keyword arguments). def __init__(self, ncards=0, *args, **kwargs) could even be better, but I'm not sure if that works correctly. But yes, other than the sel
Re: [Tutor] access class through indexing?
On 8/4/10, Evert Rol wrote: Further to my questions about overriding builtin methods earlier, how would I make a class able to be accessed and changed using index notation? For example, take the following: deck=CardPile(52) #creates a new deck of cards print(len(deck)) #prints 52, thanks to my __len__ function for c in deck: print c #also works thanks to __iter__ print(deck[4]) #fails with a list index out of range error How would I get the last one working? I tried __getattr__(self, i), but it did not work. I want to be able to get an arbitrary item from the "pile" of cards (which can be a deck, a hand, whatever), and/or set an element. A "pile" is just a list of Card objects, so I would only need to use sequence indexing, not mapping functions. >>> >>> Implement __getitem__(self, key) (See >>> http://docs.python.org/reference/datamodel.html#emulating-container-types >>> ) >>> >>> If you want to support slicing (access like deck[0:10]), you'll need to >>> handle getting a slice object as the key in addition to accepting an >>> integer >>> key. >>> >>> If a pile is really "just" a list of cards, you may want to look into >>> inheriting from list instead of re-implementing all of the functionality >>> on >>> your own. >> I tried this first, by typing >> class Pile(list): >> Doing this does not seem to work, though, since creating a pile of >> size 52 results in a list of size 0, unless I include the __len__ >> function. I thought putting (list) in my class definition would >> automatically give me the functions of a list as well as anything I >> wanted to implement, but that does not seem to be the case. > > That depends how you create the Pile of 52 cards: list(52) also doesn't > generate 52 (random) items. > If you override __init__ to accept an integer that generates the cards for > you, this should work. Here is my init, not half as pretty as yours, but it should work. Maybe this will explain the problem. def __init__(self, size, cards=None, fill=False): #creates a pile of cards. If "fill"==true, it will auto-fill the pile starting from the Ace of Clubs up through the King of Spades, stopping if it exceeds the size arg. #if the cards arg is not null, it will populate the pile with the cards in the list. self=[] if fill: #auto-fill, useful to generate a new, unshuffled deck for i in range(1, 14): for j in range(1, 5): self.append(Card(i, j)) #end for #end for self=self[:size] #keep only the amount specified elif cards is not None: #fill the pile with the cards for c in cards: self.append(c) #end for #end if #end def __init__ > Something like: > > class Pile(list): > def __init__(self, *args, **kwargs): > if len(args) == 1 and isinstance(args[0], (int, long)): > args = ([Card(i) for i in xrange(args[0])],) > super(Pile, self).__init__(*args, **kwargs) Why call super here, if it is already my own __init__? > > allows things like Pile(52), Pile([card1, card2, card3]), Pile(12)[0:3] etc. Again, my init is not nearly so fancy, and I will have to look hard at what you did to understand it, but they are the same in terms of class structure/inheriting list attributes as far as I can see, except the call to the super.__init__ method. > > Cheers, > > Evert > > -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] access class through indexing?
>>> Further to my questions about overriding builtin methods earlier, how >>> would I make a class able to be accessed and changed using index >>> notation? For example, take the following: >>> deck=CardPile(52) #creates a new deck of cards >>> print(len(deck)) #prints 52, thanks to my __len__ function >>> for c in deck: print c #also works thanks to __iter__ >>> print(deck[4]) #fails with a list index out of range error >>> How would I get the last one working? I tried __getattr__(self, i), >>> but it did not work. I want to be able to get an arbitrary item from >>> the "pile" of cards (which can be a deck, a hand, whatever), and/or >>> set an element. A "pile" is just a list of Card objects, so I would >>> only need to use sequence indexing, not mapping functions. >>> >> >> Implement __getitem__(self, key) (See >> http://docs.python.org/reference/datamodel.html#emulating-container-types ) >> >> If you want to support slicing (access like deck[0:10]), you'll need to >> handle getting a slice object as the key in addition to accepting an integer >> key. >> >> If a pile is really "just" a list of cards, you may want to look into >> inheriting from list instead of re-implementing all of the functionality on >> your own. > I tried this first, by typing > class Pile(list): > Doing this does not seem to work, though, since creating a pile of > size 52 results in a list of size 0, unless I include the __len__ > function. I thought putting (list) in my class definition would > automatically give me the functions of a list as well as anything I > wanted to implement, but that does not seem to be the case. That depends how you create the Pile of 52 cards: list(52) also doesn't generate 52 (random) items. If you override __init__ to accept an integer that generates the cards for you, this should work. Something like: class Pile(list): def __init__(self, *args, **kwargs): if len(args) == 1 and isinstance(args[0], (int, long)): args = ([Card(i) for i in xrange(args[0])],) super(Pile, self).__init__(*args, **kwargs) allows things like Pile(52), Pile([card1, card2, card3]), Pile(12)[0:3] etc. Cheers, Evert ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] access class through indexing?
On 8/4/10, Jerry Hill wrote: > On Wed, Aug 4, 2010 at 4:17 PM, Alex Hall wrote: > >> Hi all, >> Further to my questions about overriding builtin methods earlier, how >> would I make a class able to be accessed and changed using index >> notation? For example, take the following: >> deck=CardPile(52) #creates a new deck of cards >> print(len(deck)) #prints 52, thanks to my __len__ function >> for c in deck: print c #also works thanks to __iter__ >> print(deck[4]) #fails with a list index out of range error >> How would I get the last one working? I tried __getattr__(self, i), >> but it did not work. I want to be able to get an arbitrary item from >> the "pile" of cards (which can be a deck, a hand, whatever), and/or >> set an element. A "pile" is just a list of Card objects, so I would >> only need to use sequence indexing, not mapping functions. >> > > Implement __getitem__(self, key) (See > http://docs.python.org/reference/datamodel.html#emulating-container-types ) > > If you want to support slicing (access like deck[0:10]), you'll need to > handle getting a slice object as the key in addition to accepting an integer > key. > > If a pile is really "just" a list of cards, you may want to look into > inheriting from list instead of re-implementing all of the functionality on > your own. I tried this first, by typing class Pile(list): Doing this does not seem to work, though, since creating a pile of size 52 results in a list of size 0, unless I include the __len__ function. I thought putting (list) in my class definition would automatically give me the functions of a list as well as anything I wanted to implement, but that does not seem to be the case. > > -- > Jerry > -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] access class through indexing?
On Wed, Aug 4, 2010 at 4:17 PM, Alex Hall wrote: > Hi all, > Further to my questions about overriding builtin methods earlier, how > would I make a class able to be accessed and changed using index > notation? For example, take the following: > deck=CardPile(52) #creates a new deck of cards > print(len(deck)) #prints 52, thanks to my __len__ function > for c in deck: print c #also works thanks to __iter__ > print(deck[4]) #fails with a list index out of range error > How would I get the last one working? I tried __getattr__(self, i), > but it did not work. I want to be able to get an arbitrary item from > the "pile" of cards (which can be a deck, a hand, whatever), and/or > set an element. A "pile" is just a list of Card objects, so I would > only need to use sequence indexing, not mapping functions. > Implement __getitem__(self, key) (See http://docs.python.org/reference/datamodel.html#emulating-container-types ) If you want to support slicing (access like deck[0:10]), you'll need to handle getting a slice object as the key in addition to accepting an integer key. If a pile is really "just" a list of cards, you may want to look into inheriting from list instead of re-implementing all of the functionality on your own. -- Jerry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
class A: def call_by_name(self, func, data): f = A.__dict__.get(func, self.output_text) return f(data) def output_text(self, data):return data def output_hex(self, data):return '\\x' + data a = A() data = 'bar' print a.call_by_name('output_text', data) print a.call_by_name('output_hex', data) print a.call_by_name('foo', data) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
I have a side question, I am using python 2.7. Why do you use class A: instead of class A(object): ? -Huy On Wed, Aug 4, 2010 at 4:08 PM, bob gailer wrote: > On 8/4/2010 4:04 PM, bob gailer wrote: > >> On 8/4/2010 3:44 PM, Huy Ton That wrote: >> >>> Oh, that's right, I should have tried to example in the interpreter >>> instead of in my head:P >>> >>> Say Bob, >>> >>> Is that the preferred method over something like: >>> >> >> I would prefer to create a class and make these functions class methods. >> >> class A: >> def output_text(self, data):return data >> def output_hex(self, data):return '\\x' + data >> def __getattr__(self, name): >>return self.output_text >> a = A() >> data='bar' >> print a.output_text(data) >> print a.output_hex(data) >> print a.foo(data) >> >> I just realized my answer does not accomodate your looking for the > function by name. Please stand by > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] access class through indexing?
> Hi all, > Further to my questions about overriding builtin methods earlier, how > would I make a class able to be accessed and changed using index > notation? For example, take the following: > deck=CardPile(52) #creates a new deck of cards > print(len(deck)) #prints 52, thanks to my __len__ function > for c in deck: print c #also works thanks to __iter__ > print(deck[4]) #fails with a list index out of range error > How would I get the last one working? I tried __getattr__(self, i), > but it did not work. I want to be able to get an arbitrary item from > the "pile" of cards (which can be a deck, a hand, whatever), and/or > set an element. A "pile" is just a list of Card objects, so I would > only need to use sequence indexing, not mapping functions. If you want most or all of the things that lists implement, and you feel in general that CardPile is really an advanced/augmented list, just let CardPile inherit from list: class CardPile(list). I would think that should work for what you want. Evert ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] access class through indexing?
Hi all, Further to my questions about overriding builtin methods earlier, how would I make a class able to be accessed and changed using index notation? For example, take the following: deck=CardPile(52) #creates a new deck of cards print(len(deck)) #prints 52, thanks to my __len__ function for c in deck: print c #also works thanks to __iter__ print(deck[4]) #fails with a list index out of range error How would I get the last one working? I tried __getattr__(self, i), but it did not work. I want to be able to get an arbitrary item from the "pile" of cards (which can be a deck, a hand, whatever), and/or set an element. A "pile" is just a list of Card objects, so I would only need to use sequence indexing, not mapping functions. -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
On 8/4/2010 4:04 PM, bob gailer wrote: On 8/4/2010 3:44 PM, Huy Ton That wrote: Oh, that's right, I should have tried to example in the interpreter instead of in my head:P Say Bob, Is that the preferred method over something like: I would prefer to create a class and make these functions class methods. class A: def output_text(self, data):return data def output_hex(self, data):return '\\x' + data def __getattr__(self, name): return self.output_text a = A() data='bar' print a.output_text(data) print a.output_hex(data) print a.foo(data) I just realized my answer does not accomodate your looking for the function by name. Please stand by -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting date/time
On Wed, Aug 4, 2010 at 12:45 PM, Eric Hamiter wrote: > There are a few solutions here: > > http://stackoverflow.com/questions/904928/python-strftime-date-decimal-remove-0 > > Eric > > > On Wed, Aug 4, 2010 at 1:30 PM, Eduardo Vieira > wrote: >> >> I'm trying this example from python docs: >> from time import gmtime, strftime >> strftime("%a, %d %b %Y %H:%M:%S +", gmtime()) >> >> Output = 'Wed, 04 Aug 2010 17:58:42 +' >> Is not there a string formatting option for the day without a leading >> zero? Like: 'Wed, 4 Aug 2010 17:58:42 +' >> >> It looks like it's not in the docs. >> >> Thanks >> >> Eduardo >> ___ >> Tutor maillist - tu...@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > Thank you for the link. Just what I needed to know. The option %e didn't work for me, but I will use the other suggestions in the answers. Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
On 8/4/2010 3:44 PM, Huy Ton That wrote: Oh, that's right, I should have tried to example in the interpreter instead of in my head:P Say Bob, Is that the preferred method over something like: I would prefer to create a class and make these functions class methods. class A: def output_text(self, data):return data def output_hex(self, data):return '\\x' + data def __getattr__(self, name): return self.output_text a = A() data='bar' print a.output_text(data) print a.output_hex(data) print a.foo(data) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
Oh, that's right, I should have tried to example in the interpreter instead of in my head:P Say Bob, Is that the preferred method over something like: >>> import __main__ as main On Wed, Aug 4, 2010 at 3:32 PM, bob gailer wrote: > On 8/4/2010 1:23 PM, Pete wrote: > > Hi, > > I'm trying to understand the syntax for reflection in python. I was > wondering about this. > > From the example on diveintopython: > > http://diveintopython.org/power_of_introspection/index.html > > import statsout > def output(data, format="text"): > output_function = getattr(statsout, "output_%s" % format, > statsout.output_text) > return output_function(data) > >I was wondering about how to make this work if the function that you > are trying to call is not in a module. > > > Everything in Python is in a module. I suspect you mean not in an imported > module, e.g. in the main module. Whose __name__ is '__main__'. A reference > to the main module can be found: > > import sys > main = sys.modules['__main__'] > > Is that possible? > > Something like this: > > def output_text(data): > > return_value = "This is text: " + data > return return_value > > def output(data, format="text"): > output_function = getattr(*, "output_%s" % format, > statsout.output_text) > return output_function(data) > > > What I can't figure out is what to put in place of *. I've tried > globals()['__name__'], in various forms, to no avail. > > > Replace those stars with main as derived above. > > globals()['output_text'] will also give you a reference to the function. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
On 8/4/2010 1:23 PM, Pete wrote: Hi, I'm trying to understand the syntax for reflection in python. I was wondering about this. From the example on diveintopython: http://diveintopython.org/power_of_introspection/index.html import statsout def output(data, format="text"): output_function = getattr(statsout,"output_%s" % format, statsout.output_text) return output_function(data) I was wondering about how to make this work if the function that you are trying to call is not in a module. Everything in Python is in a module. I suspect you mean not in an imported module, e.g. in the main module. Whose __name__ is '__main__'. A reference to the main module can be found: import sys main = sys.modules['__main__'] Is that possible? Something like this: def output_text(data): return_value = "This is text: " + data return return_value def output(data, format="text"): output_function = getattr(*,"output_%s" % format, statsout.output_text) return output_function(data) What I can't figure out is what to put in place of *. I've tried globals()['__name__'], in various forms, to no avail. Replace those stars with main as derived above. globals()['output_text'] will also give you a reference to the function. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
*You can do like below Pete. Where globals has a reference to all functions in this space.* def output(data, format="text"): output_function = getattr(globals()['FUNCTION'], "output_%s" % format, statsout.output_text) return output_function(data) On Wed, Aug 4, 2010 at 3:18 PM, Pete wrote: > Hey Huy, > > thanks. But what is the first parameter in this case? (Note there is > nothing here I'm trying to accomplish except understand). > > In the original example, 'statsout' is the name of the module. In this case > there is no module so why can you substitute 'output_text'? > > thanks, > > Pete > > On 2010-08-04, at 3:09 PM, Huy Ton That wrote: > > If it is in the same code, and the namespace isn't a module or another > class you could do this: > > def output_text(data): > return_value = "This is text: " + data > return return_value > > def output(data, format="text"): > output_function = getattr(output_text, "output_%s" % format, > output_text) > return output_function(data) > > -HTH > > Huy > > On Wed, Aug 4, 2010 at 1:23 PM, Pete wrote: > >> Hi, >> >> I'm trying to understand the syntax for reflection in python. I was >> wondering about this. >> >> From the example on diveintopython: >> >>http://diveintopython.org/power_of_introspection/index.html >> >> import statsout >> def output(data, format="text"): >> output_function = getattr(statsout, "output_%s" % format, >> statsout.output_text) >> return output_function(data) >> >> >> I was wondering about how to make this work if the function that you are >> trying to call is not in a module. Is that possible? >> >> Something like this: >> >> def output_text(data): >> >> >> return_value = "This is text: " + data >> return return_value >> >> >> def output(data, format="text"): >> output_function = getattr(*, "output_%s" % format, >> statsout.output_text) >> return output_function(data) >> >> >> What I can't figure out is what to put in place of *. I've tried >> globals()['__name__'], in various forms, to no avail. >> >> Any pointers would be appreciated. >> >> thanks, >> >> Pete >> >> >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting date/time
On Wed, Aug 4, 2010 at 2:45 PM, Eric Hamiter wrote: > There are a few solutions here: > > > http://stackoverflow.com/questions/904928/python-strftime-date-decimal-remove-0 > > Eric > > > > On Wed, Aug 4, 2010 at 1:30 PM, Eduardo Vieira wrote: > >> I'm trying this example from python docs: >> from time import gmtime, strftime >> strftime("%a, %d %b %Y %H:%M:%S +", gmtime()) >> >> Output = 'Wed, 04 Aug 2010 17:58:42 +' >> Is not there a string formatting option for the day without a leading >> zero? Like: 'Wed, 4 Aug 2010 17:58:42 +' >> >> It looks like it's not in the docs. >> >> Thanks >> >> Eduardo >> > %e worked for me on Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
Hey Huy, thanks. But what is the first parameter in this case? (Note there is nothing here I'm trying to accomplish except understand). In the original example, 'statsout' is the name of the module. In this case there is no module so why can you substitute 'output_text'? thanks, Pete On 2010-08-04, at 3:09 PM, Huy Ton That wrote: > If it is in the same code, and the namespace isn't a module or another class > you could do this: > > def output_text(data): > return_value = "This is text: " + data > return return_value > > def output(data, format="text"): > output_function = getattr(output_text, "output_%s" % format, output_text) > return output_function(data) > > -HTH > > Huy > > On Wed, Aug 4, 2010 at 1:23 PM, Pete wrote: > Hi, > > I'm trying to understand the syntax for reflection in python. I was wondering > about this. > > From the example on diveintopython: > >http://diveintopython.org/power_of_introspection/index.html > > > import statsout > > def output(data, format="text"): > output_function = getattr(statsout, "output_%s" % format, > statsout.output_text) > return output_function(data) > > > I was wondering about how to make this work if the function that you are > trying to call is not in a module. Is that possible? > > Something like this: > > > def output_text(data): > > return_value = "This is text: " + data > return return_value > > > > def output(data, format="text"): > output_function = getattr(*, "output_%s" % format, > statsout.output_text) > return output_function(data) > > What I can't figure out is what to put in place of *. I've tried > globals()['__name__'], in various forms, to no avail. > > Any pointers would be appreciated. > > thanks, > > Pete > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting date/time
There are a few solutions here: http://stackoverflow.com/questions/904928/python-strftime-date-decimal-remove-0 Eric On Wed, Aug 4, 2010 at 1:30 PM, Eduardo Vieira wrote: > I'm trying this example from python docs: > from time import gmtime, strftime > strftime("%a, %d %b %Y %H:%M:%S +", gmtime()) > > Output = 'Wed, 04 Aug 2010 17:58:42 +' > Is not there a string formatting option for the day without a leading > zero? Like: 'Wed, 4 Aug 2010 17:58:42 +' > > It looks like it's not in the docs. > > Thanks > > Eduardo > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Formatting date/time
I'm trying this example from python docs: from time import gmtime, strftime strftime("%a, %d %b %Y %H:%M:%S +", gmtime()) Output = 'Wed, 04 Aug 2010 17:58:42 +' Is not there a string formatting option for the day without a leading zero? Like: 'Wed, 4 Aug 2010 17:58:42 +' It looks like it's not in the docs. Thanks Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] getattr()
Hi, I'm trying to understand the syntax for reflection in python. I was wondering about this. From the example on diveintopython: http://diveintopython.org/power_of_introspection/index.html import statsout def output(data, format="text"): output_function = getattr(statsout, "output_%s" % format, statsout.output_text) return output_function(data) I was wondering about how to make this work if the function that you are trying to call is not in a module. Is that possible? Something like this: def output_text(data): return_value = "This is text: " + data return return_value def output(data, format="text"): output_function = getattr(*, "output_%s" % format, statsout.output_text) return output_function(data) What I can't figure out is what to put in place of *. I've tried globals()['__name__'], in various forms, to no avail. Any pointers would be appreciated. thanks, Pete ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to get str() to use my function?
Thanks, and I also see what I did wrong with my __eq__ function. On 8/4/10, Huy Ton That wrote: > These are special method names. > > View section 3.4 and below here > > http://docs.python.org/reference/datamodel.html > > On Wed, Aug 4, 2010 at 11:37 AM, Alex Hall wrote: > >> It worked, thanks. Is there a list of these functions somewhere? That >> is, the functions that map implicitly to operators or implied uses? >> For example, printing will call __str__, as will a cal to str(). What >> about math or comparison operators? I have heard of __eq__, __gt__, >> and so on, but I tried to implement one and I got an error saying that >> it required three arguments. It did, but only because the first was >> self. I put the function inside my card class: >> def __eq__(self, card1, card2): >> return(card1.rank==card2.rank) >> #end def __eq__ >> For some reason it is still looking for three arguments... >> >> >> On 8/4/10, Huy Ton That wrote: >> > You could write __str__ function >> > >> class card(object): >> > ... def __init__(self, card1, card2): >> > ... self.card1, self.card2 = card1, card2 >> > ... def __str__(self): >> > ... return str(str(self.card1)+','+str(self.card2)) >> > ... >> a = card(0,0) >> str(a) >> > '0,0' >> > >> > On Wed, Aug 4, 2010 at 10:37 AM, Alex Hall wrote: >> > >> >> Hi all, >> >> I have a card class. A card object simply consists of a pair of >> >> numbers; 0,0 might be the ace of clubs, for example. I have a toString >> >> method in my card class. Is there a way to just say str(card) instead >> >> of card.toString()? Maybe some sort of basic, built-in function to >> >> override? TIA. Oh, what about doing the same with operators? For >> >> example, could I get the program to call my own math functions when it >> >> sees a card object in a math expression, like >> >> if(card1==card2) >> >> >> >> -- >> >> Have a great day, >> >> Alex (msg sent from GMail website) >> >> mehg...@gmail.com; http://www.facebook.com/mehgcap >> >> ___ >> >> Tutor maillist - Tutor@python.org >> >> To unsubscribe or change subscription options: >> >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > >> >> >> -- >> Have a great day, >> Alex (msg sent from GMail website) >> mehg...@gmail.com; http://www.facebook.com/mehgcap >> > -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to get str() to use my function?
These are special method names. View section 3.4 and below here http://docs.python.org/reference/datamodel.html On Wed, Aug 4, 2010 at 11:37 AM, Alex Hall wrote: > It worked, thanks. Is there a list of these functions somewhere? That > is, the functions that map implicitly to operators or implied uses? > For example, printing will call __str__, as will a cal to str(). What > about math or comparison operators? I have heard of __eq__, __gt__, > and so on, but I tried to implement one and I got an error saying that > it required three arguments. It did, but only because the first was > self. I put the function inside my card class: > def __eq__(self, card1, card2): > return(card1.rank==card2.rank) > #end def __eq__ > For some reason it is still looking for three arguments... > > > On 8/4/10, Huy Ton That wrote: > > You could write __str__ function > > > class card(object): > > ... def __init__(self, card1, card2): > > ... self.card1, self.card2 = card1, card2 > > ... def __str__(self): > > ... return str(str(self.card1)+','+str(self.card2)) > > ... > a = card(0,0) > str(a) > > '0,0' > > > > On Wed, Aug 4, 2010 at 10:37 AM, Alex Hall wrote: > > > >> Hi all, > >> I have a card class. A card object simply consists of a pair of > >> numbers; 0,0 might be the ace of clubs, for example. I have a toString > >> method in my card class. Is there a way to just say str(card) instead > >> of card.toString()? Maybe some sort of basic, built-in function to > >> override? TIA. Oh, what about doing the same with operators? For > >> example, could I get the program to call my own math functions when it > >> sees a card object in a math expression, like > >> if(card1==card2) > >> > >> -- > >> Have a great day, > >> Alex (msg sent from GMail website) > >> mehg...@gmail.com; http://www.facebook.com/mehgcap > >> ___ > >> Tutor maillist - Tutor@python.org > >> To unsubscribe or change subscription options: > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > > > -- > Have a great day, > Alex (msg sent from GMail website) > mehg...@gmail.com; http://www.facebook.com/mehgcap > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to get str() to use my function?
Am 04.08.2010 17:37, schrieb Alex Hall: It worked, thanks. Is there a list of these functions somewhere? That is, the functions that map implicitly to operators or implied uses? For example, printing will call __str__, as will a cal to str(). What about math or comparison operators? I have heard of __eq__, __gt__, and so on, but I tried to implement one and I got an error saying that it required three arguments. It did, but only because the first was self. I put the function inside my card class: def __eq__(self, card1, card2): return(card1.rank==card2.rank) #end def __eq__ For some reason it is still looking for three arguments... The official list of all special methods can be found at the datamodel description, chapter 3.4: http://docs.python.org/reference/datamodel.html#special-method-names Most Python books also have some explanations about this. Maybe the nice online book "Dive into Python" has a chapter? (I didn't check...) Regarding your problem: I've flew very fast over the docs. __eq__ seems to expect two arguments (self, other). So probably your method of the card class should look like: def __eq__(self, card2): return(self.rank==card2.rank) Cheers, Jan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to get str() to use my function?
It worked, thanks. Is there a list of these functions somewhere? That is, the functions that map implicitly to operators or implied uses? For example, printing will call __str__, as will a cal to str(). What about math or comparison operators? I have heard of __eq__, __gt__, and so on, but I tried to implement one and I got an error saying that it required three arguments. It did, but only because the first was self. I put the function inside my card class: def __eq__(self, card1, card2): return(card1.rank==card2.rank) #end def __eq__ For some reason it is still looking for three arguments... On 8/4/10, Huy Ton That wrote: > You could write __str__ function > class card(object): > ... def __init__(self, card1, card2): > ... self.card1, self.card2 = card1, card2 > ... def __str__(self): > ... return str(str(self.card1)+','+str(self.card2)) > ... a = card(0,0) str(a) > '0,0' > > On Wed, Aug 4, 2010 at 10:37 AM, Alex Hall wrote: > >> Hi all, >> I have a card class. A card object simply consists of a pair of >> numbers; 0,0 might be the ace of clubs, for example. I have a toString >> method in my card class. Is there a way to just say str(card) instead >> of card.toString()? Maybe some sort of basic, built-in function to >> override? TIA. Oh, what about doing the same with operators? For >> example, could I get the program to call my own math functions when it >> sees a card object in a math expression, like >> if(card1==card2) >> >> -- >> Have a great day, >> Alex (msg sent from GMail website) >> mehg...@gmail.com; http://www.facebook.com/mehgcap >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to get str() to use my function?
You could write __str__ function >>> class card(object): ... def __init__(self, card1, card2): ... self.card1, self.card2 = card1, card2 ... def __str__(self): ... return str(str(self.card1)+','+str(self.card2)) ... >>> a = card(0,0) >>> str(a) '0,0' On Wed, Aug 4, 2010 at 10:37 AM, Alex Hall wrote: > Hi all, > I have a card class. A card object simply consists of a pair of > numbers; 0,0 might be the ace of clubs, for example. I have a toString > method in my card class. Is there a way to just say str(card) instead > of card.toString()? Maybe some sort of basic, built-in function to > override? TIA. Oh, what about doing the same with operators? For > example, could I get the program to call my own math functions when it > sees a card object in a math expression, like > if(card1==card2) > > -- > Have a great day, > Alex (msg sent from GMail website) > mehg...@gmail.com; http://www.facebook.com/mehgcap > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to get str() to use my function?
On Thu, Aug 5, 2010 at 12:37 AM, Alex Hall wrote: > Hi all, > I have a card class. A card object simply consists of a pair of > numbers; 0,0 might be the ace of clubs, for example. I have a toString > method in my card class. Is there a way to just say str(card) instead > of card.toString()? Maybe some sort of basic, built-in function to > override? TIA. Oh, what about doing the same with operators? For > example, could I get the program to call my own math functions when it > sees a card object in a math expression, like > if(card1==card2) implement a __str__ method. For example: $ python Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16) [GCC 4.4.4 (CRUX)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(object): ... def __str__(self): ... return "" ... >>> foo = Foo() >>> foo <__main__.Foo object at 0x83d796c> >>> str(foo) '' >>> cheers James -- -- James Mills -- -- "Problems are solved by method" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to get str() to use my function?
Hi all, I have a card class. A card object simply consists of a pair of numbers; 0,0 might be the ace of clubs, for example. I have a toString method in my card class. Is there a way to just say str(card) instead of card.toString()? Maybe some sort of basic, built-in function to override? TIA. Oh, what about doing the same with operators? For example, could I get the program to call my own math functions when it sees a card object in a math expression, like if(card1==card2) -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Conflict with encoding in console view and file dump
Alex Baraibar wrote: > I just wish I understood better what happened and why. I've looked into > the Unicode section of the official docs, but I probably need to study it > more in order to fully understand it, so... Just in case you didn't come across it, there's a howto that covers the basics: http://docs.python.org/howto/unicode Peter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Conflict with encoding in console view and file dump
Hello, Peter. I checked my sys.stdout.encoding and it prints: >>> import sys >>> sys.stdout.encoding 'cp1252' Sometimes IDLE tells me I'm using characters that might not work if I don't place this at the beginning of my script: # -*- coding: cp1252 -*- Other than that, I have not made any changes to the default installation. Anyway, the modifications you made seem to work fine, so the problem appears to be solved. I just wish I understood better what happened and why. I've looked into the Unicode section of the official docs, but I probably need to study it more in order to fully understand it, so... I appreciate your help, thanx again. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor