Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python __name__ and __main__

Python name The difference between main

When reading Python code, we often see the following at the end of a file:

if __name__ == "__main__":
    main()

What does this code mean? Why do so many Python programs use this pattern?

In Python,__name__ is a special attribute of a module, and"__main__" is the name used to identify the main executing module.

By checking whether __name__ is equal to "__main__", we can tell whether the current module is running as the program entry point or being imported as an ordinary module.

This pattern is usually used to separate a program'sfunction definitionsThe difference betweenexecution entry point, making code reuse and testing easier.

1、name Variables

__name__ is a special module attribute set automatically by Python to indicate the name of the current module.

Its value depends on how the module is run:

Now create a file called module.py :

Example

module.py

print

(

"Module name: "

,

name

)

Run it directly in the terminal:

python module.py

Output result:

模块名称: __main__

If in another Python file it is imported via import module , the output is:

模块名称: module

This is because under the two ways of running, the value Python sets for the module's __name__ differs.

2、main The meaning of

__main__ is a special module name in Python used to identify the top-level execution environment.

When a Python script is run directly, Python treats the script as the main executing module and sets its __name__ to "__main__"。

For example:

python hello.py

At this point,hello.py The __name__ is "__main__"。

If you use python -m to run a module:

python -m mymodule

for the module executed as the program entry point, its __name__ is also "__main__"。

Therefore,"__main__" is not an ordinary file name, but a special name Python uses to identify the main executing module.

In addition, Python also supports defining a package's execution entry point through a __main__.py file in the package; this approach is often used with python -m 包名 to start programs.

3、if name == "main": the role of

In Python, a file can be run directly or imported by other files.

If test code, command-line interaction or program startup logic is placed at the top level of a module, that code may also run when the module is first imported.

To avoid this, you can use the following check:

if __name__ == "__main__":
    # Only executes when run as the main program
    main()

Where:

For example, here is a complete program that can be run directly:

Example

def

main

(

)

:

   

print

(

"Program starts running"

)

if

name

==

"main"

:

    main

(

)

When run directly, the output is:

程序开始运行

If the file is imported as a module,main() will not be executed automatically because of this check, but the function can still be called explicitly through the module name.

Note:if __name__ == "__main__": only controls whether the code inside it runs; it does not prevent other top-level code in the module from running at import time.


4. A complete example

The following uses two Python files to demonstrate the difference between the same module being run directly and being imported.

Create example.py

First create example.py File:

the example.py file

def

greet

(

)

:

   

print

(

"Greetings from the example module!"

)

if

name

==

"main"

:

   

print

(

"This script is running directly."

)

    greet

(

)

else

:

   

print

(

"This script was imported as a module."

)

Run example.py directly

Execute in the terminal:

python example.py

Output result:

该脚本正在直接运行。
来自 example 模块的问候!

Because example.py is being run directly, so __name__ Equal "__main__", and the code in the if branch is executed.

Import example.py

Next create another file in the same directory another_script.py:

the another_script.py file

another_script.py

import

example

example.

greet

(

)

Execute in the terminal:

python another_script.py

Output result:

该脚本作为模块被导入。
来自 example 模块的问候!

The execution process here is as follows:

  1. Python executes another_script.py。
  2. and encounters import example, loads and executes example.py 's top-level code.
  3. At this point example.__name__ is "example", so the else branch is not executed.
  4. Then it executes example.greet(), printing the greeting.

Therefore,Importing a module does not mean that none of the code in the module will execute; rather, only the code protected by if __name__ == "__main__": will not run during a normal import.

5. Practical use: separating functional code from the execution entry point

In real development, it is usually not necessary to write if __name__ == "__main__": after else branch is not executed.

; the more common approach is to write reusable functions in a module and then use main() to organize the program entry point uniformly.

For example, create calculator.py:

Example

calculator.py

def

add

(

a

,

b

)

:

   

return

a + b

def

multiply

(

a

,

b

)

:

   

return

a * b

def

main

(

)

:

   

print

(

"Addition result: "

,

add

(

10

,

5

)

)

   

print

(

"Multiplication result: "

,

multiply

(

10

,

5

)

)

if

name

==

"main"

:

    main

(

)

Run directly:

python calculator.py

Output result:

加法结果: 15
乘法结果: 50

If imported in another module:

Example

import

calculator

result

=

calculator.

add

(

3

,

7

)

print

(

"Calculation result: "

,

result

)

Output result:

计算结果: 10

In this example, importing calculator does not automatically execute main(), but you can still normally use add() and multiply() function in Vue 3.

This organization lets the same Python file be used for standalone execution, module import and unit testing.

6. python -m and main.py

Besides running a Python file directly, you can also use python -m to execute a module or package.

For example, suppose the project structure is as follows:

myproject/
└── mypackage/
    ├── __init__.py
    └── __main__.py

Where__main__.py with the content:

Example

mypackage/main.py

def

main

(

)

:

   

print

(

"Starting a program via python -m"

)

if

name

==

"main"

:

    main

(

)

in myproject Execute in the directory:

python -m mypackage

Output result:

通过 python -m 启动程序

This is because when Python uses -m to execute a package, it looks for and executes the __main__.py files.

Note:__main__.py is a Python file name with a special purpose, while "__main__" is the name of the main executing module; the two are related but not the same concept.

7. Frequently asked questions

Why does print() still execute when a module is imported?

Because when Python first imports a module normally, it usually executes the module's top-level statements, including function and class definitions as well as print() statements that are not protected by a condition.

For example:

print("模块正在加载")

def hello():
    print("Hello")

Even just executing import modulewill output "module is loading".

If you do not want a piece of code to run at import time, put it inside if __name__ == "__main__": it.

Must every Python file use this check?

No.

If a file only provides functions, classes and other module functionality and does not need to run independently, there is no need to add this check.

If a file needs to support both independent execution and import reuse, using this pattern is usually more appropriate.

Is main() a special function in Python?

No.

main is just an ordinary function name, a naming convention often used by developers for the program entry point.

Python does not require that a main() function must exist, nor that this name must be used.

For example:

def start():
    print("程序启动")


if __name__ == "__main__":
    start()

This form of writing is also valid.

name The difference between file What is the difference?

__name__ represents the module name, while __file__ usually represents the file path corresponding to the module.

For example:

print(__name__)
print(__file__)

When running an ordinary Python script directly,__name__ is usually "__main__", while __file__ is the path of the script file.

Note that modules in some runtime environments may not have a __file__ attribute, for example in some interactive environments and built-in modules.

Summary

The __name__ and __main__ is mainly used to distinguish how a module is executed.

How to run name Typical values of
Run directly python example.py "__main__"
Pass import example Import "example"
Pass import package.module Import "package.module"
Use python -m package.module Executing "__main__"

The most common form is:

if __name__ == "__main__":
    main()

Its purpose is:Run the entry code inside it only when the current module is executed as the main program.

When writing a reusable Python module, it is recommended to wrap the functionality in functions or classes, then use if __name__ == "__main__": to organize the entry point for standalone execution.