contextlib.contextmanager and try/finally

Ian Kelly ian.g.kelly at gmail.com
Wed Jan 11 12:20:19 EST 2012


On Wed, Jan 11, 2012 at 8:45 AM,  <johannh at gmail.com> wrote:
> However, then I read the following paragraph from PEP-343:
>
>    Note that we're not guaranteeing that the finally-clause is
>    executed immediately after the generator object becomes unused,
>    even though this is how it will work in CPython.  This is similar
>    to auto-closing files: while a reference-counting implementation
>    like CPython deallocates an object as soon as the last reference
>    to it goes away, implementations that use other GC algorithms do
>    not make the same guarantee.  This applies to Jython, IronPython,
>    and probably to Python running on Parrot.
>
> That suggests that I cannot rely on the contextlib.contextmanager decorator to ensure that the connection is closed and would have to write my own object with __enter__ and __exit__ methods to guarantee this.
>
> Is this understanding accurate?  If so, could someone illustrate why this is so?

First, this is just a timing issue.  There is no guarantee that the
finally clause will be executed immediately, but it is guaranteed to
be executed at some point.  In the other implementations, it would
happen whenever the GC algorithm runs.

Second, I believe that passage is not referring to the contextmanager
decorator specifically, but more generally to the changes that were
made to allow generators to yield from within a try-finally construct
(previously this would have been illegal syntax, since there was no
way to guarantee the finally block would be performed).

Like Neil mentioned, a contextmanager generator is wrapped with an
__exit__ method that is guaranteed to be called and that explicitly
resumes or closes the generator.  So as long as your contextmanager
generator is properly written (i.e. it yields exactly once), the
finally block will execute in a timely fashion.



More information about the Python-list mailing list