if __name__ == "__main__" β Understanding Script ExecutionIntroduction π
The expression if __name__ == "__main__" is one of the most important Python patterns. It determines whether a Python file is being:
- β Run directly as the main program
- β Imported into another module
Note
if __name__ == "__main__" runs ONLY when the file is executed directly, NOT when imported.1. What is __name__? π€
Every Python file (module) has a built-in variable called __name__.
| How file is used? | __name__ value |
|---|---|
| Executed directly | "__main__" |
| Imported as module | module name |
2. Basic Example π§±
main_example.py
# file: demo.py
print("Value of __name__:", __name__)
if __name__ == "__main__":
print("This runs ONLY when executed directly!")β If you run python demo.py β block runs
β If you import it: import demo β block does NOT run
3. Why Use __main__? π―
- β Prevents code from running automatically when imported
- β Allows files to behave both as scripts and modules
- β Good for testing or demo code inside modules
- β Essential in large projects for clean structure
4. Custom Module Example π§©
module_with_main.py
# file: calculator.py
def add(a, b):
return a + b
if __name__ == "__main__":
print("Testing calculator...")
print(add(10, 20))use_module.py
import calculator
# add() can be used but the test block does NOT runβ The testing code runs only when calculator.py is used directly.
5. Real-World Use Case: Script Entry Point π
entry_point.py
def main():
print("Program started")
if __name__ == "__main__":
main()β Standard method for creating an application entry point.
6. Organizing Large Projects π¦
project_structure
project/
calculator.py
utils.py
main.pymain.py becomes the central place where your program starts.
main.py
from calculator import add
from utils import greet
if __name__ == "__main__":
print(add(5, 10))
greet("Sathish")7. Preventing Code from Running on Import π
no_unwanted_execution.py
# file: db.py
print("Connecting to DB...") # Bad! Runs even on import
# FIX:
if __name__ == "__main__":
print("Connecting to DB...")Note
8. Using for Testing Code π§ͺ
testing_example.py
def multiply(a, b):
return a * b
if __name__ == "__main__":
print("Testing multiply...")
print(multiply(3, 4))β Helps developers test functions inside their modules.
9. Examples with Command-Line Programs π₯οΈ
cli_example.py
def greet(name):
print("Hello", name)
if __name__ == "__main__":
import sys
greet(sys.argv[1])β Turning modules into CLI tools.
10. Importing Behavior Summary π
| Scenario | __name__ value | Block runs? |
|---|---|---|
| python file.py | "__main__" | YES |
| import file | "file" | NO |
| Executed as script | "__main__" | YES |
Conclusion π
if __name__ == "__main__" lets your Python file behave like both a reusable module and an executable script β one of Pythonβs cleanest design patterns.β β¨You now fully understand __name__ == "__main__" in Python! Want the next topic? Try OOP (Classes & Objects), File Handling, Import System, or Virtual Environments. Just tell me! π