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.pysets uptest.pyto be imported as__main__.
- There is no module __main__yet. Python executestest.pyto create the module.
- functionAand- functionBare defined,
- print("t1")is called,
- functionAis called,- 
- import testis run,- 
- There is no module testyet. Python executestest.pyto create the module.
- functionAand- functionBare defined,
- print("t1")is called,
- functionAis called,
- import testis run,- 
- The module testalready exists (though not completely).
- Python binds the testmodule to the nametest.
 
- print("a1")is called,
 
- print("m1")is called,
 
- print("a1")is called,
 
- print("m1")is called,