[Python-ideas] Automatic context managers
Steven D'Aprano
steve at pearwood.info
Thu Apr 25 08:17:10 CEST 2013
On 25/04/13 14:47, anatoly techtonik wrote:
> On Thu, Apr 25, 2013 at 7:23 AM, Cameron Simpson <cs at zip.com.au> wrote:
>> Then aren't you just talking about the __del__ method?
>>
>
> No. The __del__ method is only called during garbage collection phase which
> may be delayed. In PySide the QObject is deleted immediately.
Citation please. Where is this documented?
I find your claim difficult to believe, unless PySide implements it's own garbage collector which runs side-by-side to the Python one and knows about PySide objects. Otherwise when objects are deleted depends on Python, not the framework. Objects in Python do not know when they are deleted unless Python calls their __del__ method.
My guess is that if you set up a circular reference between two PySide objects, they will suffer the exact same delay in garbage collection as any other two objects.
This thread on the PySide mailing list suggests that you are mistaken, PySide does not have superpowers over and above Python's garbage collector, and is subject to the exact same non-deterministic destructors as any other Python object. Whether you call that destructor __del__ or __exit__ makes no difference.
http://www.mail-archive.com/pyside@lists.openbossa.org/msg01029.html
Or, and for the record, the reason that with statements work so well is because they are guaranteed to be deterministic. You cannot leave the with block without the __exit__ method being called. It doesn't matter whether you have one reference to the context manager object or ten references, the __exit__ method is still called, and the object still exists. That is *very* different from a destructor method.
py> with open('/tmp/rubbish', 'w') as f:
... f.write('hello world')
...
11
py> f.write('goodbye')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
py> f
<_io.TextIOWrapper name='/tmp/rubbish' mode='w' encoding='UTF-8'>
On the other hand, objects being freed is not deterministic. They'll be freed when there are no longer any references to it, which may be Never.
Reference counting GCs are deterministic, but cannot deal with circular references. Other GCs can deal with circular references, but are non-deterministic. Even the Java GC doesn't guarantee that the finalize() method will always be called.
--
Steven
More information about the Python-ideas
mailing list