272

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.

2

8 Answers 8

497

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

Sign up to request clarification or add additional context in comments.

9 Comments

sometimes this doesn't remove it entirely this only removes that reference to a in memory. This can leave ghost variables in memory that don't get gc.
del also has the disadvantage that if you try to delete a variable that doesn't exist it throws an exception, which is usually undesirable.
I just wanted to point out that if you accidentally declared a variable that is overwriting built in commands e.g., type=… when you meant to type type(…) then deleting it is the easiest way to get back the original functionality. That is, if you keep it around as None you will still be cutting off access to the underlying function.
Garbage Collection/Collector/Collected
This was the one I was looking for. Playing at the cmd line, I had ... set = set(myList) and then realized I could not use set anymore as a function (doh). Using del set allowed me to use it again as a fx. Of course I'd never use that reserved var in an actual script.
|
184

What's wrong with self.left = None?

10 Comments

Not familiar with the None keyword. Is this similar to null in other languages?
Yes; it is equivalent to null.
@Bnicholas However it's not like null in PHP, in that setting a variable to null in PHP gives you similar behaviour in most cases as if you hadn't defined it in the first place. A value of None in Python is quite different from an undefined variable. None is quite like most other incarnations of null, however (until we get into more arcane details, at least).
Open the python terminal and type print x and press enter. This will produce an interpreter error, as do most languages when you try to print an undefined variable. But if you define the variable, and then try to clear it with None, using the print x code will produce the word None as output. I'm new to python so I could be mistaken, but this does not seem like the behavior of a cleared variable.
This solution isn't the best solution. It just assigns it as null, but it still is a variable. If you were to overwrite keywords - then you would still get errors trying to call a none type. Use del variable
|
133

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.

1 Comment

What if I want to completely delete variable that in some circumstances does not exist. Is there any parameter to avoid an error? I need to delete several variables: del a, b, c, d I could use loop and try/except, but I prefer some switch to avoid it.
73

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

5 Comments

I don't understand why the =None answer is so popular. This is the correct answer
The OP said clear not remove. del will kill the attribute and lookups. It is way cleaner to set it to None, than you can check if self.left and that would be good enough to check if a node is empty.
"It is way cleaner to set it to None" -- it's worth considering that if someone (yourself some time later or a collaborator) is reading the code del, IMHO, makes it more obvious that the variable can be forgotten about when 'mentally parsing' the code.
@NikolayGromov in your day to day code, when you want to get the value of self.left do you prefer to check if self.left:, or do you prefer to deal with a possible NameError exception that will crash your program if you don't handle it everywhere ?
Check gcore $PID, your variable still exists in memory.
51
  • 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

Comments

6

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.

Comments

5

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

variable = None; del variable

Comments

0

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.