How to Use the if __name__ == '__main__' Guard in Python

This code defines reusable functions and uses the standard main guard to run them only when the script is executed directly, not when imported.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 13 views 0 copies

Python code

12 lines
Python 3.9+
def greet(name: str) -> str:
    """Return a friendly greeting."""
    return f"Hello, {name}!"

def get_planet() -> str:
    """Return the name of our planet."""
    return "Earth"

if __name__ == "__main__":
    user = "Dorothy"
    print(greet(user))
    print(f"We live on {get_planet()}.")

Output

stdout
Hello, Dorothy!
We live on Earth.

How it works

The if __name__ == "__main__": line checks whether the script is being run directly or imported as a module. When executed directly, __name__ is set to "__main__", so the code block runs. If imported elsewhere, __name__ is the module name and the block is skipped, preventing side effects. This pattern keeps functions reusable and testable.

Common mistakes

  • Forgetting to put the call inside the block, so it runs on import.
  • Typing `name` instead of `__name__` (target of the comparison).

Variations

  1. Define a `main()` function and call it inside the guard: `if __name__ == '__main__': main()`.
  2. Use `argparse` to parse command-line arguments inside the guard.

Real-world use cases

  • Creating CLI tools where the script only runs when invoked from the terminal.
  • Keeping reusable modules side-effect-free for unit testing.
  • Debugging script code without executing it during import in other modules.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.