My Generator Paradox!

mensanator at aol.com mensanator at aol.com
Thu Mar 16 19:48:57 EST 2006


vbgunz wrote:
> I am afraid that this is the first time in which I would probably need
> something explained to me as if I were a little child. I am having a
> hard time getting this through my thick skull. What in the world is
> wrong with this!?
>
> ''' ########################################################### '''
>
> def generatorFunction(sequence=['item1', 'item2', 'item3']):
>     for item in sequence:
>         yield item
>
> yieldedValue = generatorFunction()
>
> '''this seems to work perfectly.'''
> print '-' * 32
> print yieldedValue          # <generator object at 0xb723014c>
> print yieldedValue.next()   # item1
> print yieldedValue.next()   # item2
> print yieldedValue.next()   # item3
>
> '''this is where things don't make any sense!'''
> print '-' * 32
> print generatorFunction()           # <generator object at 0xb723022c>
> print generatorFunction().next()    # item1
> print generatorFunction().next()    # item1
> print generatorFunction().next()    # item1
>
> ''' ########################################################### '''
>
> the first set of calls assigned to yieldedValue work but the second set
> without assignment don't.  I asked for help on this at #python (I love
> those people in there!) and was told the following...
> generatorFunction() is a call (obvious) when calling the second set, I
> am resetting the iteration and this explains why I only and always get
> item1.
>
> ok. *but* why in the world does the first set of calls work?
> technically, isn't yieldedValue == generatorFunction() on a name basis?
> I mean isn't the following technically the same?
>
> generatorFunction()
> yieldedValue = generatorFunction()

No. Look at this

>>> a = generatorFunction()
>>> b = generatorFunction()
>>> a==b
False

Why aren'y they the same? Here's a clue:

>>> generatorFunction()
<generator object at 0x00B28418>
>>> generatorFunction()
<generator object at 0x00AD24E0>

Note the addresses are different.

Try this

>>> b.next()
'item1'
>>> b.next()
'item2'
>>> generatorFunction().next()
'item1'

Just like your example, the generator re-initailized and
printed item1. But that's not the same generator as b

>>> b.next()
'item3'


>
> aren't they both the same? To me they should be but obviously this
> creates the point of this paradox. I don't understand what is happening
> here... Can someone care to explain why the assignment works but not
> the direct call? In a sense shouldn't the assignment yield the same
> results as the direct call and vice versa? I am confused :(
> 
> Thank you for any help on this!




More information about the Python-list mailing list