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.py
print("a module imported")
Then
import sys
def 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) # True
def func2():
import a_module
func1() # a module imported
func2() # 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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…