Learning navigation

Code with Animation

Modules, Imports & the __main__ Guard

Understand Python module system: module execution lifecycle, the sys.path search hierarchy, namespace isolation, circular import hazards, and the if __name__ == '__main__': entrypoint guard.

Python7 min readConcept 16 of 24

Every Python File is a Module

In Python, every .py file is inherently a module. Its filename without the extension becomes its module name. When you execute import math_utils, Python loads, compiles to bytecode, and executes the file from top to bottom.

The objects created during this top-to-bottom execution (functions, classes, variables) become attributes on the resulting module object.

Python caches imported modules inside the sys.modules dictionary. If a module is imported a second time anywhere in the same process, Python retrieves the cached module instantly without re-executing the file.

The __name__ == '__main__' Entrypoint Guard

Whenever Python runs a script file directly from the terminal (for example python app.py), it automatically assigns the special built-in variable __name__ = '__main__'. This tells the runtime that this file is the top-level entrypoint.

However, when that exact same file is imported by another file (such as import app), Python assigns __name__ = 'app' instead.

By placing script execution code inside if __name__ == '__main__':, you allow a file to serve dual roles: a reusable library module that exports functions cleanly without unwanted side effects, and an executable script when invoked directly.

Module Search Path and the sys.path Hierarchy

When you write import custom_tool, Python searches directories listed in sys.path in strict sequential order.

First, it checks the directory containing the running script (or current working directory).

Second, it checks directories specified in the PYTHONPATH environment variable.

Finally, it checks standard library directories and third-party vendor directories inside the active environment's site-packages.

If the module is not found in any of these locations, Python raises a ModuleNotFoundError.

The Module Execution & Entrypoint Gate

Toggle between executing a script directly from the terminal versus importing it as a library. Watch how the __name__ variable toggles between '__main__' and the module name, activating or guarding test runs.

Select Execution / Import Mode:
# File: math_utils.py
def add(a, b):
return a + b
# Guarded execution block:
if __name__ == "__main__":
print("Self-test:", add(2, 3))
# Runtime status:
__name__ = "__main__" (Guard runs!)
MODULE NAMESPACE & EXECUTION RESOLUTIONCLI: python math_utils.pyInvocation Mode:Top-Level ScriptTARGET: math_utils.pyAssigned __name__:"__main__"EVALUATION: __name__ == '__main__' is TRUE✓ Standalone block executed: 'Self-test: 5' printed to stdoutLibrary serves as executable test scriptSTANDALONE EXECUTION: Direct terminal invocation (__name__ == '__main__')✓ Script runs tests and CLI logic without contaminating imports
★ Python Rule: Always guard test code with if __name__ == "__main__":. This prevents your module from executing accidental code when imported into other applications.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What value does Python assign to the built-in variable `__name__` when a file `utils.py` is imported via `import utils`?
  2. 2What is the primary cause of an `ImportError: cannot import name from partially initialized module`?
  3. 3Which directory does Python check first when resolving an import statement via `sys.path`?

Remember this

  • Every Python file is an importable module; its filename is its module identifier.
  • Python caches imported modules in sys.modules and only executes them once per process.
  • __name__ equals '__main__' when executed directly, but equals the module name when imported.
  • The if __name__ == '__main__': pattern protects library files from running demo or test code upon import.
  • sys.path defines the directory search priority: script folder first, then PYTHONPATH, then standard library and site-packages.

Done with this concept?

Mark it complete to track your progress. No login needed.