Is there a way to delete created variables, functions, etc from the memory of the interpreter?

前端 未结 6 1950
春和景丽
春和景丽 2020-11-27 10:07

I\'ve been searching for the accurate answer to this question for a couple of days now but haven\'t got anything good. I\'m not a complete beginner in programming, but not y

6条回答
  •  醉酒成梦
    2020-11-27 10:52

    You can delete individual names with del:

    del x
    

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

提交回复
热议问题