TLDR: import
loads each module only once per interpreter session. However, the main module is special in that it can be imported in two variants.
The import
statement is responsible for two things:
- loading the target module into the interpreter, and
- binding the module or some of its name in the current scope.
Notably, if the module has already been loaded (it is in sys.modules
), the module is not loaded again. Only the name binding happens in this case.
This is why importing the module recursively does not rerun its code infinitely.
The main module, that is the initial module run, is special in that it can regularly exist with two variants:
- with the name
__main__
, set automatically by running the module, and
- with its own name such as
test
, set automatically by importing the module.
Notably, these two versions are not identical. Every module with an if __name__ == "__main__":
guard runs different code, and thus achieves different state.
This is why the __main__
module can be loaded twice, once under the name __main__
and once under its own name.
For this code in specific, the sequence is like this:
- Executing
python3 test.py
sets up test.py
to be imported as __main__
.
- There is no module
__main__
yet. Python executes test.py
to create the module.
functionA
and functionB
are defined,
print("t1")
is called,
functionA
is called,
import test
is run,
- There is no module
test
yet. Python executes test.py
to create the module.
functionA
and functionB
are defined,
print("t1")
is called,
functionA
is called,
import test
is run,
- The module
test
already exists (though not completely).
- Python binds the
test
module to the name test
.
print("a1")
is called,
print("m1")
is called,
print("a1")
is called,
print("m1")
is called,