[Tutor] __del__ exception

wesley chun wescpy at gmail.com
Thu Jun 5 23:59:31 CEST 2008


> class Person:
>         population = 0
>
>         def __init__(self, name):
>                 self.name = name
>                  print '%s has been added' %self.name
>                 Person.population += 1
>
>         def __del__(self):
>                 print '%s is leaving' % self.name
>                 Person.population -= 1
>                 print 'population = %d' %Person.population
>
> p = Person('Jean')
> d = Person('Michael')
>
> Output:
> Jean has been added
>  Michael has been added
> Michael is leaving
> population = 1
> Jean is leaving
> Exception exceptions.AttributeError: "'NoneType' object has no attribute
> 'population'" in <bound method Person.__del__ of <__main__.Person instance
> at 0xb7dadacc>> ignored
>
> So once all objects have been destroyed, an exception is triggered on class
> variable 'population'.

not quite.  if you look back carefully, the exception is really about
Person no longer existing, hence the reason why a get on
None.population fails.


> Any more logical explanation and work around? I just need to understand what
> python is doing here

it is generally recommended that people do *not* implement an
__del__() method, esp. if the program is exiting.  many people are
under the misconception that this method is called whenever an object
goes out-of-scope, but that may not necessarily be true... it is only
called when the reference count of the object goes to zero.  details
here:

http://docs.python.org/ref/customization.html

the sidebar boxes on this page also point out that when programs end,
exceptions are ignored in this method because some objects may have
already been deallocated by the time this code is reached, i.e.
Person, and are no longer available.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list