Deleting all variables in python

Clear variable in python

Is there a way to clear the value of a variable in python? For example if I was implementing a binary tree:

class Node: self.left = somenode1 self.right = somenode2 

7 Answers 7

>>> a=1 >>> a 1 >>> del a >>> a Traceback (most recent call last): File "", line 1, in NameError: name 'a' is not defined 

But in this case I vote for self.left = None

sometimes this doesn’t remove it entirely this only removes that reference to a in memory. This can leave ghost variables in memory that don’t get gc.

del also has the disadvantage that if you try to delete a variable that doesn’t exist it throws an exception, which is usually undesirable.

I just wanted to point out that if you accidentally declared a variable that is overwriting built in commands e.g., type=… when you meant to type type(…) then deleting it is the easiest way to get back the original functionality. That is, if you keep it around as None you will still be cutting off access to the underlying function.

@JakobBowyer May I ask how you know this? Reading this makes me quite paranoid about how many other importances in programming are still unknown-unknowns to me

What’s wrong with self.left = None ?

@Bnicholas However it’s not like null in PHP, in that setting a variable to null in PHP gives you similar behaviour in most cases as if you hadn’t defined it in the first place. A value of None in Python is quite different from an undefined variable. None is quite like most other incarnations of null , however (until we get into more arcane details, at least).

Open the python terminal and type print x and press enter. This will produce an interpreter error, as do most languages when you try to print an undefined variable. But if you define the variable, and then try to clear it with None, using the print x code will produce the word None as output. I’m new to python so I could be mistaken, but this does not seem like the behavior of a cleared variable.

This solution isn’t the best solution. It just assigns it as null, but it still is a variable. If you were to overwrite keywords — then you would still get errors trying to call a none type. Use del variable

var = None «clears the value», setting the value of the variable to «null» like value of «None», however the pointer to the variable remains.

del var removes the definition for the variable totally.

In case you want to use the variable later, e.g. set a new value for it, i.e. retain the variable, None would be better.

Читайте также:  Universal selector in css

What if I want to completely delete variable that in some circumstances does not exist. Is there any parameter to avoid an error? I need to delete several variables: del a, b, c, d I could use loop and try/except, but I prefer some switch to avoid it.

Actually, that does not delete the variable/property. All it will do is set its value to None , therefore the variable will still take up space in memory. If you want to completely wipe all existence of the variable from memory, you can just type:

The OP said clear not remove . del will kill the attribute and lookups. It is way cleaner to set it to None, than you can check if self.left and that would be good enough to check if a node is empty.

«It is way cleaner to set it to None» — it’s worth considering that if someone (yourself some time later or a collaborator) is reading the code del , IMHO, makes it more obvious that the variable can be forgotten about when ‘mentally parsing’ the code.

@NikolayGromov in your day to day code, when you want to get the value of self.left do you prefer to check if self.left: , or do you prefer to deal with a possible NameError exception that will crash your program if you don’t handle it everywhere ?

Then your_variable will be empty

Do you want to delete a variable, don’t you?

ok, I think I’ve got a best alternative idea to @bnaul’s answer:

You can delete individual names with del :

or you can remove them from the globals() object:

for name in dir(): if not name.startswith('_'): del globals()[name] 

This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.

Modules you’ve imported (like import os ) are going to remain imported because they are referenced by sys.modules ; subsequent imports will reuse the already imported module object. You just won’t have a reference to them in your current global namespace.

Источник

Deleting all variables in 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.

Читайте также:  Java date and sql datetime

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.

Источник

Оцените статью