wow! (generators) - suggestion (yield saved)

Quinn Dunkan quinn at retch.ugcs.caltech.edu
Tue Aug 7 17:33:19 EDT 2001


On Sun, 5 Aug 2001 12:20:02 +0200, Gerhard Häring <gerhard.nospam at bigfoot.de>
wrote:
>Like in most of the cases I played with generators, you could have replaced
>them with a simple s = "" at the beginning, replace every yield with s +=
><whatever> and a return s at the end. I think you can always do this if all you
>want is a list.
>
>>I like generators :-)
>
>I like them, too :-)

Well, better to do the usual make-list-then-join idiom, not "s = s + foo".

Generators are cool, but I think they have a danger of other "cool" features:
the urge to use them when you don't really need them.  I fall into this with
list comprehensions all the time.  I'll need some simple operation, and write
[ f(x) for x in a ].  Then I'll need to do some more, so I'll write
[ g(f(x)) for x in a + b ].  I wind up with things like

for k, v in [ k.strip(), v.strip() for k, v in line.split('=')
                for line in open(self.config_file).readlines()
                if not line.beginswith('#') ]:
    self.dict[k] = v

... which I quickly dismantle and rewrite as a series of statements in the
loop, which I'll have to do anyway if I want the "parsing" to be smarter.  I
should have started with a loop in the first place.

I have a feeling that myself and others are going to feel tempted to use
generators when a list would be more flexible and easier to understand.  They
make it easy to give yourself an "it'll be more efficient" rationale, and we
all know how misleading those are.  Besides, they're just plain nifty.  Like
list comprehensions, I'll be (subconciously, perhaps) *looking* for uses for
them.



More information about the Python-list mailing list