Python __name__

How __name__ is set, the if __name__ == '__main__' guard, and why it matters for imports.

Beginner
Key PointsEvery module has a __name__; it equals '__main__' only for the file you ran, which is how a file can be both a library and a script.

What __name__ Holds

When Python imports a module, it sets the module's __name__ to its dotted import path. When you run a file directly, Python sets it to the string "__main__" instead.

Python
# utils.py
print("__name__ is", __name__)

# $ python3 utils.py
# __name__ is __main__

# $ python3 -c "import utils"
# __name__ is utils

The Guard

Put executable code behind if __name__ == "__main__":. Then importing the module only defines functions and classes — it does not start a server, open a database or send mail.

Python
def fetch(url):
    ...


def main():
    print(fetch("https://api.example.com/health"))


if __name__ == "__main__":
    main()

Why It Matters

  • Without the guard, import utils in a test would run the whole program.
  • It makes a module reusable as both a library and a CLI entry point.
  • Multiprocessing on Windows re-imports the module in each child — without the guard you get an infinite spawn loop.
  • Packaging tools look for __main__.py to support python -m package.
Python
# mypkg/__main__.py  ->  python -m mypkg 时执行
from mypkg.cli import main

if __name__ == "__main__":
    main()

Common Patterns

PatternPurpose
if __name__ == "__main__":Script entry point
if __name__ != "__main__":Library-only setup
__all__ = [...]Control from x import *
__version__ = "1.0"Package metadata
__name__ is a module-level variable, not a function. Never assign to it — code that checks it will misbehave.

Friends & Partners