generator object, next method

Peter Otten __peter__ at web.de
Thu Sep 8 09:49:06 CEST 2005


simonwittber at gmail.com wrote:

>>>> gen = iterator()
>>>> gen.next
> <method-wrapper object at 0x009D1B70>

Behind the scene, gen.next is bound to _, i. e. it cannot be
garbage-collected. Then...

>>>> gen.next
> <method-wrapper object at 0x009D1BB0>

a new method wrapper is created and assigned to _, and the previous method
wrapper is now garbage-collected. The memory location is therefore
available for reuse for...

>>>> gen.next
> <method-wrapper object at 0x009D1B70>

yet another method wrapper -- and so on.

>>>> gen.next
> <method-wrapper object at 0x009D1BB0>
>>>> gen.next is gen.next
> False
> 
> 
> What is behind this apparently strange behaviour? (The .next method
> seems to alternately bind to two different objects)

But it isn't. What seems to be the same object are distinct objects at the
same memory location. See what happens if you inhibit garbage-collection by
keeping a reference of the method wrappers:

>>> it = iter("")
>>> [it.next for _ in range(5)]
[<method-wrapper object at 0x4029388c>, <method-wrapper object at
0x402938ec>, <method-wrapper object at 0x402938cc>, <method-wrapper object
at 0x4029390c>, <method-wrapper object at 0x4029392c>]

Peter




More information about the Python-list mailing list