In a Python script, is there a command/function to delete all variables from the workspace, release them from the system memory, and clear all variables at some point.
Alibaba Cloud Simple Application Server: Anti COVID-19 SME Enablement Program
$300 coupon package for all new SMEs and a $500 coupon for paying customers.
The following sequence of commands does delete every name from the current module:
>>> import sys
>>> sys.modules[__name__].__dict__.clear()
I doubt if you actually want to do this, because "every name" contains all the built-in plugins, so there is nothing you can do after it is completely eliminated. Remember, there is really no such thing as "variables" in Python-there are objects, there are many kinds (including modules, functions, classes, numbers, strings...), and names, which are bound to objects The role of the sequence is to delete every name from the module (if and only if every reference to them is deleted, the corresponding object will disappear).
Maybe you want to be more selective, but unless you want to be more specific, it's difficult to guess exactly what you mean. But, to give an example:
>>> import sys
>>> this = sys.modules[__name__]
>>> for n in dir():
... if n[0]!='_': delattr(this, n)
...
>>>
This sequence only retains private or magic names, including the __builtins__ special name, which contains all built-in names. Therefore, the built-in functions are still valid-for example:
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'n']
>>>
As you can see, the name n (the control variable in the for) also happens to be (because it is rebound in the for clause every time), so it might be better to name the control variable _, for example, to clearly show " It is special" (in addition, in the interactive interpreter, the name_ is re-bound to the value of that expression anyway after each complete expression entered at the prompt, so it will not remain for a long time ;-) .
In any case, once you are sure what you want to do, it is not difficult to define a function for this purpose and place it in your startup file (if you only want to use it in an interactive session) or a website customization file ( If you want to use it in every script).