__name__ == "__main__" in Python
What It Is In Python, every file (module) has a built-in variable called __name__.
Its value depends on how the file is being used:
• ✅ When run directly:
The value of __name__ is set to "__main__".
• 📦 When imported as a module:
The value of __name__ is set to the module’s name (i.e., the filename without .py).
A module is basically a Python file (.py) containing variables, functions, or classes.
The statement:
Python
if __name__ == "__main__":
is used to determine whether a Python script is being executed directly or imported into another script.
Code inside this block executes only when the file runs directly, not when it’s imported as a module.
Why It’s Useful:
- Encourages Code Reuse
You can define functions, classes, or constants in a file and use them both for:- Direct testing or execution.
- Importing into other programs as reusable modules.
- Prevents Unwanted Execution During Import
Any test or print statements inside the if __name__ == "__main__": block won’t run when the file is imported. - Promotes Modularity and Clean Design
Helps keep your codebase organized and ensures that modules have a single, clear entry point.
Example: Simple demonstration.
Python
# file: mymodule.py
# Define a function
def greet(name):
print(f"Hello, {name}!")
if __name__ == "__main__":
# This code runs only when the file is executed directly
greet("Ashish") • When run directly: python mymodule.py • Output: Hello, Ashish!
• Imported in another file:
Python
# file: test.py
import mymodule
mymodule.greet("World") Output: Hello, World!
Note: The code inside if __name__ == "__main__": in mymodule.py does not execute when imported.
Explanation:
| Concept | Explanation |
|---|---|
| __name__ | Built-in variable in every Python file |
| "__main__" | Value of __name__ when the file is executed directly |
| if __name__ == "__main__": | Ensures that code runs only when file is executed directly, not on import |