No, if you have a reference to an instance of the class, then by definition it has remaining references. You can use the del
keyword to delete a name (releasing the reference from that name to the object), but if a reference to the instance is held elsewhere, the instance remains.
If what you're going for is deterministic cleanup behavior, don't use __del__
(which is not deterministic in an obvious or consistent way, and prior to Python 3.4, could cause reference cycle leaks if any member of the cycle was an instance of a class that defined a __del__
finalizer). Have the class implement the context manager protocol, and use instances with with
statements to get deterministic cleanup; the instance will still exist until the last reference goes away, but as long as __exit__
performs the necessary release of resources, the empty shell of the instance costs you almost nothing.
As an example of context management, we'll make x
an instance attribute of foo
, not a class attribute, and we'll say we need ensure the instance's reference to x
goes away at a known time (note, because del
just deletes our reference, if someone else saved off a.x
, the object won't actually be freed until the other reference(s) are also released):
class foo(object):
def __init__(self, x):
self.x = x
print "hi"
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print "bye"
del self.x
with foo(123456789) as a:
print a.x # This works, because a.x still exists
# bye is printed at this point
print a.x # This fails, because we deleted the x attribute in __exit__ and the with is done
# a still exists until it goes out of scope, but it's logically "dead" and empty