sec05 - Chapter 2: Python's if __name__ == '__main__': Explained: Understanding __name__ and Namespaces

In the previous lecture, we learned how to structure packages and modules and how to use import. In this lecture, you will learn how Python distinguishes between modules that are executed directly and those that are executed when they are imported from another module.

Python provides a built-in mechanism for determining “how the code was executed.” That mechanism is what we will learn about in this lecture: __name__ and the conditional statement if __name__ == '__main__'.

スポンサーリンク

Understanding Python’s __name__: How It Works and Why It Matters

Python defines several “special variables” automatically when a script is executed. One of these is __name__ (a name wrapped in double underscores).

__name__ indicates “how this script was executed.” In other words, it serves as a marker that tells Python whether the file was run directly or loaded through import from another file.

Sample Code to Check __name__ (check_name.py / import_test.py)

Create two files outside the fortune_cookie package: check_name.py and import_test.py. (Place both files in the same directory.)

# check_name.py

print('The __name__ of this file is:', __name__)

This code simply prints the value of __name__. It is intentionally minimal.

# import_test.py

import check_name

Checking How the Value of __name__ Changes

① First, run check_name.py directly. Open check_name.py in Visual Studio Code and execute it.

Output:

The __name__ of this file is: __main__

② Next, import this file from import_test.py. Open import_test.py in Visual Studio Code and execute it.

Output:

The __name__ of this file is: check_name

In summary, the value of __name__ becomes "__main__" when a file is executed directly. When the same file is imported from another file, its value becomes the "module name" (the file name without the .py extension). Python uses this variable to determine how the file was executed.

Understanding and Using if __name__ == '__main__' in Python

By taking advantage of the behavior described above, you can write code like the following:

def main():
    print('Executing main process')

if __name__ == '__main__':
    main()

The meaning of this structure is very simple.

“Only execute main() when this file is run directly.”

By including this conditional, you can prevent main() from running automatically when the module is imported from another file. It acts as a kind of “safety mechanism” to avoid unintended execution.

スポンサーリンク

What Is a Python Namespace? Understanding How Modules Stay Independent

There is an important concept that you should understand alongside this behavior: the “namespace.”

A namespace is an independent container that manages the “names” of variables and functions. In Python, each module has its own separate namespace. Functions and variables defined in one module do not interfere with those in another.

This means that even if the module executed directly, Module A, and Module B all define a function named main(), they are managed completely independently. By calling main(), A.main(), or B.main(), you can execute the main() function in the module you intend to use.

Why Variables Stay Independent Across Modules (With Example Code)

Create three files outside the fortune_cookie package: module_a.py, module_b.py, and main.py, and then run the main module.

# module_a.py
value = 'Value in A'
# module_b.py
value = 'Value in B'
# main.py
import module_a
import module_b

print(module_a.value)
print(module_b.value)

Output:

Value in A
Value in B

Even though the variable name value is the same, each module manages it independently within its own namespace. This is how namespaces work in Python.

Summary of __name__, __main__, and Namespaces

ConceptDescription
__name__A special variable that represents the identifier of a module
"__main__"The value assigned to __name__ when the file is executed directly
if __name__ == '__main__':A structure that runs the enclosed block only when the file is executed directly
NamespaceAn independent management area for distinguishing variables and functions, created for each module
スポンサーリンク