8-5. The if __name__ == "__main__": Statement

The if __name__ == "__main__": statement is a common construct in Python programming. It is used to ensure that certain code is only executed when the script is run directly, and not when it is imported as a module in another script.

What is __name__?

In Python, __name__ is a special built-in variable that represents the name of the module. Depending on how the module is being used, the value of __name__ changes:

  • If the module is being run directly (i.e., you run the script from the command line or an IDE), __name__ is set to "__main__".
  • If the module is being imported into another module, __name__ is set to the module's name.

Why Use if __name__ == "__main__":?

This construct allows you to control the execution of code based on whether the module is run as a standalone script or imported as a module. It's particularly useful for:

  • Running Tests or Example Code:
    • You can include tests or example usage of your functions in the same file, and they will only be executed if the file is run directly.
  • Avoiding Side Effects:
    • When a module is imported, you usually don't want certain parts of the code (like script-specific setup, user prompts, or other side effects) to run automatically.

 How Does It Work?

Here's a basic example to illustrate the use of if __name__ == "__main__"::

# my_module.py

def my_function():
    print("Hello from my_function!")

if __name__ == "__main__":
    print("This is executed when the script is run directly")
    my_function()

 

  • Scenario 1: Running the script directly

If you run the my_module.py script in your Command Prompt or Terminal:

> python my_module.py

The output will be:

This is executed when the script is run directly
Hello from my_function!

 

In this scenario, since the script is run directly, the condition if __name__ == "__main__": evaluates to True, and the code inside the block is executed.

Scenario 2: Importing the module

If you import the my_module.py module from another script and call the function using the module name as follows:

# another_script.py

import my_module
my_module.my_function() # Call my_function() using the module name

The output will be:

Hello from my_function!

In this scenario, when my_module is imported, the condition if __name__ == "__main__": evaluates to False, so the code inside the block is not executed. Only my_function() is called explicitly in another_script.py.