[Python-ideas] Automatic context managers

anatoly techtonik techtonik at gmail.com
Wed Apr 24 10:59:40 CEST 2013


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.

I don't know why it was not implemented in the first place. Any ideas?

Depending on the answer to the above, the solution can be different. I
assume that this was done for a reason (probably immediate garbage
collection is too expensive), but confirmation is welcome. Meanwhile the
solution can be implemented with auto context manager, which __exit__
method is automatically called when all links to created object are lost.

Difference from usual "with something" is that it is transparent to the
user (leaves less details to worry about) and makes code more beautiful --
in the example above the assignment is made inside setup(...) parameter
assignment. An example with ordinary "with" statement would look like:

    with open('README.txt') as readme:
      setup(
        ....
        long_description=readme.read(),
        ....
      )

The nesting level increases with every new file you need to read.
Another variation is intermediate variables, which is also less nice.

    with open('README.txt') as readme:
      content = readme.read()
    setup(
      ....
      long_description=content,
      ....
    )

-- 
anatoly t.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130424/8bcf8f9a/attachment.html>


More information about the Python-ideas mailing list