Why won\'t this work? I\'m trying to make an instance of a class delete itself.
>>> class A():
def kill(self):
del self
>>>
I think I've finally got it!
NOTE: You should not use this in normal code, but it is possible.
This is only meant as a curiosity, see other answers for real-world solutions to this problem.
# NOTE: This is Python 3 code, it should work with python 2, but I haven't tested it.
import weakref
class InsaneClass(object):
_alive = []
def __new__(cls):
self = super().__new__(cls)
InsaneClass._alive.append(self)
return weakref.proxy(self)
def commit_suicide(self):
self._alive.remove(self)
instance = InsaneClass()
instance.commit_suicide()
print(instance)
# Raises Error: ReferenceError: weakly-referenced object no longer exists
When the object is created in the __new__ method, the instance is replaced by a weak reference proxy and the only strong reference is kept in the _alive class attribute.
Weak-reference is a reference which does not count as a reference when the garbage collector collects the object. Consider this example:
>>> class Test(): pass
>>> a = Test()
>>> b = Test()
>>> c = a
>>> d = weakref.proxy(b)
>>> d
# The weak reference points to the Test() object
>>> del a
>>> c
<__main__.Test object at 0x10670f390> # c still exists
>>> del b
>>> d
# d is now only a weak-reference to None. The Test() instance was garbage-collected
So the only strong reference to the instance is stored in the _alive class attribute. And when the commit_suicide() method removes the reference the instance is garbage-collected.