Remove all variables python

How to delete or clear variable from memory in Python?

Computer memory is very important not just for storing data, code and instructions but also for the system’s performance. Variables are the simplest and most basic storage units. You must be knowing that Python variables are dynamically typed, i.e, they are declared as and when they are assigned/used.

Sometimes, even though you assigned a variable with some value in the program, you may realize later that that variable is not necessary. In such a scenario, you will want to delete that variable both from your program as well as your memory.
In this tutorial, you will understand how to delete a variable from the memory space in Python.

The del keyword

It is used to simply delete any Python object. (variables,arrays,lists,dictionaries etc).
Syntax: del(element to be deleted)

You can look into the below-coded example to understand this better.

Example 1: Deleting a variable

--------------------------------------------------------------------------- NameError Traceback (most recent call last) in  2 print(a) 3 del(a) ----> 4 print(a) NameError: name 'a' is not defined

Note: The del method can be used not just with variables but with all Python objects like arrays, lists, dictionaries etc.

Example 2: Deleting a list

--------------------------------------------------------------------------- NameError Traceback (most recent call last) in  2 print(a) 3 del(a) ----> 4 print(a) NameError: name 'a' is not defined

In this case, the program returns a NameError exception. This is because the variable you are trying to access no longer exists in the variable namespace.

However, the above del method only removes the variable from the namespace. It does not remove the variable from the memory space.

Well, so how do we permanently remove the variable and clear its memory?

The gc.collect() method in Python

The del method does not clear the variable from the memory. Hence, to clear the variable from memory you can resort to the gc.collect() method.
The gc.collect() method forces an immediate garbage collection of all generations. You can invoke the garbage collector as demonstrated below.

Example 1: Deleting a variable

import gc a=10 print(a) del(a) gc.collect() print(a)
NameError Traceback (most recent call last) in  4 del(a) 5 gc.collect() ----> 6 print(a) NameError: name 'a' is not defined

In this case, you are deleting a from the memory space itself.

Just like the del method, you can invoke the gc.collect() for clearing the memory of not just variables but for all Python objects.

Example 2: Deleting a dictionary

import gc a= print(a) del(a) gc.collect() print(a)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) in  4 del(a) 5 gc.collect() ----> 6 print(a) NameError: name 'a' is not defined

Thus, you can use a combination of del() and gc.collect() to clear the variable from Python memory.

On a side note, though not very relevant, you can use the dir() method to get a list of the names of all the objects in the current scope.

['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_i', '_i7', '_ii', '_iii', 'a']
a = 5 print(dir()) del a print(dir())
['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_i', '_i10', '_i9', '_ii', '_iii', 'a'] ['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_i', '_i10', '_i9', '_ii', '_iii']

Источник

Remove all variables python

Last updated: Jun 19, 2023
Reading time · 5 min

banner

# Table of Contents

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

Copied!
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.

Copied!
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'

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:

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

Copied!
site = 'bobbyhadz.com' print(site) globals().clear() print(str) # 👉️ # ⛔️ Not defined print(site)

The globals function returns a dictionary that implements the current module namespace.

Copied!
site = 'bobbyhadz.com' print(site) # , '__spec__': None, '__annotations__': <>, '__builtins__': , '__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.

Copied!
site = 'bobbyhadz.com' print(site) for name in dir(): if not name.startswith('_'): del globals()[name] print(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.

# Removing specific variables from a Python script

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

Copied!
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.
Copied!
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

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.

Copied!
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 :

Copied!
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.

Copied!
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.

Copied!
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.

Copied!
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.

Copied!
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.

  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.

Источник

Читайте также:  Php settings allow url fopen
Оцените статью