Order of object cleanup at interpreter exit?
Michael Hudson
mwh21 at cam.ac.uk
Mon Feb 14 04:44:53 EST 2000
rob at hooft.net (Rob W. W. Hooft) writes:
> I am writing a package (98% python) that controls an analytical robot.
> The robot is controlled via a simple text protocol over a socket
> connection.
>
> When the robot control object is garbage-collected, the __del__ method
> takes care of a proper termination of the socket connection by sending
> a last "EXIT" command:
>
> def sendfixed(sock,data):
> l=0
> while l<len(data):
> l=l+sock.send(data[l:])
>
> class Robot:
> def __del__(self):
> if self.status>0:
> sendfixed(self.sock1,'EXIT')
> self.status=-1
>
>
> I have noticed that this does not work if the __del__ method is called
> when the interpreter is exiting (i.e., when I am using a Robot() object
> in the __main__ module at the global scope). I get:
>
> Exception exceptions.TypeError: 'call of non-function (type None)' in
> <method Robot.__del__ of Robot instance at 81c8778> ignored
>
> And indeed, it seems that the "sendfixed" function was already garbage
> collected: "print sendfixed" just before the call reports "None"....
>
> I was not aware that it was "illegal" to call a function from a destructor.
> Is this a strange caveat? Bug? Feature? Any way to avoid it?
Try this:
def __del__(self,sendfixed=sendfixed):
if self.status>0:
sendfixed(self.sock1,'EXIT')
self.status=-1
That way, sendfixed shouldn't get collected before the instance
object.
Maybe a FAQ entry, except it's not very F Aed.
HTH,
Michael
More information about the Python-list
mailing list