contextlib.nested()

Diez B. Roggisch deets at nospam.web.de
Thu Nov 6 17:45:36 CET 2008


> Diez, Robert,
> 
> OK. The practice of "going live" or doing non-trivial initialization
> in __enter__ is new to me. I'm new to Python with a C++ background, so
> that shouldn't be a surprise. :-)
> 
> Ideally I would like to put all initialization in __init__ since then
> I would be able to use my object right after constructing it, without
> having to use it in a with statement. The reason I'm struggling with
> this is probably my C++ background. I'm rally accustomed to design
> with RAII in mind. Acquiring all resources in the ctor and releasing
> all resources in the dtor is *really* handy.

Yes, but this is a C++ idiom that does not translate well to python's
GC-based approach. Which is the *exact* reason why contexts have been
created in the first place.

> If you had a class that wanted to acquire some external resources that
> must be released at some point, how would you rewrite the code from my
> example?

If you *can*, use a context. Use __enter__ and __exit__. Try really hard to
use it that way.

If not - create a specific finalize-method or some such, and try not to
forget to call that. Potentially with an atexit-handler or some such.

the problem is that python can't guarantee that a __del__-method is invoked
at all, and *if* it is, it might find other stuff being released already
that it relies upon - e.g. imported modules being freed & not known
anymore.

Diez



More information about the Python-list mailing list