Modules and imports · 6 / 16 Theory

__name__, sys.path and circular imports

To finish with modules, three pieces of the import mechanism that explain most strange errors.

__name__ and the execution guard

Every module has an internal name, __name__. If the file is run directly, it is "__main__"; if it is imported, it is the module name. The guard if __name__ == "__main__": makes some code run only in the first case.

print(__name__)     # __main__   (this file is being run as a program)
# Illustrative example: it needs real files, not run in the corrector.
# calculations.py
def double(x):
    return x * 2

if __name__ == "__main__":      # only if it is run: python calculations.py
    print(double(21))            # 42

# other.py
import calculations                 # prints NOTHING: __name__ is "calculations"
print(calculations.double(5))        # 10

Always use it for test code or the entry point: that way other files can import your functions without the program starting by itself. You practice it in Program or module.

sys.modules: the module cache

The first time a module is imported, Python runs its code and stores the result in the sys.modules dictionary. The following imports reuse that object without running anything again. That is why a print at the top of a module appears only once.

import sys
import types

mod = types.ModuleType("mydemo")
mod.greeting = lambda: "hello"
sys.modules["mydemo"] = mod        # "register" the module by hand

import mydemo                      # Python finds it in sys.modules
print(mydemo.greeting())             # hello
print("mydemo" in sys.modules)     # True

You reproduce that mechanism in Importing only once.

sys.path: where Python looks

When you run import x, Python looks first in sys.modules and then, in order, in the folders of the sys.path list: the script's folder, the PYTHONPATH paths and those of the installed packages. If the module is in none of them, ModuleNotFoundError occurs. A file of yours named like a standard module (for example random.py) hides it: do not use that name.

import sys

print(type(sys.path).__name__)     # list
print(len(sys.path) > 0)           # True

Circular imports

If a imports b and b imports a, each one needs the other before it is complete, and Python fails with an ImportError. It is a design problem, not a syntax error.

# Illustrative example: it needs real files, not run in the corrector.
# a.py
from b import f_b
def f_a(): return "a"

# b.py
from a import f_a           # ImportError: ... (most likely due to a circular import)
def f_b(): return "b"

# Usual solutions:
#  1) move the shared code to a third module that both import
#  2) import INSIDE the function that needs it
#  3) redesign: if two modules need each other, they may be one module

Before loading a set of modules you must decide an order in which each one is imported after its dependencies; if no such order exists, there is a cycle. You compute it in Import order.