Is it possible to remove (rather than just disable) a class?
Suppose I am defining a class.
>>> class A(object):
>>> pass
Then I want to remove this class. I can use del
to detach it from a variable A
.
>>> del A
>>> A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined
But del
it doesn't actually remove the class itself. I can tell this because it is still subclassed object
.
>>> object.__subclasses__()
[..., <class '__main__.A'>]
I don't think this will work, but ...
>>> del object.__subclasses__()[-1]
>>> object.__subclasses__()
[..., <class '__main__.A'>]
Is there a way to remove the class in such a way that it is no longer in object.__subclasses__()
?
source to share
Weak links A
will not follow you del A
. One of the reasons this is needed is to allow circular references without preventing garbage collection. Try this to see what is still referencing it (this is python interpreter specific, may be different if you run the script file):
>>> class A(object):
... pass
...
>>> A
<class '__main__.A'>
>>> del A
>>> A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined
>>> object.__subclasses__()[-2]
<class '__main__.A'>
>>> # using weakref
>>> import weakref
>>> weakref.getweakrefs(object.__subclasses__()[-2])
[<weakref at 0x800fa4ba8; to 'type' at 0x800f9d420 (A)>]
>>> # Another method using gc to see the referrers:
>>> import gc
>>> gc.collect()
>>> gc.get_referrers(object.__subclasses__()[-2])
[<__main__.A object at 0x800face90>, (<class '__main__.A'>, <type 'object'>), <attribute '__dict__' of 'A' objects>, <attribute '__weakref__' of 'A' objects>]
>>> # See the referents
>>> print '\n'.join(map(str, gc.get_referents(object.__subclasses__()[-2])))
{'__dict__': <attribute '__dict__' of 'A' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
(<class '__main__.A'>, <type 'object'>)
(<type 'object'>,)
<type 'object'>
Additional information on the topic:
http://pymotw.com/2/weakref/
https://docs.python.org/2/library/gc.html
https://docs.python.org/2.7/library/weakref.html
https: // www.python.org/dev/peps/pep-0205/
https://docs.python.org/release/2.6.4/library/stdtypes.html#class. subclasses
source to share
You can use gc.collect after removal:
del A
from gc import collect
collect()
print( object.__subclasses__())
source to share