What does if __name__ == "__main__": do?
Categories:
Understanding if __name__ == "__main__":
in Python

Explore the purpose and functionality of the if __name__ == "__main__":
idiom in Python, a crucial construct for controlling script execution and module behavior.
In Python, you'll frequently encounter the line if __name__ == "__main__":
at the top level of many scripts. This seemingly cryptic statement is a fundamental idiom that plays a vital role in how Python modules are executed and reused. It allows a Python file to be used both as an executable script and as an importable module, providing a clean way to define code that should only run when the script is executed directly.
The Role of __name__
and __main__
To understand if __name__ == "__main__":
, we first need to grasp the special variables __name__
and __main__
.
Every Python module (which is essentially any .py
file) has a built-in attribute called __name__
. The value of __name__
depends on how the module is being used:
- When a script is run directly: The
__name__
attribute of that script is set to the string"__main__"
. - When a script is imported as a module: The
__name__
attribute of the imported module is set to its actual module name (i.e., the filename without the.py
extension).
# my_module.py
print(f"The value of __name__ is: {__name__}")
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print("This code runs only when my_module.py is executed directly.")
print(greet("World"))
Example of __name__
in a Python module
Let's see this in action. If you run my_module.py
directly from your terminal:
python my_module.py
The output would be:
The value of __name__ is: __main__
This code runs only when my_module.py is executed directly.
Hello, World!
Now, if you import my_module.py
into another script (e.g., another_script.py
):
# another_script.py
import my_module
print(f"In another_script.py, my_module.__name__ is: {my_module.__name__}")
print(my_module.greet("Alice"))
Running another_script.py
would produce:
The value of __name__ is: my_module
In another_script.py, my_module.__name__ is: my_module
Hello, Alice!
Notice that the code inside the if __name__ == "__main__":
block in my_module.py
did not execute when it was imported. This demonstrates its core utility.
Why is it Useful?
The if __name__ == "__main__":
block serves several important purposes, primarily promoting code reusability and preventing unintended side effects.
Distinguishing between direct execution and import: It allows you to define code that should only run when the script is the primary entry point of the program. This is typically where you'd put function calls, test cases, or setup code that initializes your application.
Preventing execution on import: When you import a module, Python executes all the code at the top level of that module. Without the
if __name__ == "__main__":
guard, any code meant for direct execution (likeprint("Hello, World!")
ormain()
function calls) would run every time the module is imported into another script, which is usually undesirable.Encouraging modular design: It promotes a clear separation between the reusable components (functions, classes) of your module and the specific logic for running it as a standalone program. This makes your code easier to understand, test, and maintain.
flowchart TD A[Python Interpreter Starts] B{Is this script the main program?} C[Set __name__ = "__main__"] D[Set __name__ = "module_name"] E[Execute code outside if block] F{Is __name__ == "__main__"?} G[Execute code inside if block] H[Skip code inside if block] A --> B B -- Yes --> C C --> E B -- No (Imported) --> D D --> E E --> F F -- True --> G F -- False --> H
Execution flow with if __name__ == "__main__":
Common Use Cases
This idiom is commonly used for:
- Calling a
main()
function: Many Python programs structure their primary execution logic within amain()
function, which is then called inside theif __name__ == "__main__":
block. - Running unit tests: If a module contains its own unit tests, they can be placed within this block so they only run when the module is executed directly, not when imported.
- Command-line argument parsing: Code that parses command-line arguments and performs actions based on them is often placed here.
- Demonstration code: Examples or demonstrations of how to use the module's functions can be included without affecting other scripts that import it.
# calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def main():
print("--- Simple Calculator ---")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(f"{num1} + {num2} = {add(num1, num2)}")
print(f"{num1} - {num2} = {subtract(num1, num2)}")
if __name__ == "__main__":
main()
Using if __name__ == "__main__":
to call a main()
function
if __name__ == "__main__":
. This makes your modules more robust and reusable, preventing unexpected behavior when they are imported by other parts of your project or by third-party libraries.