How to Clear Variables in Python
Managing variables effectively is crucial for writing clean and efficient Python code.
This guide explores various techniques for clearing variables, discussing the use of globals()
, del
, delattr()
, restarting the interpreter, IPython's %reset
magic command and saving/restoring context. We'll cover the implications and caveats of each approach.
Clearing All Global Variables (with Caveats)
You can clear all global variables in the current module's namespace using sys.modules[__name__].__dict__.clear()
:
import sys
site = 'tutorialreference.com'
sys.modules[__name__].__dict__.clear()
try:
print(site) # Raises NameError
except NameError as e:
print(e) # Output: name 'site' is not defined
This approach also removes built-in functions and classes, making them inaccessible directly. While you can technically regain access, it's not recommended due to potential disruption of the interpreter. This approach is generally useful for testing or very specific use cases.
Clearing Global Variables with globals()
The globals()
function returns a dictionary representing the module's global namespace. Using .clear()
on this dictionary removes user-defined global variables:
site = 'tutorialreference.com'
print(site) # Output: tutorialreference.com
globals().clear()
try:
print(site) # Raises NameError because it is removed from globals
except NameError as e:
print(e) # Output: name 'site' is not defined
print(str) # Output: <class 'str'> (built-in objects are preserved)
Built-in objects (like str
, int
, etc.) are not removed.
Preserving Built-in Attributes
To avoid removing built-in attributes (those starting with _
), use a loop and conditional check:
site = 'tutorialreference.com'
print(site) # Output: tutorialreference.com
for name in list(globals()): # Create a copy to avoid RuntimeError
if not name.startswith('_'):
del globals()[name]
try:
print(site)
except NameError as e:
print(e) # Output: name 'site' is not defined
print(str) # Output: <class 'str'> (built-in objects are preserved)
Removing Specific Variables with del
For targeted variable removal, use the del
statement:
site = 'tutorialreference.com'
del site
try:
print(site) # Raises NameError because it was deleted.
except NameError as e:
print(e) # Output: name 'site' is not defined
- This is useful when memory needs to be managed.
Conditionally Removing Variables with delattr()
Use delattr()
with sys.modules
for conditional removal:
import sys
site = 'tutorialreference.com'
for name in list(globals()):
if not name.startswith('_'):
del globals()[name]
try:
print(site) # Raises NameError, since it was deleted
except NameError as e:
print(e) # Output: name 'site' is not defined
print(str) # Output: <class 'str'> (built-in objects are preserved)
Clearing Variables by Restarting the Interpreter
Restarting the interpreter (or kernel in Jupyter/IPython) completely clears all variables and resets the environment.
Clearing Variables in Jupyter/IPython with %reset
In Jupyter Notebook or IPython, use the %reset
magic command to clear all user-defined variables.
site = 'tutorialreference.com'
%reset
# Output: Once deleted, variables can not be recovered. Proceed (y/[n])?
print(site) # Raises NameError since variable was removed.
- Respond to the confirmation prompt by typing
y
and pressingEnter
.
Using %reset
in Non-interactive Mode
To remove variables without confirmation, use the -f
flag:
site = 'tutorialreference.com'
%reset -f
print(site) # Raises NameError since variable was deleted
- The
-f
flag (force) avoids the confirmation question.
Using %reset
Programmatically with magic()
from IPython import get_ipython
site = 'tutorialreference.com'
get_ipython().magic('reset -f')
print(site) # Output: NameError, since the variable is no longer defined.
- This avoids manual intervention during execution.
Saving and Restoring Context
For complex scenarios, you can save a context of namespace using sys.modules
:
import sys
saved_context = {}
def save_context():
saved_context.update(sys.modules[__name__].__dict__)
def restore_context():
current_context = sys.modules[__name__].__dict__
for name in list(current_context.keys()):
if name not in saved_context:
del current_context[name]
save_context()
site = 'tutorialreference.com'
print(site) # Output: tutorialreference.com
restore_context()
try:
print(site) # Raises NameError because the variable has been removed.
except NameError as e:
print(e) # Output: name 'site' is not defined