Bnicholas
Bnicholas

Reputation: 14121

Clear variable in python

Is there a way to clear the value of a variable in python?

For example if I was implementing a binary tree:

class Node:
    self.left = somenode1
    self.right = somenode2

If I wanted to remove some node from the tree, I would need to set self.left to empty.

Upvotes: 269

Views: 818870

Answers (8)

Brian Jack
Brian Jack

Reputation: 478

For a collection like a binary tree it is best, for consistency (for a binary tree, 'has left and right links' is a fairly strong interface contract obligation), to only clear the target of a link and not the link itself. It adds additional complexity to iterators during future maintenance if one must check for nonexistent attributes in addition to the target of the link being empty.

For this case, a binary tree, it is better to just set the target of the link to None with either self.left=None or self.right=None when children do not exist in their respective slots.

In contrast, one possible use for del is when a local variable needs to hold some temporary (emphasis on temporary) value whose scope should only be the next few lines or so. We could use a nested function (or in this case creating a general purpose swap method would be preferred) but in a pinch we can just del the temporary when we are done with it:

# swap two things
temp=collection[a]
collection[a]=collection[b]
collection[b]=temp
del temp

If we don't use del temp there is a second reference to the thing at collection[a] and we might get surprised down the line in the case we don't use temp later in the current scope but do expect some backend ref-counter to remove the thing in collection[a] after del collection[a], collection.pop(a,None) (discarding the return value) or collection[a]=None but the backend still registers that thing still exists (because it does, in temp).

Upvotes: 0

Umair Ayub
Umair Ayub

Reputation: 21231

Delete its contents by setting it to None and then del to remove its pointer from memory

variable = None; del variable

Upvotes: 5

Federico Migueletto
Federico Migueletto

Reputation: 158

Do you want to delete a variable, don't you?

ok, I think I've got a best alternative idea to @bnaul's answer:

You can delete individual names with del:

del x

or you can remove them from the globals() object:

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.

Modules you've imported (like import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.

Upvotes: 5

U13-Forward
U13-Forward

Reputation: 71570

  • If want to totally delete it use del:

    del your_variable
    
  • Or otherwise, to make the value None:

    your_variable = None
    
  • If it's a mutable iterable (lists, sets, dictionaries, etc, but not tuples because they're immutable), you can make it empty like:

    your_variable.clear()
    

Then your_variable will be empty

Upvotes: 51

starrify
starrify

Reputation: 14731

The del keyword would do.

>>> a=1
>>> a
1
>>> del a
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

But in this case I vote for self.left = None

Upvotes: 494

bnaul
bnaul

Reputation: 17636

What's wrong with self.left = None?

Upvotes: 183

user11788
user11788

Reputation: 1695

var = None "clears the value", setting the value of the variable to "null" like value of "None", however the pointer to the variable remains.

del var removes the definition for the variable totally.

In case you want to use the variable later, e.g. set a new value for it, i.e. retain the variable, None would be better.

Upvotes: 133

Viraj Shah
Viraj Shah

Reputation: 982

Actually, that does not delete the variable/property. All it will do is set its value to None, therefore the variable will still take up space in memory. If you want to completely wipe all existence of the variable from memory, you can just type:

del self.left

Upvotes: 72

Related Questions