[Python-ideas] Automatic context managers

anatoly techtonik techtonik at gmail.com
Fri Apr 26 15:22:48 CEST 2013


On Thu, Apr 25, 2013 at 8:46 AM, Ronald Oussoren <ronaldoussoren at mac.com>wrote:

>
> 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.
>

The proposal is fully illustrated by the user story above - immediately
close file after it is read operation is complete. The proposed
implementation is automatic context manager -- optional, Python level
mechanism to run exit part of the context protocol when object loses all
references. GC is out of scope here.


> Automaticly calling __exit__ when an object goes out of scope won't work
> either, it would break passing arguments to functions.
>

Why? Can you provide an example?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130426/1fa940e5/attachment.html>


More information about the Python-ideas mailing list