# 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.

Subject: Python | Lesson 16 of 24 | 7 min read
Interactive lesson: https://codewithanimation.in/python/imports
Previous: [Magic (Dunder) Methods & Protocols](https://codewithanimation.in/python/magic-methods.md) | Next: [The Python Standard Library: Batteries Included](https://codewithanimation.in/python/standard-library.md)

## 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`.

## Common mistake: Circular Import Traps and Partial Initialization

A circular import occurs when `module_a` imports `module_b`, and `module_b` simultaneously imports `module_a` at the root level.

When `module_a` imports `module_b`, Python pauses execution of `module_a` and starts running `module_b`. When `module_b` tries to access attributes from `module_a`, those attributes have not been executed yet.

This produces confusing errors such as `ImportError: cannot import name 'User' from partially initialized module 'module_a'`. Fix this by restructuring shared dependencies into a third independent module or moving specific imports inside functions.

## Tip: PEP 8 Import Grouping Hierarchy

Follow the PEP 8 standard: group imports at the very top of your file into three distinct blocks separated by a single blank line: 1) Standard library imports (e.g. `os`, `sys`, `pathlib`), 2) Related third-party imports (e.g. `requests`, `fastapi`), and 3) Local application or library-specific imports.

## Try it: 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.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/imports

## Check yourself

### Question 1

What value does Python assign to the built-in variable `__name__` when a file `utils.py` is imported via `import utils`?

- A. 'utils'
- B. '__main__'
- C. None
- D. '__init__'

Correct answer: A

When imported, a file's `__name__` matches its module name (`'utils'`). It only evaluates to `'__main__'` when executed as the top-level script.

- Why not B: '__main__' is only assigned when the file is run directly from the command line.
- Why not C: __name__ is always populated with a string identifier.
- Why not D: '__init__' is for package markers and class initializers, not module names.

### Question 2

What is the primary cause of an `ImportError: cannot import name from partially initialized module`?

- A. Two modules circular-importing each other at the root file level before attributes are defined
- B. Using snake_case instead of CamelCase in module filenames
- C. Missing __name__ == '__main__' guard at the bottom of the module
- D. The module file is marked read-only on the operating system

Correct answer: A

Circular imports pause the first module mid-execution to load the second module, which attempts to read uninitialized attributes from the first module.

- Why not B: Python PEP 8 encourages snake_case for module filenames.
- Why not C: The __main__ guard prevents standalone execution, not import initialization.
- Why not D: Read-only files can still be imported and executed in memory.

### Question 3

Which directory does Python check first when resolving an import statement via `sys.path`?

- A. The directory containing the top-level script that was executed
- B. The system site-packages directory
- C. The operating system root folder /
- D. The user home directory ~/.python

Correct answer: A

The first item `sys.path[0]` is always the directory of the script used to invoke the Python interpreter (or the current working directory in the REPL).

- Why not B: Site-packages is checked after the current script folder and standard library.
- Why not C: OS root is not included in default sys.path.
- Why not D: Home directory is not searched unless added explicitly to PYTHONPATH.

## 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.
