πŸš€ Python if __name__ == "__main__" β€” Understanding Script Execution

Introduction 🌟

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

πŸ’‘ Code inside 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 modulemodule 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.py

main.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

βœ” Prevents unexpected behavior when imported in other modules.

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__ valueBlock 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! 😊