How to delete object assigned to variable?

Viewed 790

I have the following code:

class Node:
  def __init__(self, item):
    self.item = item  

node1 = Node(12)
cur = node1

Is it possible to delete node1using cur?

I tried del cur but it doesn't give the desired outcome cur now no longer exists but node1 still does.

Any help appreciated.

2 Answers

Let's clear a misconception: objects are not "assigned" in Python.

Variables are merely a reference to a location in memory that happens to contain values.

By doing del cur you are only making sure that cur does not reference the memory location that node1 also refers to, but nothing will happen to node1.

Check out this visualization. Note how both node1's and cur's arrows point to the same Node object's location in memory. If you click on "Forward" you will see that when del cur is executed the only thing that happens is that cur's arrow will be removed (ie cur will no longer reference the same location in memory that node1 references).

There is no way to do the same for node1 without doing del node1, and even then it is up to the garbage collector to decide when to delete the Node object itself (which will actually free up the memory it takes). This depends on the specific implementation of the Python interpreter, but this is usually done with reference-counting.

See these 2 off-site resources for useful info:

Python's garbage collector and Facts and myths about Python names and values

in addition to DeepSpace answer, there is no way to delete node1 except that you find all variables that refer to that instance, then delete it, I came up with a function to use instead of del for your purpose:

import sys

def kill(name):
    l = []
    for k, v in sys.modules[__name__].__dict__.items():
        if str(v) == str(name):  # Finding all vars that refers to that instace
            l.append(k)

    for i in l:  # Deleting them
        del sys.modules[__name__].__dict__[i]

so, if you have this class

class Node:
    def __init__(self, item):
        self.item = item  

node1 = Node(12)
cur = node1

if you type:

kill(cur)

node1 and all of the others that is referring to that instance will be deleted.

testing:

In [116]: node1
Out[116]: <__main__.Node at 0x7f68eca386d8>

In [117]: cur
Out[117]: <__main__.Node at 0x7f68eca386d8>

In [118]: kill(cur)

In [119]: cur
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-119-3c1cfaee77de> in <module>()
----> 1 cur

NameError: name 'cur' is not defined

In [120]: node1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-120-d9e9a8ca6efc> in <module>()
----> 1 node1

NameError: name 'node1' is not defined
Related