Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete every reference of an object in Python?

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.

like image 270
Juanjo Conti Avatar asked Jun 10 '10 09:06

Juanjo Conti


2 Answers

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.

like image 79
abyx Avatar answered Sep 18 '22 00:09

abyx


The only solution I see right now is that you should make sure that you are holding the only reference to x, everyone else must not get x itself but a weak reference pointing to x. Weak references are implemented in the weakref module and you can use it this way:

>>> import weakref
>>> class TestClass(object):
...     def bark(self):
...         print "woof!"
...     def __del__(self):
...         print "destructor called"
...
>>> x = TestClass()
>>> b = weakref.proxy(x)
>>> b
<weakproxy at 0x7fa44dbddd08; to TestClass at 0x7fa44f9093d0>
>>> b.bark()
woof!
>>> del x
destructor called
>>> b.bark()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ReferenceError: weakly-referenced object no longer exists

However, note that not all classes can be weak-referenced. In particular, most built-in types cannot. Some built-in types can be weak-referenced if you subclass them (like dict), but others cannot (like int).

like image 29
Tamás Avatar answered Sep 21 '22 00:09

Tamás