How to Delete Variables & Functions From Memory in Python

Functions and variables a put into memory when they are defined. When they are no longer in use, Python will automatically remove this data to save memory.

 

It is also possible to manually delete variables and functions from memory in Python, which we will look at in this tutorial.

 

Delete a Single Variable or Function

Use the Python del statement to remove a variable or function from memory. Pass the name of the item to remove after the del statement like this:

 

number = 1

del number

print(number)
NameError: name 'number' is not defined

 

Delete all User Defined Objects

The Python dir() function returns all the objects defined in a Python program. If the name of the object doesn't begin with __ (two underscores) then it is a user-defined object.

 

number = 1

print(dir())
['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'number']

 

To delete all user-defined objects, loop through the result of the dir() function, check that the object doesn't begin with two underscores then delete it using del globals()[element_name]

 

number = 1

for element in dir():
   if element[0:2] != "__":
       del globals()[element]

del element
print(dir())
['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']