How to clear all variables in a Python script

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
5 min

banner

# Table of Contents

  1. How to clear all variables in a Python script
  2. Using the globals() dictionary to clear all variables in a Python script
  3. Removing specific variables from a Python script
  4. Conditionally removing variables from a Python script
  5. Clearing all variables in Python by restarting the interpreter
  6. Save the context at a given point in time

# How to clear all variables in a Python script

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

main.py
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.

main.py
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'
The code for this article is available on GitHub
In Python, you have objects (e.g. classes, functions, modules, string literals, numbers, lists) and names that store specific objects.

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:

  • NameError: name 'X' is not defined

# Using the globals() dictionary to clear all variables in a Python script

You can also use the globals() dictionary to clear all variables in a Python script.

main.py
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.

main.py
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.

main.py
site = 'bobbyhadz.com' print(site) for name in dir(): if not name.startswith('_'): del globals()[name] print(str) # ๐Ÿ‘‰๏ธ <class 'str'> # โ›”๏ธ Not defined print(site)
The code for this article is available on GitHub

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.

# Removing specific variables from a Python script

If you only want to remove specific variables, use the del statement.

main.py
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.

# Conditionally removing variables from a Python script

You can also conditionally remove variables from a Python script:

  1. Use a for loop to iterate over the dir() list.
  2. Check if each attribute meets a certain condition.
  3. Use the delattr() method to delete the matching attributes.
main.py
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())

conditionally delete variables

The code for this article is available on GitHub

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.

main.py
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())

# Clearing all variables in Python by restarting the interpreter

You can also clear all variables in Python by restarting the interpreter.

For example, if you start the native Python interpreter by issuing python:

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

restart python interpreter to clear all variables

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.

main.py
site = 'bobbyhadz.com' %reset # โ›”๏ธ not defined print(site)

clear all variables using reset in jupyter notebook

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.

main.py
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.

main.py
from IPython import get_ipython site = 'bobbyhadz.com' get_ipython().magic('reset -f') # โ›”๏ธ not defined print(site)

using reset command with import statement

We passed the reset -f command to the magic() method.

The magic() method runs the given command.

# Save the context at a given point in time

You can also save the context at a given point in time and restore it later on in your code.

main.py
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 code for this article is available on GitHub

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.

  1. We first called the save_context() function to save the context at that point in time.
  2. We declared a site variable.
  3. We called the restore_context() function and the site variable got deleted.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev