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() # 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
The sys module provides information about constants, functions and methods of the Python interpreter. dir(system) gives a summary of the available constants, functions and methods. Another possibility is the help() function. Using help(sys) provides valuable detail information.
The sys module in Python provides various functions and variables that are used to manipulate different parts of the Python runtime environment. It allows operating on the interpreter as it provides access to the variables and functions that interact strongly with the interpreter.
sys. modules is a dictionary containing all the modules that have ever been imported since Python was started; the key is the module name, the value is the module object. Note that this is more than just the modules your program has imported.
The purpose of __all__ is simply to define which symbols should be imported as part of a wildcard import that targets that module. If a symbol is importable through a wildcard import, it makes sense that it should be considered public.
What are modules in Python? Modules refer to a file containing Python statements and definitions. A file containing Python code, for example: example.py , is called a module, and its module name would be example . We use modules to break down large programs into small manageable and organized files.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With