I. What Is name
__name__ is a special attribute that Python automatically sets for modules, used to represent the name of the current module.
Every Python module has its own __name__ attribute. When a module runs in different ways, this attribute may have different values.
1. The Simplest Example
Create a file example.py:
print(__name__)
Execute it directly:
python example.py
Output:
__main__
If you import it in another file:
import example
The output is usually:
example
This shows:
- When a module file is executed directly,
__name__is usually"__main__". - When imported as an ordinary module,
__name__is usually the module's import name.
2. The Nature of name
__name__ is not a Python keyword; it is a special attribute of the module object.
You can inspect it as follows:
import math
print(math.__name__)
Output:
math
You can also inspect the current module:
print(__name__)
Its value is determined by Python's module execution and import mechanisms, not unconditionally by the file name.
3. Common Module Attributes
Python modules also have several other important attributes:
| Attribute | Purpose |
|---|---|
__name__ |
The name of the current module |
__file__ |
The file path corresponding to the module; some modules may not have it |
__package__ |
The name of the package the module belongs to |
__doc__ |
The module docstring |
__spec__ |
The module's import specification information |
__loader__ |
The module loader |
__path__ |
The search path for a package's submodules |
Together, these attributes describe a module's identity, origin, and import context.
II. What Is main
__main__ is the special module name Python uses for a program's main execution environment.
When Python executes a piece of code as the program entry point, the module containing that code usually uses __main__ as its module name.
1. Executing a Python File Directly
Create hello.py:
print("Hello Python")
print(__name__)
Execute:
python hello.py
Output:
Hello Python
__main__
Here, Python executes hello.py as the program entry point, so its __name__ is "__main__".
2. Importing It as a Module
Create main.py:
import hello
print("主程序运行")
Execute:
python main.py
Output:
Hello Python
hello
主程序运行
Two different execution processes happen here:
main.pyis the entry module of the current program, and its__name__is"__main__".hello.pyis imported as a module, and its__name__is"hello".
Note that when a module is imported, its top-level code still executes. __name__ does not prevent module code from executing; it merely provides information about the module's current running identity.
III. Basic Usage of if name == "main"
Python development often uses the following structure:
def main():
print("程序开始执行")
if __name__ == "__main__":
main()
The meaning of this code is:
Only when the current module is running as __main__ is main() called.
1. When executed directly
Run:
python example.py
At this point:
__name__ == "__main__"
The condition is true, so it executes:
main()
2. When imported by another module
For example:
import example
At this point, the __name__ of example.py is usually "example".
The condition is false, so the main() in the main program entry point is not executed.
However, note that module top-level code outside the entry-point check will still be executed.
3. Overall execution flow
flowchart TD
A["Python module execution"] --> B["Set the module's __name__"]
B --> C{"Is __name__ equal to __main__?"}
C -->|Yes| D["Execute the main program entry point"]
C -->|No| E["Skip the main program entry point"]
D --> F["Continue executing program logic"]
E --> G["Module import complete"]
F --> H["Program ends"]
G --> I["Caller continues execution"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
IV. Why Do We Need a Main Program Entry Point?
If a Python file contains both function definitions and actual runtime logic, then when other modules import it, they may accidentally execute that runtime logic.
1. The problem without an entry-point check
Suppose there is a file calculator.py:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
print("初始化计算器")
print(add(10, 20))
When another module executes:
import calculator
it will output:
Initializing calculator
30
Even if the caller only wants to use add(), the print statements at the top level of the module will still be executed.
If the module includes operations such as database connections, file writes, or starting services, it may cause more serious side effects.
2. Improving it with a main program entry point
Change it to:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def main():
print("初始化计算器")
print(add(10, 20))
if __name__ == "__main__":
main()
Now:
When executed directly:
python calculator.py
it will run main().
When importing the module:
import calculator
print(calculator.add(10, 20))
Only module definitions such as functions and variables will be executed; main() will not run automatically.
3. The problems solved by the main program entry point
| Problem | Solution |
|---|---|
| Business logic accidentally executed on import | Put the running code inside an entry function |
| Functions cannot be reused by other modules | Separate function definitions from the program entry point |
| Unnecessary operations triggered during testing | Skip the entry code when importing the module |
| Program execution logic is scattered | Manage it uniformly through main() |
| Module responsibilities are unclear | Distinguish feature definitions from application startup |
V. The Difference Between the main Function and main
main() and __main__ often appear together, but they are completely different concepts.
1. main Is an Ordinary Function
For example:
def main():
print("程序入口")
main is just an ordinary function name.
Python does not require every program to define main(), nor does it call this function automatically.
The following code is equally valid:
def start():
print("开始运行")
if __name__ == "__main__":
start()
2. main Is a Special Module Name
__main__ is the module name that Python uses in the main execution environment.
It is not a function, and it is not a keyword either.
3. The Relationship Between the Two
def main():
print("Hello Python")
if __name__ == "__main__":
main()
Here:
main()is responsible for organizing the program's execution logic.__main__is used to determine whether the current module has the main execution identity.- The
ifcondition decides whether to callmain().
It can be understood as:
__main__: determines whether the current module is the program entry point
main(): organizes the concrete execution process of the program
VI. The Standard Way to Write a Main Program Entry
In real-world development, it is recommended to use a main() function to organize the program entry point.
1. Basic Structure
def main():
print("程序开始")
if __name__ == "__main__":
main()
This structure suits simple scripts and small tools.
2. Including a Return Value
You can have main() return an integer status code:
def main():
print("执行任务")
return 0
if __name__ == "__main__":
result = main()
print("退出状态:", result)
Where:
0usually indicates successful execution.- A non-zero value usually indicates that an error occurred.
3. Using sys.exit
For command-line programs, a more common approach is:
import sys
def main():
print("执行任务")
return 0
if __name__ == "__main__":
sys.exit(main())
sys.exit() ends the program by raising SystemExit.
When an integer is passed in, that integer is usually used as the process exit status code:
0means success.- A non-zero value means failure or some other state.
You can also pass in a string directly; Python will print it to the standard error stream and exit with a non-zero status.
4. Why sys.exit(main()) Is Recommended
This style of writing has several advantages:
- The main logic is concentrated in
main(). - The function can be imported and reused by other modules.
- The return value can express the result of the program's execution.
- Command-line tools can use standard exit status codes.
- Unit tests can directly test the return value of
main().
Note that sys.exit(main()) is not mandatory. A simple script can call main() directly; it is only necessary when you need explicit control over the process exit status.
VII. Command-Line Arguments and the Main Program Entry
__main__ is often used for entry-point control in command-line programs.
Python provides mechanisms such as sys.argv and argparse for handling command-line arguments.
1. Using sys.argv
Create calculator.py:
import sys
def main():
if len(sys.argv) < 3:
print("用法:python calculator.py 数字1 数字2")
return 1
a = float(sys.argv[1])
b = float(sys.argv[2])
print("结果:", a + b)
return 0
if __name__ == "__main__":
sys.exit(main())
Run:
python calculator.py 10 20
Output:
结果:30.0
sys.argv is a list:
| Index | Meaning |
|---|---|
sys.argv[0] |
Program name or script path provided at startup |
sys.argv[1] |
First command-line argument |
sys.argv[2] |
Second command-line argument |
2. Using argparse
For complex command-line programs, the standard library argparse is recommended.
import argparse
def main():
parser = argparse.ArgumentParser(
description="简单计算器"
)
parser.add_argument("a", type=float)
parser.add_argument("b", type=float)
parser.add_argument(
"--operation",
choices=["add", "subtract"],
default="add"
)
args = parser.parse_args()
if args.operation == "add":
result = args.a + args.b
else:
result = args.a - args.b
print(result)
return 0
if __name__ == "__main__":
raise SystemExit(main())
Run:
python calculator.py 10 20 --operation add
Output:
30.0
Here, the main program entry point is responsible for starting the command-line application, while argparse is responsible for argument parsing.
3. Execution flow of a command-line program
flowchart TD
A["Start Python program"] --> B["Set __main__ identity"]
B --> C["Call main"]
C --> D["Create argument parser"]
D --> E["Parse command-line arguments"]
E --> F{"Are arguments valid?"}
F -->|No| G["Output error or help information"]
F -->|Yes| H["Execute application logic"]
H --> I{"Did execution succeed?"}
I -->|Yes| J["Return status code 0"]
I -->|No| K["Return non-zero status code"]
J --> L["End process"]
K --> L
G --> L
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style L fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
8. Differences Between Directly Running a Python File and Using python -m
There are two common ways to run a Python module:
python example.py
And:
python -m example
Both can run code as the main execution module, but they differ in module identity, import context, and search path.
1. Directly Executing a File
python example.py
Python executes the specified file as a script.
It usually has the following characteristics:
__name__is"__main__".sys.argv[0]is usually the script path.- The initial search path usually includes the directory containing the script.
- The file usually does not have the relative import context of a normal package module.
2. Executing a Module with -m
python -m package.example
Python first locates the module through the module import mechanism, then executes it as the main program.
It usually has the following characteristics:
__name__is"__main__".__spec__.nameretains the canonical name of the module.sys.argv[0]is usually the file path corresponding to the executed module.- The module can obtain the corresponding package context.
- It is more suitable for running modules within a package.
3. Comparison of the Two Execution Methods
| Comparison Item | python example.py |
python -m package.example |
|---|---|---|
| Execution target | File path | Module name |
__name__ |
__main__ |
__main__ |
__spec__ |
Usually None |
Usually contains the module spec |
| Package context | Usually absent | Can be established |
| Relative imports | Usually unavailable | Available in a valid package structure |
| Typical use | Standalone script | Module within a package |
4. How python -m Works
flowchart TD
A["Run python -m package.module"] --> B["Resolve module name"]
B --> C["Find the module through the import system"]
C --> D{"Module found?"}
D -->|No| E["Import failed"]
D -->|Yes| F["Get module spec"]
F --> G["Execute as the main program"]
G --> H["Set __name__ to __main__"]
H --> I["Execute module code"]
I --> J["Program ends"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style J fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
5. Why -m Is Recommended Inside Packages
Suppose the project structure is:
my_project/
├── main.py
└── app/
├── __init__.py
├── utils.py
└── services/
├── __init__.py
└── user_service.py
In user_service.py:
from ..utils import get_logger
def main():
print(get_logger())
if __name__ == "__main__":
main()
Run directly:
python app/services/user_service.py
This usually results in a relative import error.
Run from the project root:
python -m app.services.user_service
then the module can be executed in the correct package context.
Note that -m is not required in every scenario. Directly executing a standalone script is perfectly reasonable, but modules inside a package should preferably be run using their module path.
9. main and Module Import Cache
Understanding __name__ also requires understanding Python's module caching mechanism.
1. The Role of sys.modules
Python uses sys.modules to cache module objects that have been loaded or are being initialized.
For example:
import sys
import math
print("math" in sys.modules)
print(sys.modules["math"])
When a module already exists in the cache, subsequent imports usually reuse the existing module object.
2. The Difference Between the Main Module and Imported Modules
Running directly:
python example.py
Python places the program entry module in:
sys.modules["__main__"]
When other modules import example, it is usually placed in:
sys.modules["example"]
with the corresponding module object stored there.
These two names may correspond to different module objects even if they come from the same file.
3. Why the Same File May Have Two Module Identities
Suppose:
# example.py
class User:
pass
print(__name__)
Running directly:
python example.py
In this case, the file is executed under the __main__ identity.
If the program also executes the following while running:
import example
and example has not yet been imported normally, Python may load the same source file again and create another module object.
At this point, there may be:
import __main__
import example
print(__main__.User is example.User)
The result may be:
False
The reason is that the two module objects each created their own User class object.