if __name__ == "__main__":
Runs code only when a file is executed directly — not when another module imports it.
if __name__ == "__main__":
main()
Purpose
Every module has a __name__ variable. When a file is run directly (python file.py), Python
sets its __name__ to "__main__". When the same file is imported by another module instead,
its __name__ is set to the module’s own name (e.g. "greeting_helpers"). The guard checks which
of those happened, so code inside it runs only on direct execution.
Example
def greet(name: str) -> str:
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("Ada")) # runs when this file is executed directly
# does NOT run when another file does `import this_module`
Behavior notes
- Every canonical example on this site ends with this exact guard, calling a
main()function — the standard shape: define functions and classes unconditionally (so they’re available whether the file is imported or run), and put only “actually do something now” code behind the guard. - Without the guard, a file that both defines reusable functions and runs top-level code (like a
printor a script action) would run that top-level code every time anything imports it — not just when someone deliberately executes the file. - The guard is what makes a file usefully both a script (runnable directly) and a module (importable for its functions) at once, without those two uses interfering with each other.
Common mistakes
- Assuming a module-level
print(...)or other side-effecting code “only runs once” — it runs every time the file is imported for the first time in a given process, in addition to whenever it’s executed directly, unless it’s behind the guard. - Putting function or class definitions behind the guard — this makes them unavailable to code that imports the file, which usually isn’t the intent. Only the “run this now” call belongs behind the guard, not the definitions it depends on.
Implementation notes
__name__’s value ("__main__" for direct execution, the module’s own name when imported) is
part of the language’s import system — guaranteed behavior across conforming implementations.