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.
Python code
12 linesdef 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
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
- Define a `main()` function and call it inside the guard: `if __name__ == '__main__': main()`.
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.