__name__ == "__main__"

The if __name__ == "__main__": guard lets a single file act as both a runnable script and a safely importable module — without one role interfering with the other.

Every Python file can be used two ways: run directly as a program, or imported by another file to reuse its definitions. The if __name__ == "__main__": guard is the standard idiom that separates the two, so a file that gets imported doesn't accidentally execute code meant only for standalone running.

Script Execution vs Import Execution

When Python runs a file directly (python file.py), it sets that file's built-in __name__ attribute to the string "__main__". When the same file is instead imported by another module, __name__ is set to the module's own name. This is the only difference in how the file executes — the rest of the top-level code runs identically either way.

# tool.py
print('Value of __name__:', __name__)
$ python tool.py
Value of __name__: __main__

>>> import tool
Value of __name__: tool

The Main Guard

Wrapping script-only code in if __name__ == "__main__": means that code runs only when the file is executed directly, never when it's imported.

Importing converter for the function alone never triggers the interactive input() prompt; running converter.py directly does.

# converter.py
def celsius_to_fahrenheit(c: float) -> float:
    return c * 9 / 5 + 32

if __name__ == '__main__':
    value = float(input('Enter Celsius: '))
    print(celsius_to_fahrenheit(value))

Why This Matters: Reusable Module Design

Without the guard, every top-level statement — including things that only make sense standalone, like reading command-line input, printing demo output, or running a full test suite — executes the instant anyone imports the file. This turns an otherwise-useful module into something risky to import: unwanted output, blocked input() calls, or unintended side effects.

# WITHOUT a guard — dangerous to import
# stats_bad.py
def mean(values):
    return sum(values) / len(values)

print(mean([1, 2, 3]))   # runs on every import, not just direct execution

The Guard as an Entry Point

It's idiomatic to keep the guard's body minimal — typically a single call to a main() function — so that the script's logic itself remains testable and reusable, and only the decision of 'run main() now' is gated.

Another file can from thisfile import main and call it explicitly, or a test can call main() directly, without needing to simulate command-line execution.

def main() -> None:
    print('running as a script')

if __name__ == '__main__':
    main()

Common Pattern: Dual-Purpose Files

A file can define genuinely reusable functions/classes at the top level and also serve as a runnable demo or CLI entry point, using the guard to separate the two roles cleanly.

from fibonacci import fib reuses the function silently; python fibonacci.py prints the first ten Fibonacci numbers.

# fibonacci.py
def fib(n: int) -> int:
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

def main() -> None:
    for i in range(10):
        print(fib(i), end=' ')
    print()

if __name__ == '__main__':
    main()

Edge Cases

Running a module inside a package with python -m package.module also sets that module's __name__ to "__main__" (not to the dotted package path), so the guard behaves the same way whether launched with python file.py or python -m package.module. A module imported for its side effects only (rare, and usually a design smell) never triggers the guard at all — by definition, since it wasn't run as __main__.

Mental Model

Think of __name__ as Python silently answering the question "how was this file started?" for every file, every time. The guard is simply an if statement reading that answer: "was I launched directly, or borrowed by someone else?"

Quick Reference

python file.py           -> file's __name__ == '__main__'
import file                -> file's __name__ == 'file'
python -m pkg.file          -> file's __name__ == '__main__'

if __name__ == '__main__':
    main()   # runs only on direct execution

Key Takeaways

__name__ equals "__main__" only when the file is executed directly (including via python -m), never when it is imported.

The main guard prevents script-only code from running as a side effect of import.

Idiomatic style keeps the guard's body to a single call, usually main().

The guard makes a file safely dual-purpose: a reusable module and a runnable script.

Without the guard, importing report.py for load_data or summarize alone triggers the full script (including any I/O) immediately.

if __name__ == "main": # missing double underscores if __name__ == "__main__":

The comparison must match the exact string "__main__" including both pairs of underscores; "main" never equals __name__ and the guard's body silently never runs.

What value does __name__ take when a file is run directly with python file.py?

What value does __name__ take when the same file is imported by another module?

The module's own name (its filename without .py).

Why does code outside the if __name__ == "__main__": guard run on both direct execution and import, while code inside it runs only on direct execution?

Because __name__ is set before the file's top-level code executes, and only the guard's if-condition checks that value — everything else runs unconditionally regardless of how the file was started.

What is the idiomatic pattern for the guard's body?

A single call to a main() function, keeping the reusable logic outside the guard and testable independently.

What happens to __name__ when a module is run with python -m package.module?

It is still set to "__main__", the same as running the file directly — not to the dotted package path.

What practical problem does omitting the main guard cause for a module that calls input() at the top level?

Any file that imports that module would immediately block waiting for input, even if it only wanted to reuse a function from it.

Write a file calc.py defining add(a, b) and subtract(a, b), with a main guard that prints add(2, 3) and subtract(5, 1) only when run directly.

Running python calc.py prints 5 then 4. Doing import calc from elsewhere defines add and subtract without printing anything, since those prints are inside the guard.

What does running python main.py print, and in what order?

It prints 'A' then 'C'. Importing lib.py sets its __name__ to 'lib', not '__main__', so the guarded print('B') is skipped, while the unguarded prints ('A' and 'C') run unconditionally.

Why is if __name__ == "__main__": preferred over simply never adding demo/script code to a reusable module at all?

The guard lets one file serve two legitimate purposes at once — a reusable library and a directly runnable script/demo/CLI — without forcing developers to maintain a separate script file just to exercise the module's functionality.

# lib.py
print('A')

if __name__ == '__main__':
    print('B')

print('C')

# main.py
import lib