My Generator Paradox!
vbgunz
vbgunz at gmail.com
Thu Mar 16 19:17:46 EST 2006
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()
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