[Python-ideas] Automatic context managers

Georg Brandl g.brandl at gmx.net
Fri Apr 26 20:44:21 CEST 2013


Am 26.04.2013 19:26, schrieb anatoly techtonik:

>     Again, I suspect we are falling prey to fuzzy language.  CPython will
>     reclaim objects as soon as their reference count reaches zero.  This is not
>     the garbage collector.  The garbage collector is a separate facility which
>     kicks in every once in a while to find objects that have non-zero reference
>     counts, even though they are unreachable, because of circular references. 
>     Some people say "garbage collector" or "garbage collection" to mean the
>     usual reclamation of objects when their refcount reaches zero, but this is
>     imprecise and confusing when mixed with people who use the term differently.
> 
>     I know nothing about the internals of QObjects, but like most others, I
>     *strongly* suspect that they are doing nothing special above and beyond what
>     Python does to determine the lifetime of an object.  Their cleanup happens
>     when the object is reclaimed (note I am careful not to say, "when the object
>     is garbage collected"). 
> 
>     The example on the PySide wiki is reproducible because it is not subject to
>     garbage collector laziness.  The "animation" name is a local in
>     animate_stuff.  At the end of that function, the name "animation" falls out
>     of scope, decrementing the reference count on the QPropertyAnimation object
>     it referenced.  That object now has a reference count of zero, so it is
>     reclaimed.  The cleanup code is then invoked, destroying the native objects
>     as well.
> 
> 
> Thanks. That makes it more clear. So if I create a circular reference with two
> QObjects and lose a link to both of them - they won't be reclaimed until GC
> starts, because their mutual reference count is not zero, right? And the same
> will be true for the object returned by open() involved in circular reference.
> 
> I guess that's the reason why the example in file.close() could not be updated
> to note that "with" is not needed anymore.
> http://docs.python.org/2/library/stdtypes.html#file.close

You got it backwards.  "with" has been introduced to supersede both the
correct-but-clumsy try-finally idiom and the sometimes-but-not-everywhere-
correct implicit "automatic" cleanup.

Georg




More information about the Python-ideas mailing list