Python Script Execution Control: Direct Run vs. Import

When writing Python scripts, you often see the following code at the end of the file:

Python

if __name__ == "__main__":
    main()

This is often written as a standard “boilerplate,” but it is actually an important control structure to determine whether “the file was executed directly as a script” or “imported as a module from another file.”

This article explains the mechanism of the special variable __name__ and why this syntax is necessary.


目次

The Problem: Code Runs Just by Importing

Python’s import statement reads the specified file and executes all the code inside it from top to bottom. If you write not only function or class “definitions” but also function “calls (execution)” at the top level, they will be executed arbitrarily the moment the file is imported.

Example: Problematic Code (greeter.py)

def say_hello():
    print("Hello from greeter!")

# Function is called immediately after definition
print("--- Loading greeter.py ---")
say_hello()

There is no problem when running this file directly. However, problems arise when you try to use it from another file.

Using Side (app.py)

import greeter

print("--- Starting app.py processing ---")

Execution Result (python app.py):

--- Loading greeter.py ---
Hello from greeter!
--- Starting app.py processing ---

Even though app.py simply wanted to use the features of greeter, say_hello() inside greeter.py was executed arbitrarily upon import.


Solution: Branching with the __name__ Variable

To solve this problem, we use the special variable __name__, which Python sets automatically. This variable holds the following values depending on the execution context:

  • When executed directly: __name__ contains the string "__main__".
  • When imported: __name__ contains the module name (filename).

We use this property to create a branch that says “perform this processing only when executed directly.”

Corrected Code (greeter.py)

def say_hello():
    print("Hello from greeter!")

# The following block is executed only when run directly
if __name__ == "__main__":
    print("--- Direct execution of greeter.py ---")
    say_hello()

Verification

1. When executed directly (python greeter.py) Since __name__ is "__main__", the content of the if block is executed.

--- Direct execution of greeter.py ---
Hello from greeter!

2. When imported (python app.py) Since __name__ is "greeter", the if block becomes False, and the content is not executed. Only the function definition is loaded.

--- Starting app.py processing ---

We have successfully prevented unintended execution.


Common Structure (Using main() function)

In Python programs, it is recommended to group the code that serves as the entry point of processing into a function named main() and call it from the if __name__ == "__main__": block.

def process_data():
    print("Processing data...")

def main():
    """Main processing"""
    print("Starting script.")
    process_data()
    print("Ending script.")

if __name__ == "__main__":
    main()

Doing this prevents polluting the global namespace with variables and improves code readability. It also allows for flexible operations, such as calling only the main() function from external test code.


Summary

  • Python files execute their contents both when run directly and when imported.
  • The special variable __name__ becomes "__main__" when run directly, and the module name when imported.
  • By using if __name__ == "__main__":, you can write code that runs only when executed as a script (such as test runs or main processing).
  • This is a fundamental practice for writing code that is reusable as a module.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次