How to delete every reference of an object in Python?

Juanjo Conti picture Juanjo Conti · Jun 10, 2010 · Viewed 20.5k times · Source

Supose you have something like:

x = "something"
b = x
l = [b]

How can you delete the object only having one reference, say x?

del x won't do the trick; the object is still reachable from b, for example.

Answer

abyx picture abyx · Jun 10, 2010

No no no. Python has a garbage collector that has very strong territory issues - it won't mess with you creating objects, you don't mess with it deleting objects.

Simply put, it can't be done, and for a good reason.

If, for instance, your need comes from cases of, say, caching algorithms that keep references, but should not prevent data from being garbage collected once no one is using it, you might want to take a look at weakref.