Reliable destruction

Benjamin Niemann pink at odahoda.de
Thu Aug 4 07:57:36 EDT 2005


Pierre-Eric.Melchy at uni-konstanz.de wrote:

> Hello,
> 
> I have a class measurement representing a physical measurement.
> Different objects in this class represent laboratory equipment, which
> might raise an exception (e.g. overtemperature).
> 
> In any case the equipment has to be switched off after the experiment,
> since if a
> power supply stays in the on state for a prolonged time equipment may
> be
> destroyed. Switching off is done by invoking the destructors of the
> instruments.
> 
> My measurement looks like this:
> 
> class measurement:
> def __init__(self):
> self.setup()
> self.run()
> 
> def setup(self):
> self.powerSupply=apparate.PowerSupply()
> self.magnet=apparate.magnet() # Exception("Communication Error")
> self.thermo=apparate.thermometer()
> # some 5 more instruments
> 
> def run():
> for i in range(100)
> self.powerSupply.setCurrent(i) # Exception("Overcurrent")
> self.magnet.setField(0.5*i)
> 
> 
> Different measurements are executed in a script which might run
> overnight:
> If one measurement raises an exception the next one might still work
> and I don't
> want to loose the results from the following experiments.
> 
> try:
> measurement()
> except:
> pass
> try:
> measurement2()
> except:
> pass
> 
> 
> An exception might be thrown anywhere in init or run if e.g. the
> PowerSupply
> overheats. Maybe an asynchronous event might happen, too (user
> interrupt with ^C but I might live without that if it is impossible to
> handle)
> 
> 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.

I would suggest an explicit tearDown() method

try:
    m = measurement()
    try:
        m.setup()
        m.run()
    finally:
        m.tearDown()
except KeyboardInterrupt:
    # user pressed ctrl-C
    print "***BREAK"
    sys.exit(1)
except:
    # you should at least log the exception for later debugging
    traceback.print_exc()

and remove the calls to setup() and run() from the constructor.

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/



More information about the Python-list mailing list