The if __name__ == "__main__": guard is the Python idiom that lets one file behave as both a runnable script and an importable module. When you launch the file directly with python myfile.py, Python sets the special variable __name__ to "__main__" and the block under the guard runs. When something else does import myfile, __name__ takes the module's import name ("myfile") instead, and the same block stays silent. This piece is one of 17 short explainers in our Python Concepts Explained reference.

Key Takeaways

  • __name__ is a variable Python sets automatically in every module. Its value is "__main__" when the file runs as the entry point, and the module's actual import name otherwise.
  • The guard if __name__ == "__main__": runs code in script mode and skips it on import. That's the whole mechanic, no magic beyond an ordinary if.
  • Use it around main() calls, CLI entrypoints, ad-hoc demos, and any code you don't want to execute as a side effect of someone doing import yourfile.
  • The guard is effectively mandatory for safe multiprocessing on Windows and on macOS (default spawn start method). Without it, child workers re-import the script and re-spawn themselves recursively (Python docs on multiprocessing start methods).
  • Skip the guard in library-only files that have nothing to run as a script. Adding it where it isn't needed clutters small modules for no benefit.

The __name__ Value Cheat Sheet

The fastest way to internalize the guard is to memorize what value __name__ takes in every loading scenario. This single table answers most "wait, why does it do that?" questions:
How the file is loadedValue of __name__Guard fires?
python myfile.py"__main__"yes
python -m mypackage.myfile"__main__"yes
python -m mypackage (runs __main__.py)"__main__"yes
import myfile from another file"myfile" (the module name)no
from mypackage import myfile"mypackage.myfile"no
Interactive REPL or Jupyter cell"__main__"yes
Spawned child in multiprocessing (Windows / macOS spawn)module name, NOT "__main__"no (this is what saves you)
This pattern is known in the Python community as the name-main idiom, a term Real Python helped popularize.Programmer's screen showing a Python script being executed in a terminal, the canonical place where __main__ matters

What Is __name__, Exactly?

__name__ is one of Python's built-in module attributes. Every .py file gets one, populated by the import system the moment the file is loaded. The value depends on how the file was loaded:
  • Run with python myfile.py or python -m mypackage.myfile: Python assigns __name__ = "__main__". The file is the program's entry point.
  • Loaded via import myfile from another file: Python assigns __name__ = "myfile". The file is a library being imported.
  • Inside the interactive REPL: __name__ == "__main__" as well (you, the typist, are the entry point).
The guard reads that variable and branches. Nothing else is going on. Print it once and the mystery dissolves:
# greet.py
print(f"__name__ is {__name__!r}")

def hello():
    print("Hello from greet.hello()")

if __name__ == "__main__":
    hello()
Run it as a script: prints __name__ is '__main__' then calls hello(). Import it from another file: prints __name__ is 'greet' and hello() stays untouched.

How Does the Guard Actually Work?

The condition is a plain string equality check. Python evaluates module top-level code once, in order, when the module loads. By the time interpretation reaches the guard, __name__ already holds either "__main__" or the module name. The if branch picks one path.
Script execution vs import: two paths through the same file Same file, two execution paths $ python myfile.py run as script __name__ == "__main__" guard evaluates True Protected block RUNS import myfile imported as module __name__ == "myfile" guard evaluates False Protected block SKIPPED myfile.py one source The same myfile.py is loaded; only the value of __name__ differs. Code under the guard sees one truth on the left, another on the right.
Same source file, two execution paths. __name__ is the only variable that differs.
The mechanic is the same as any if. There's no special hook, no metaclass, no decorator. Python's documentation describes __main__ as "the name of the scope in which top-level code executes" (Python docs on __main__) — that scope's __name__ is set to the literal string by the import machinery, and the guard simply reads it.

What's the Standard Template?

The pattern most professional codebases follow is short:
def main():
    # all the script's work happens here
    ...

if __name__ == "__main__":
    main()
Three reasons this layout wins over inline code under the guard:
  1. Importable. Anyone can from yourfile import main and call your script's logic programmatically, useful for tests and for chaining scripts together.
  2. Testable. Unit tests can call main() directly without spawning a subprocess.
  3. Argument parsing stays in one spot. The main() function owns the CLI; the guard owns the "am I the entry point" decision. Concerns split cleanly.
For scripts that take arguments, the slightly fuller template uses argparse or sys.argv inside main() and returns an exit code:
import sys

def main(argv: list[str] | None = None) -> int:
    args = argv if argv is not None else sys.argv[1:]
    # ...work...
    return 0

if __name__ == "__main__":
    sys.exit(main())

When Does It Actually Matter?

Five concrete cases where the guard pulls its weight:
  1. Dual-purpose files. A module that exposes useful functions AND has a "run me" mode (e.g. python -m my_tool.cli).
  2. multiprocessing on Windows and macOS. Child workers re-import the main script. Without the guard, the spawn call re-fires in every child, and your machine spirals.
  3. Demo or smoke-test sections. A library file with an if __name__ == "__main__": block at the bottom that exercises the API for quick manual checks.
  4. Test files. Frameworks like unittest let you run a test module directly via if __name__ == "__main__": unittest.main() while still allowing the test runner to import it.
  5. Notebook-friendly modules. Same module imported into a Jupyter notebook for exploration shouldn't run its CLI by accident.

