Generator state/parameters
David Mertz, Ph.D.
mertz at gnosis.cx
Fri Dec 12 02:52:32 EST 2003
More information about the Python-list mailing list
Fri Dec 12 02:52:32 EST 2003
- Previous message (by thread): Generator state/parameters
- Next message (by thread): Python supported web hosting?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
|mertz at gnosis.cx (David Mertz, Ph.D.) wrote: |> >>> def echo(): |> ... message = [None] |> ... while message[0] != "EXIT": |> ... yield message |> ... |> >>> for mess in echo(): |> ... if mess[0] is not None: print mess[0] |> ... mess[0] = raw_input("Word: ") michele.simionato at poste.it (Michele Simionato) wrote previously: |A more verbose but arguably more elegant way would be to wrap the |generator in a class. Let me repost some code I wrote some time ago. |class MyIterator(Iterator): | def __gen__(self): | self.x=1 | yield self.x # will be changed outside the class | yield self.x | |iterator=MyIterator() |print iterator.next() |iterator.x=5 |print iterator.next() I don't disagree, of course, with Michele's class-based approach. For something fleshed out, his style lets you do a lot more with the underlying class. But there *is* something awfully elegant about the function-like definition syntax of simple generators. Doing what I do in the simple example--yielding a mutable object, and manipulating that object outside the generator--feels very Pythonic to me. I use a list for this, but a different mutable object would work similarly (a dictionary, instance, shelve, etc.) But obviously, keep both styles in mind; either might be a good solution to a problem. It just depends on your needs and coding style. Yours, David... -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! -------------------------------------------------------------------------
- Previous message (by thread): Generator state/parameters
- Next message (by thread): Python supported web hosting?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list