metaclasses
Alex Martelli
aleax at aleax.it
Thu Feb 27 05:29:02 EST 2003
Dmitri Mouromtsev wrote:
> Hello all!
>
> I've tried to override __del__ method for class object, but nothing to
> happen. Why? Does the __del__ method called when class object deleted or
> not?
Yes, but del doesn't delete an object, just a reference; the object
gets deleted only when all references to it disappear -- and classes
are referred to by other places. Watch...:
class MyMetaclass(type):
def __init__(cls, name, bases, dict):
super(MyMetaclass, cls).__init__(name, bases, dict)
print 'initialized', cls.__name__
def __del__(cls):
print 'deleted', cls.__name__
class MyClass(object):
__metaclass__ = MyMetaclass
class Sub(MyClass):
pass
del Sub
import gc,pprint
def isActuallySub(x):
return type(x) is MyMetaclass and x is not MyClass
a = [x for x in gc.get_objects() if isActuallySub(x)]
del x
referrers = [x for x in gc.get_referrers(a[0]) if x is not a]
print len(referrers),'still holding on to Sub...:'
pprint.pprint(referrers)
[alex at lancelot mydata]$ python ap.py
initialized MyClass
initialized Sub
1 containers still hold on to Sub...:
[(<class '__main__.Sub'>, <class '__main__.MyClass'>, <type 'object'>)]
[alex at lancelot mydata]$
So, object <class '__main__.Sub'> cannot be deleted because of
this reference to it. Exactly where this tuple comes from is
an interesting puzzle (I think it's object keeping track of all
of its subclasses, but that's just a guess), but in practice I
do think it means no class object is ever truly deleted...
Alex
More information about the Python-list
mailing list