Last updated: Apr 11, 2024
Reading timeยท5 min
globals()
dictionary to clear all variables in a Python scriptUse the sys.modules
attribute to clear all variables in a Python script.
You can call the __dict__.clear()
method on the attribute to remove every
name from the current module.
import sys site = 'bobbyhadz.com' sys.modules[__name__].__dict__.clear() # โ๏ธ Not defined print(site)
The sys.modules[__name__].__dict__.clear()
line clears all variables in the
Python script.
However, the line also removes the built-in methods and classes, making them inaccessible in the script.
You can still technically access built-ins but it is a hassle.
import sys site = 'bobbyhadz.com' sys.modules[__name__].__dict__.clear() # ๐๏ธ accessing int() built-in int = (5).__class__ print(int('100')) # ๐๏ธ 100 # ๐๏ธ accessing str() built-in str = ''.__class__ print(str(100)) # ๐๏ธ '100'
When you run the sys.modules[__name__].__dict__.clear()
, you remove all names
from the module.
If all references to an object have been deleted, the object also gets removed.
If you try to access a variable after running the line, you get an error:
globals()
dictionary to clear all variables in a Python scriptYou can also use the globals()
dictionary to clear all variables in a Python
script.
site = 'bobbyhadz.com' print(site) globals().clear() print(str) # ๐๏ธ <class 'str'> # โ๏ธ Not defined print(site)
The globals function returns a dictionary that implements the current module namespace.
site = 'bobbyhadz.com' print(site) # {'site': 'bobbyhadz.com', '__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7feb7d2c1b10>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/borislav/Desktop/bobbyhadz_python/main.py', '__cached__': None, } print(globals()) globals().clear() # {} print(globals())
You can use the clear()
method to delete all keys from the dictionary.
If you don't want to remove the built-in attributes (ones starting and ending
with __
), use an if
statement.
site = 'bobbyhadz.com' print(site) for name in dir(): if not name.startswith('_'): del globals()[name] print(str) # ๐๏ธ <class 'str'> # โ๏ธ Not defined print(site)
We used a for
loop to iterate over the dir()
list.
On each iteration, we use the str.startswith method to check if the attribute doesn't start with an underscore
If the condition is met, we delete the attribute.
If you only want to remove specific variables, use the del statement.
site = 'bobbyhadz.com' # โ๏ธ Not defined # print(site) del site # โ๏ธ Not defined print(site)
The del
statement is most commonly used to remove an item from a list by an
index.
However, the del
statement can also be used to delete entire variables.
Trying to access the variable after it has been deleted causes a NameError
exception.
You can also conditionally remove variables from a Python script:
for
loop to iterate over the dir()
list.delattr()
method to delete the matching attributes.import sys site = 'bobbyhadz.com' for attr_name in dir(): if attr_name[0] != '_': delattr(sys.modules[__name__], attr_name) # ['attr_name', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] print(dir())
We used a for loop to iterate over the dir()
list.
The dir() function returns a list containing the module's attributes.
In the example, we check if each attribute doesn't start with an underscore _
.
If the condition is met, we use the delattr()
method to remove the attribute.
Names of built-in attributes usually start and end with two underscores.
Notice that the list also contains the name attr_name
because we declared a
variable with that name in the for
loop.
You can rename the variable in the for
loop to an underscore to indicate that
you don't intend to use it later on.
import sys site = 'bobbyhadz.com' for _ in dir(): if _[0] != '_': delattr(sys.modules[__name__], _) # ['_', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] print(dir())
You can also clear all variables in Python by restarting the interpreter.
For example, if you start the native Python interpreter by issuing python
:
python # or python python3 # Windows alias py
You can press Ctrl
+ D
or use the exit()
function to exit the interpreter
and start it again.
Once you exit the interpreter, use the python
command to start a new session
in which the variables from the previous session won't exist.
If you use Jupyter Notebook, you can clear all variables with the %reset
magic
command.
site = 'bobbyhadz.com' %reset # โ๏ธ not defined print(site)
The %reset
magic command resets the namespace by removing all names defined by
the user.
The command doesn't remove the built-in names.
When you issue the %reset
command you will get prompted whether you want to
delete all variables in the environment.
You can type y
and press enter to confirm or simply issue the %reset
command
with the -f
flag.
site = 'bobbyhadz.com' %reset -f # โ๏ธ not defined print(site)
Adding the -f
flag issues the %reset
command in non-interactive mode, so you
won't get prompted for confirmation.
You can also use the reset
command as follows.
from IPython import get_ipython site = 'bobbyhadz.com' get_ipython().magic('reset -f') # โ๏ธ not defined print(site)
We passed the reset -f
command to the magic()
method.
The magic()
method runs the given command.
You can also save the context at a given point in time and restore it later on in your code.
import sys __saved_context__ = {} def save_context(): __saved_context__.update(sys.modules[__name__].__dict__) def restore_context(): attr_names = list(sys.modules[__name__].__dict__.keys()) for attr_name in attr_names: if attr_name not in __saved_context__: del sys.modules[__name__].__dict__[attr_name] save_context() site = 'bobbyhadz.com' print(site) # ๐๏ธ bobbyhadz.com restore_context() # โ๏ธ Not defined print(site)
The save_context()
function saves the context (names) at the time the function
was called.
The function simply updates the __saved_context__
dictionary with the names
from the sys.modules
dictionary.
When the restore_context()
function is called, it deletes all names from the
sys.modules
dictionary that are not in the __saved_context__
dictionary.
save_context()
function to save the context at that
point in time.site
variable.restore_context()
function and the site
variable got
deleted.You can learn more about the related topics by checking out the following tutorials: