Searching equivalent to C++ RAII or deterministic destructors

Carl Banks pavlovevidence at gmail.com
Sat Jul 4 18:47:57 EDT 2009


On Jul 3, 5:34 am, Jack Diederich <jackd... at gmail.com> wrote:
> On Thu, Jul 2, 2009 at 2:36 PM, Carl Banks<pavlovevide... at gmail.com> wrote:
> > 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
> > object.
>
> WARNING-er: As Carl points out, adding a __del__ method actually makes
> it /less/ likely that your object will be cleaned up.

No I wasn't pointing that out, and I don't really agree with it.  (You
can't really say it is "more likely" or "less likely" without
considering the skill and patience of the programmer, and there are
many programmers who are up to the task.)

__del__ can succeed with care, and if you are willing to give up a
certain amount of flexibility and portability

I don't recommend going that way.  For one thing RAII isn't quite so
wonderful in Python's dynamic environment as it is in C++'s static
universe, and people seem to expect more from it than they get.
Second, relying on implementation-dependent behavior is not a good
thing and can set you up for problems later, something few people
expect to happen to them but it does more often than they think.
(Search comp.lang.python for a thread started by Warren DeLano for an
example of someone who got bit hard by such a change he should have
seen coming.)  But still I leave that for them to risk for themselves.


[snip]
> If you care enough about a resource to write a __del__ method
> you care enough to clean it up explicitly.  'with' blocks are very
> nice for that.

The OP already said with blocks won't suffice since the resources are
long-lived objects that aren't limited to a single scope.


Carl Banks



More information about the Python-list mailing list