Searching equivalent to C++ RAII or deterministic destructors
pavlovevidence at gmail.com
Thu Jul 2 20:36:38 CEST 2009
On Jul 2, 3:12 am, Ulrich Eckhardt <eckha... at satorlaser.com> wrote:
> Bearophile wrote:
> > Ulrich Eckhardt:
> >> a way to automatically release the resource, something
> >> which I would do in the destructor in C++.
> > Is this helpful?
> Yes, it aims in the same direction. However, I'm not sure this applies to my
> case. The point is that the resource handle is not just used locally in a
> restricted scope but it is allocated and stored. The 'with' is something
> that makes sense in the context of mutex locking, where you have a
> well-defined critical section. What I need is something similar to open(),
> which returs a file. When the last reference to that object goes out of
> scope, the underlying file object is closed.
On CPython you can do it with a __del__ attribute.
Warning: objects with a __del__ attribute prevent reference cycle
detection, which can potentially lead to memory (and resource) leaks.
So you must be careful to avoid creating reference loops with that
Note that file objects have a close method; you can explicitly close
it at any time. Your object should follow that example, and define a
close (or release, or whatever) method. I'd recommend making an
effort to call it and to rely on __del__ as little as possible.
More information about the Python-list