Exception error when accessing the class variable at the termination of the program

Duncan Booth duncan.booth at invalid.invalid
Mon Feb 2 04:37:21 EST 2009


jwalana at vsnl.net wrote:

>  Can someone please explain why the exception happens in the case
>  where there is no explicit del statement? 

When Python is ecleaning up as it exits, it clears all the global 
variables in each module by setting them to None. This happens in an 
arbitrary and unpredictable order: in this particular case it set Person 
to None before setting x2 to None.

If you must have a __del__ method on a class then you should take care 
not to access any globals from inside the __del__ method (or any 
function it calls). Alternatively you could just catch and ignore any 
exceptions thrown from your __del__ method.

In the example you gave, provided you never subclass Person you could 
use self.__class__.Count to access your class variable. However in many 
cases you'll probably find that a much better solution is to use weak 
references. e.g. a WeakValueDictionary mapping id(self) to self:

from weakref import WeakValueDictionary

class Person:
    _instances = WeakValueDictionary()

    def __init__(self, name):
        self.name = name
        self._instances[id(self)] = self
        print name, 'is now created'

    @property
    def Count(self):
        return len(self._instances)

    def __del__(self):
        print self.name, 'is now deleted'
        if self.Count==0:
            print 'The last object of Person class is now deleted'
        else:
            print 'There are still', self.Count, 'objects of class 
Person'

x2 = Person('Krishna')
# del x2


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list