Reliable destruction

Raymond Hettinger python at rcn.com
Thu Aug 4 20:24:16 CEST 2005


[Pierre-Eric.Melchy at uni-konstanz.de]
> My questions are:
> 1) under normal conditions (no exceptions) is there a guarantee, that
> __del__ of
> all instruments is called at the end of measurement()?
>
> 2) if an exception is thrown, will all instruments be deleted if the
> error
> occurs in run() ?
> (only the instruments already initialized if the error occurs
> in setup() )?
>
> I am using CPython (on WinXP) and there are no reference cycles between
> the instruments.
>
> I have to stress again that a reliable finalization is important and
> cannot wait
> until the interpreter shuts down.
>
> I have tried this and it seems to work but this is of course no
> guarantee.

On the plus side, Python does guarantee destruction in the absence of
cycles when the last reference disappears.  If there is a cycle, you
have to wait for GC.  If you can't wait, then schedule a gc.collect()
to run periodically.

On the minus side, this is a somewhat brittle and error-prone design
strategy.  A single, accidental persistent reference is sufficient to
cause failure -- that is a land-mine for all future maintainers of your
code.  It is better to make explicit tear-down calls and to wrap
finalization is a try/finally suite.

The simplified code in your post suggests that the instrument shut-off
can be placed at the end of the run() method -- loosely translated as
turn-off the lights when you're done.

An alternative strategy is to periodically poll resources and shut them
off if they are not in use -- loosely translated as having a security
guard turn-off any coffee-pots that were left on by frazzled
programmers as they leave at odd hours of the night.


Raymond




More information about the Python-list mailing list