What does ‘if __name__ == “__main__”:’ do in Python?

In Python, the if __name__ == "__main__": construct is used to control code execution when a Python file is run directly versus imported as a module. Here’s a breakdown:

1. What does it do?

  • When a Python script is run directly, the special variable __name__ is automatically set to "__main__".
  • When the script is imported as a module into another script, __name__ is set to the module’s name (e.g., "my_module").

The code block under if __name__ == "__main__": will only execute if the script is run directly, not when imported.

2. Why use it?

  • Avoid unintended execution: Code inside the block won’t run when the file is imported as a module.
  • Module testing: Allows you to add test code or demo logic that runs only when the script is executed directly.
  • Code organization: Separates reusable functions/classes (outside the block) from execution-specific logic (inside the block).

3. Example

Suppose you have a file example.py:

python

def greet():
    print("Hello from the module!")

if __name__ == "__main__":
    print("This runs only when the script is executed directly.")
    greet()

Case 1: Run directly

bash

python example.py

Output:

This runs only when the script is executed directly.
Hello from the module!

Case 2: Import as a module

python

# another_script.py
import example

example.greet()  # Output: "Hello from the module!"

No output from the if __name__ == "__main__": block.

4. Common Use Cases

  • Running tests or demos for a module.
  • Defining command-line interfaces (CLIs) (e.g., with argparse).
  • Initializing resources only when the script is the main program.

Key Takeaway

  • if __name__ == "__main__": ensures code runs only in direct execution, making scripts modular and reusable.
  • It’s a Python best practice for organizing code that serves dual purposes (module + executable).

Leave a Reply

Your email address will not be published. Required fields are marked *