[Python-ideas] Automatic context managers
Ronald Oussoren
ronaldoussoren at mac.com
Thu Apr 25 07:46:26 CEST 2013
On 25 Apr, 2013, at 6:00, anatoly techtonik <techtonik at gmail.com> wrote:
> On Wed, Apr 24, 2013 at 12:23 PM, Ronald Oussoren <ronaldoussoren at mac.com> wrote:
>
>
>
>
> On 24 Apr, 2013, at 10:59, anatoly techtonik <techtonik at gmail.com> wrote:
>
> > Long time no see, all. :P
> >
> > PySide Qt binding have an interesting property - when you create widgets, you need to assign them to variables. When such variable is lost, object is immediately destroyed.
> >
> > I often use this one-shot code in setup.py:
> > ...
> > long_description = open('README.txt').read(),
> > ....
> >
> > Which probably leaves the README.txt file open until the setup.py exits. So, the idea is to close the file as soon as the variable is lost.
>
> The file is automaticly closed as soon as the file object is garbage collected. In your example CPython would currently collect at the end of the read call (unles there is an exception) because of the reference counting garbage collector, but other implementations have other garbage collectors and can collect the file object (much) later.
>
> Right. Automatic context manager proposal brings this mechanism from garbage collection implementation level to language definition level.
What proposal? What you appear to propose is either that implementations must use a reference counting collector (more or less ensuring that the file will be closed after the call to read in your example), or that the exit part of the context protocol is run whenever an object is going out of scope.
Neither is going to happen, the language specification doesn't proscribe the garbage collection algorithm for a reason: implementations of Python like Jython and IronPython inherit the garbage collector from their host environment (the JVM and CLR). Automaticly calling __exit__ when an object goes out of scope won't work either, it would break passing arguments to functions.
Ronald
More information about the Python-ideas
mailing list