contextlib.nested()

Diez B. Roggisch deets at nospam.web.de
Thu Nov 6 05:35:17 EST 2008


brasse wrote:

> Hello!
> 
> I have been running in to some problems when using
> contextlib.nested(). My problem arises when using code similar to
> this:
> 
> from __future__ import with_statement
> 
> from contextlib import nested
> 
> class Foo(object):
> 
>     def __init__(self, tag, fail=False):
>         print 'ctor', tag
>         self.tag = tag
>         if fail:
>             raise Exception()
> 
>     def __enter__(self):
>         print '__enter__', self.tag
>         return self
> 
>     def __exit__(self, *args):
>         print '__exit__', self.tag
> 
> with nested(Foo('a'), Foo('b', True)) as (a, b):
>     print a.tag
>     print b.tag
> 
> Here the construction of b fails which in turn means that the
> contextmanager fails to be created leaving me a constructed object (a)
> that needs to be deconstructed in some way. I realize that nested() is
> in a tight spot here to do anything about it since it doesn't exist.
> This behavior makes it hard for me to use the with statement (using
> nested()) the way I want.
> 
> Has anyone else been running in to this? Any tips on how to handle
> multiple resources?

I don't fully understand this. Why is in need to be deconstructed? Sure, the
object is created, but whatever is actually done on initialization which is
non-trivial should of course to the __enter__-method - which isn't called.

So, a falls out of a scope & gets GC'ed. What else do you expect to happen?

Diez



More information about the Python-list mailing list