module name in sys.modules and globals()
If I import a module, the module name shows up in both sys.modules
and globals()
. If I again delete it, it is removed from globals()
, but still resides in sys.modules
. Why is it so?
import mymodule
'mymodule' in globals() # True
'mymodule' in sys.modules # True
del mymodule
'mymodule' in globals() 开发者_如何学C # False
'mymodule' in sys.modules # Still True, why?
I also found the following difference:
from mypackage import mymodule
'mypackage' in sys.modules # True
'mymodule' in sys.modules # False !
'mypackage.mymodule' in sys.modules # also True !
while the answers are complementary for globals()
:
'mypackage' in sys.modules # False
'mymodule' in sys.modules # True
'mypackage.mymodule' in sys.modules # False
Just like any other Python object, a module continues to exist until there are no more references to it. In other words, sys.modules
behaves like a regular dict, and
import mymodule
lst = {mymodule.__name__: mymodule}
'mymodule' in globals() # True
'mymodule' in lst # True
del mymodule
'mymodule' in globals() # False
'mymodule' in lst # Still True
sys.modules
is only consulted on import statements. You can delete a module from sys.modules
to make Python reload it the next time it is imported.
del
removes the binding of a name in the appropriate scope; it has nothing to do with modules per se.
sys.modules
keeps a list of all modules that have been loaded, regardless of whether they're bound to any name in your program.
Because Python caches modules in sys.modules
to prevent the (expensive, slow) module-finding process being run more than is necessary.
It is OK to remove the module from sys.modules
if you need to, although reload
may also work.
In more detail, when you import mymodule
various things happen. Off the top of my head, and assuming mymodule
isn't one of the modules built in to the interpreter executable:
The interpreter runs some complex code to locate the file containing
mymodule
(this may bemymodule.py
,mymodule.pyc
, ormymodule.pyd
-- or maybe something else that I haven't thought of. This looks through the current directory, sys.path, and other places too.The file thus located is lexed, parsed, and compiled (if necessary) into interpreter bytecodes.
The compiled module is executed, giving a module object.
The module object is inserted into sys.modules.
The module object is bound to the local variable specified in the
import
statement.
(The above is a very rough approximation based on what I remember about the mechanics behind import
. It's probably wrong in important and subtle ways.)
Note, then, that binding the module object to the local name is actually quite a small part of the actual import process. Removing the name binding, by executing del mymodule
, doesn't affect the rest of the import.
精彩评论