My Generator Paradox!

Fredrik Lundh fredrik at pythonware.com
Fri Mar 17 08:21:03 CET 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
>
> ''' ########################################################### '''

does the following surprise you too ?

    f = open("filename")
    print f.readline() # prints first line
    print f.readline() # prints second line
    print f.readline() # prints third line

    print open("filename").readline() # prints first line
    print open("filename").readline() # prints first line
    print open("filename").readline() # prints first line

</F>






More information about the Python-list mailing list