Python Forum
Delete all variables except few - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Delete all variables except few (/thread-30632.html)



Delete all variables except few - Robotguy - Oct-28-2020

Hello,

I know how to use del var1, var2,... to delete multiple variables. However, this is not handy when I have to delete several variables. Is there an alternative to delete all variables except the ones that interests me? In MATLAB one can use clearvars -except var1 var2 ... to delete every variable except var 1, var 2. Is there something similar in Python?

I tried the below but this gives me an error after its execution NameError: name 'numpy' is not defined probably because I will need to import the modules again. Any suggestions to delete multiple variables without naming all of them one-by-one?

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



RE: Delete all variables except few - buran - Oct-29-2020

Why do you need to delete variables? Python garbage collector will take care for variables no longer referenced