__del__ pattern?

BranoZ zarnovican at gmail.com
Mon Aug 15 10:34:04 EDT 2005


> So when my class is instantiated, I create a little lock file, and I
> have a __del__ method that deletes the lock file.  Unfortunately, there
> seem to be some circumstances where my lock file is not getting
> deleted.

Maybe the interpreter died by the signal.. in that case the __del__
is not called.

You can try 'flock', instead of lock files.

import fcntl

class Test1(object):

  def __init__(self):
    self.lock=open('/var/tmp/test1', 'w')
    fcntl.flock(self.lock.fileno(), fcntl.LOCK_EX)
    print 'Lock aquired!'

  def __del__(self):
    fcntl.flock(self.lock.fileno(), fcntl.LOCK_UN)
    self.lock.close()

In this case, if interpreter dies, the lock is released by OS.

If you try to create another instance in the same interpreter
or another, the call will block in __init__. You can change it to
raise an exception instead. 

BranoZ




More information about the Python-list mailing list