What About __main__.py for Packages?

Python lets a whole package act as a script by giving it a __main__.py file. When you run python -m mypackage, the interpreter loads mypackage/__main__.py with __name__ == "__main__", exactly as if you'd run a single-file script.
# mypackage/__main__.py
from mypackage.cli import run

if __name__ == "__main__":
    run()
The guard inside __main__.py is technically redundant (this file isn't meant to be imported by anything), but most maintainers leave it in for consistency and to keep linters quiet. Standard-library tools like http.server, venv, pip, and unittest all expose themselves through __main__.py, which is why python -m http.server just works.

How Do You Test main() Directly?

Wrapping your script logic in a main() function unlocks a quiet superpower: main() becomes unit-testable.
# myscript.py
def main(argv: list[str]) -> int:
    if not argv:
        print("usage: myscript <name>")
        return 1
    print(f"Hello, {argv[0]}")
    return 0

if __name__ == "__main__":
    import sys
    sys.exit(main(sys.argv[1:]))
# test_myscript.py
from myscript import main

def test_main_with_name(capsys):
    exit_code = main(["Ada"])
    captured = capsys.readouterr()
    assert exit_code == 0
    assert "Hello, Ada" in captured.out

def test_main_no_args(capsys):
    exit_code = main([])
    assert exit_code == 1
Two payoffs. First, you skip the subprocess dance (no subprocess.run(["python", "myscript.py"]) in every test). Second, the guard prevents myscript.main() from auto-firing when pytest imports the file. Without the guard, the import would execute the script before the tests ran.

Common Mistakes

Four traps to watch for: Mistake 1: typos in the literal. "__main__" needs exactly two leading and two trailing underscores. "_main_" or "__main_" will never match, and the guard will never fire. Most editors highlight the variable, which helps catch this. Mistake 2: top-level side effects outside the guard. A network call, file write, or expensive computation written at module top level runs on every import. Move them inside main() or inside the guard. Mistake 3: forgetting the guard before multiprocessing. On Windows this gets you an immediate RuntimeError with a friendly hint. On macOS with newer defaults, the failure is more subtle: workers crash or hang. Always guard the Pool / Process spawn call. Mistake 4: using it as a "main function" replacement. The guard isn't a function and doesn't take arguments. Define a real main() and call it from inside the guard.

When Should You Skip the Guard?

Pure library modules that contain only definitions (functions, classes, constants) and never need to run as a script have no use for the guard. Adding it just to add it is noise. The rule of thumb: if there's nothing you'd want to run when calling python yourfile.py, there's nothing for the guard to protect.

Frequently Asked Questions

Do I always need if __name__ == "__main__": in Python?

No. Use it only when the file is meant to run as a script AND be importable as a module. For library-only modules with no executable code at the bottom, the guard adds nothing. For scripts that nobody will ever import, it still costs nothing and protects against future import surprises, so the convention is to include it anyway.

What's the difference between __name__ and __main__?

__name__ is a variable that Python sets automatically in every module. __main__ is the special string value Python assigns to __name__ when a file is executed directly (via python file.py or python -m). When the file is imported, __name__ holds the module's actual import name instead. So __name__ is the variable; "__main__" is one of the values it can take.

Why does multiprocessing need the guard?

On Windows and on macOS (with the default spawn start method), child processes re-import the main script to get the worker code. Without the guard, any code at module top level runs again in each child, including the call that spawned them in the first place, which spawns infinitely. The guard stops that recursion: child imports see __name__ as the module name, not "__main__", so the spawn call stays silent.

Can I use def main(): without the guard?

Yes, defining main() is independent of the guard. The function exists either way. The guard decides whether main() actually gets called when the file loads. The standard idiom defines main() at module level and calls it inside the guard, so the function is reusable from importers while still running automatically when the file is the script.

The Bottom Line: Two Modes From One File

The whole feature is a single if on a single variable. Python sets __name__ based on how the file was loaded; the guard branches on the value. Adopt the standard def main(): ... if __name__ == "__main__": main() template and your files will work cleanly as scripts, as importable modules, and as test targets, all at once. For the rest of the most-asked Python concept questions, browse the full Python Concepts Explained index. For broader syntax coverage, see our Python syntax tutorial for beginners.

Build the Habit on Real Python Tasks

CodeGym's Python track turns idioms like if __name__ == "__main__": into muscle memory through 800+ hands-on tasks across 62 levels. The AI validator checks every submission in seconds; the AI mentor explains what broke when you get stuck. First level free; full plan on the pricing page. Learn Python on the free track →

Learn more about our mission and terms of service. Published article was last reviewed on 2026-05-26.