Playground / What import Really Does

Import a module twice and see what runs

What import Really Does

Interactive lab

Try it: What import Really Does

What happens on import: Python checks sys.modules, searches sys.path in order (first match wins), creates the module object, runs its top level once, then binds a name — the module, one function, or an alias — in the importing namespace; plus packages, __name__ == "__main__", ModuleNotFoundError and ImportError.

How it works

  1. If the name is already in sys.modules, reuse that module object: its code does not run again.
  2. Otherwise search each sys.path entry in order (the script's folder first); the first match wins, none raises ModuleNotFoundError.
  3. Create an empty module object, store it in sys.modules, then run the file's top level once (its __name__ is the module name, so a __main__ guard is skipped).
  4. import m binds m to the module; import m as x binds x; from m import f binds only f (ImportError if m has no f).
  5. A package runs its __init__.py first; submodules are found on the package's __path__ and become attributes of the package.

Default run (19 steps): $ python main.py — sys.path starts as [/project, /venv/site-packages, /usr/lib/python3.12]: the script's folder, then site-packages, then the standard library. Only our own modules are shown in sys.modules below. … Done. Printed: helpers loaded, __name__ = helpers | Hi Ann | Hi Ann.

Simplified: A fixed virtual project (main.py, helpers.py, pkg/, a site-packages folder and a one-file stand-in for the standard library). Built-in and frozen modules, .pyc caching, relative imports and namespace packages are not modelled; only our own modules are listed in sys.modules.

Educational simulation

Loading the simulation…