Python: if __name__ == ‘__main__’ — Beginner’s Guide

1. Introduction

The “if name == ‘main‘” construct commonly seen in Python programs is an important feature for determining how a script was executed. By using this construct, the same code can behave differently depending on whether it was “run directly” or “imported from another script”. By correctly understanding this feature, you can improve code reusability and maintainability, and enable more efficient debugging and testing. In this article, we explain in detail the role, usage, and benefits of this construct, along with concrete code examples.

2. Basic understanding of Python’s name and main

What is Python’s special variable name?

When a Python program is executed, several special variables are automatically created. __name__ is one of them and stores the name of the file (module) being executed. Typically, the __name__ variable indicates which module the program was executed from.
Note: Difference between a module and a script Module: A file containing Python code designed to be imported and used by other files. Script: A Python file intended to be executed as a program, typically not imported by other files but run directly.

Example: Behavior of name

For example, imagine a file example.py with the following contents.
# example.py
print(__name__)
If you run this file directly, the value of __name__ becomes '__main__', and the terminal will display the following:
__main__
On the other hand, when the file is imported from another file, the value of __name__ is set to the filename 'example' instead of __main__. This shows that the value of __name__ varies depending on how the script is run.

What is main?

The Python interpreter assigns the special name “__main__” to the file being executed. This lets a Python program confirm that a script is being run directly by checking “__main__“.
年収訴求

3. Practical usage of if name == ‘main

Using the “if name == ‘main‘” construct allows you to execute specific code only when a Python script is run directly. This construct is very useful for gaining better control over code behavior.

Basic syntax

if __name__ == '__main__':
    # Code that runs only when the script is executed directly
    print("This script is being run directly.")

Concrete example

Below is code using the calculate.py file as an example. This file contains a function and a conditional statement.
# calculate.py
def add(a, b):
    return a + b

if __name__ == '__main__':
    result = add(3, 4)
    print("Calculation result:", result)

Execution result

If you run this file directly, it will produce the following output.
Calculation result: 7
On the other hand, if this calculate module is imported from another file, the code below if __name__ == '__main__' will not run. Below is an example of importing and using it from another file, main_script.py.
# main_script.py
import calculate

# When imported, the code under if __name__ == '__main__' in calculate.py is not executed
print(calculate.add(10, 5))  # 15 is printed
As shown, using the “if name == ‘main‘” construct lets you make a script behave differently when it is run directly versus when it is imported by another script.

4. Benefits of Using This Construct

1. Improved Module Reusability

Using 「if name == ‘main‘」 improves a module’s reusability. It prevents unnecessary code from running when the module is imported and allows you to control that only the necessary parts are executed, which improves code maintainability.

2. Easier Testing

By placing test or debug code inside if __name__ == '__main__', you can easily run tests during development. Because the test code won’t be executed when the module is imported, you can debug more efficiently.

Example Test Code

Let’s add a simple test to calculate.py.
# calculate.py
def add(a, b):
    return a + b

if __name__ == '__main__':
    # Test code
    print("3 + 4 =", add(3, 4))
    print("10 + 5 =", add(10, 5))
In this way, by having simple tests run only when the module is executed directly, tests won’t run when the module is imported by other code, and only the necessary functions will be used.
年収訴求

5. Precautions and Best Practices

Precautions

  1. Improve code clarity if __name__ == '__main__'Place test and execution code below this point to clearly separate responsibilities within the file. Make sure parts that should not run on import are enclosed within the conditional so that unnecessary code doesn’t run by accident.
  2. Be careful with circular imports If multiple files import each other in code using if __name__ == '__main__', take care to avoid circular imports. Complex module dependencies increase the risk of circular imports, so try to keep dependencies simple.

Best Practices

  1. Put test code in a main block By placing test code inside if __name__ == '__main__', you prevent unnecessary execution when the module is imported by other code. Ensuring tests only run when the module is executed directly helps avoid unintended behavior.
  2. Group related functions together By grouping related functions within if __name__ == '__main__' and calling them as needed, your code stays concise, easier to read, and simpler to maintain.

6. Summary

The “if name == ‘main‘” construct is a convenient way to determine how a Python script was executed. Using this construct, you can ensure that code runs only when the script is executed directly, improving module reusability and making testing easier. When programming in Python, make effective use of this construct and separate scripts and modules appropriately to enhance code maintainability and reusability.
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール