__name__ == '__main__'
The __name__ == '__main__' pattern lets a file work as both a module (importable) AND a script (runnable). This is a Python essential.
10 min•By Priygop Team•Updated 2026
__name__ Guard
__name__ Guard
# When you run a file directly:
# __name__ == "__main__"
# When you import it as a module:
# __name__ == "module_name"
# Example: calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
# This code ONLY runs when executed directly
# NOT when imported as a module
if __name__ == "__main__":
print("Running calculator.py directly!")
print(f"5 + 3 = {add(5, 3)}")
print(f"4 * 7 = {multiply(4, 7)}")
# Run tests
assert add(2, 3) == 5
assert multiply(3, 4) == 12
print("All tests passed!")
# If another file does 'from calculator import add':
# Only the functions are imported
# The test code does NOT run!
# This is the standard Python pattern.
# ALWAYS use it in your scripts.
print(f"\n__name__ = '{__name__}'")Tip
Tip
Always use if __name__ == '__main__': to guard script code. It prevents side effects when importing your module.
Diagram
Loading diagram…
Module = file, Package = folder + __init__.py, Library = pip.
Common Mistake
Warning
Putting executable code at module level without the __name__ guard. It runs on import, causing unexpected behavior.
Quick Quiz
Practice Task
Note
(1) Create a module with the __name__ guard. (2) Import it and verify the guard works. (3) Run it directly and see the difference.