As everyone knows, you can do del sys.modules[module]
to delete an imported module. So I was thinking: how is this different from rewriting sys.modules
? An interesting fact is, rewriting sys.modules
can't truely delete a module.
# a_module.pyprint("a module imported")
Then
import sysdef func1(): import a_module # del sys.modules['a_module'] sys.modules = { k: v for k, v in sys.modules.items() if 'a_module' not in k} print('a_module' not in sys.modules) # Truedef func2(): import a_modulefunc1() # a module importedfunc2() # no output here
If I use del sys.modules['a_module']
, calling func2()
also prints a module imported
, which implies that a_module
is successfully deleted.
My question is: What does del sys.modules[module]
actually do, besides changing the dictionary?