File Unlocking in __del__ does not work

Terry Reedy tjreedy at udel.edu
Wed Nov 10 10:54:04 EST 2004


"schwerdy" <schwerdy at web.de> wrote in message 
news:c498bc9a.0411100344.34703bfa at posting.google.com...
> #***************************************************
> import sys, time
> from fcntl import *
> class Log(object):
>    """
>    Very Simple Logger Class
>    """
>    def __init__(self, path):
>        self.logfile = open(path, 'a')
>        flock(self.logfile, LOCK_EX | LOCK_NB) # throw exept. if file
> locked
>
>    def write(self, msg):
>        self.logfile.write(time.strftime('%Y-%m-%d %H:%M:%S : ') +
> str(msg) + '\n')
>        self.logfile.flush()
>
>    def __del__(self):
>        flock(self.logfile, LOCK_UN)
>        self.logfile.close()
>
>
> l = Log('/var/log/myagi.log')
> log = l.write
>
> log("bla")
> #***************************************************
>
> When I run the script, python says "Exception exceptions.TypeError:
> "'NoneType' object is not callable" in <bound method Log.__del__ of
> <__main__.Log object at 0x401e238c>> ignored"
> It seems, as in the __del__ method, the flock function has gone (a
> debug line as "print flock" in the __del__ method prints "None").
>
> does anybody know what is going on?

A wild guess: your quoted script does not explicitly delete instance l and 
method log (which contains an bound reference to the same object). 
Therefore, the object will only be deleted and __del__ invoked as part of 
the shutdown cleanup process.  In the absence of explicitly registered 
cleanup functions, cleanup happens in arbitrary implementation and 
version-specific order.  It just happens that flock is None'ed before l. 
So what happens if you do do an explicit 'del l,log' at the end of your 
script?

Note: on Jython, even explicit delete is not enough to trigger the __del__ 
method.  Better to rename __del__ as 'close' and call l.close() to release 
the resources.

Terry J. Reedy






More information about the Python-list mailing list