For efficiency\'s sake I am trying to figure out how python works with its heap of objects (and system of namespaces, but it is more or less clear). So, basically, I am tryi
The approximate sequence of steps that occurs when a module is imported is as follows:
Python tries to locate the module in sys.modules
and does nothing else if it is found. Packages are keyed by their full name, so while pymodule
is missing from sys.modules
, pypacket.pymodule
will be there (and can be obtained as sys.modules["pypacket.pymodule"]
.
Python locates the file that implements the module. If the module is part of the package, as determined by the x.y
syntax, it will look for directories named x
that contain both an __init__.py
and y.py
(or further subpackages). The bottom-most file located will be either a .py
file, a .pyc
file, or a .so
/.pyd
file. If no file that fits the module is found, an ImportError
will be raised.
An empty module object is created, and the code in the module is executed with the module's __dict__
as the execution namespace.1
The module object is placed in sys.modules
, and injected into the importer's namespace.
Step 3 is the point at which "objects get loaded into memory": the objects in question are the module object, and the contents of the namespace contained in its __dict__
. This dict typically contains top-level functions and classes created as a side effect of executing all the def
, class
, and other top-level statements normally contained in each module.
Note that the above only desribes the default implementation of import
. There is a number of ways one can customize import behavior, for example by overriding the __import__ built-in or by implementing import hooks.
1 If the module file is a .py
source file, it will be compiled into memory first, and the code objects resulting from the compilation will be executed. If it is a .pyc
, the code objects will be obtained by deserializing the file contents. If the module is a .so
or a .pyd
shared library, it will be loaded using the operating system's shared-library loading facility, and the init
C function will be invoked to initialize the module.