Python __name__
How __name__ is set, the if __name__ == '__main__' guard, and why it matters for imports.
Key PointsEvery module has a __name__; it equals '__main__' only for the file you ran, which is how a file can be both a library and a script.
What __name__ Holds
When Python imports a module, it sets the module's __name__ to its dotted import path. When you run a file directly, Python sets it to the string "__main__" instead.
Python
# utils.py
print("__name__ is", __name__)
# $ python3 utils.py
# __name__ is __main__
# $ python3 -c "import utils"
# __name__ is utilsThe Guard
Put executable code behind if __name__ == "__main__":. Then importing the module only defines functions and classes — it does not start a server, open a database or send mail.
Python
def fetch(url):
...
def main():
print(fetch("https://api.example.com/health"))
if __name__ == "__main__":
main()Why It Matters
- Without the guard,
import utilsin a test would run the whole program. - It makes a module reusable as both a library and a CLI entry point.
- Multiprocessing on Windows re-imports the module in each child — without the guard you get an infinite spawn loop.
- Packaging tools look for
__main__.pyto supportpython -m package.
Python
# mypkg/__main__.py -> python -m mypkg 时执行
from mypkg.cli import main
if __name__ == "__main__":
main()Common Patterns
| Pattern | Purpose |
|---|---|
| if __name__ == "__main__": | Script entry point |
| if __name__ != "__main__": | Library-only setup |
| __all__ = [...] | Control from x import * |
| __version__ = "1.0" | Package metadata |
__name__ is a module-level variable, not a function. Never assign to it — code that checks it will misbehave.__name__ 里是什么
Python 导入模块时,把模块的 __name__ 设为它的点分导入路径;直接运行某个文件时,则设为字符串 "__main__"。
Python
# utils.py
print("__name__ is", __name__)
# $ python3 utils.py
# __name__ is __main__
# $ python3 -c "import utils"
# __name__ is utils入口守卫
把可执行代码放在 if __name__ == "__main__": 之后。这样导入模块时只会定义函数和类,不会启动服务、连数据库或发邮件。
Python
def fetch(url):
...
def main():
print(fetch("https://api.example.com/health"))
if __name__ == "__main__":
main()为什么重要
- 没有守卫时,测试里
import utils会直接跑完整个程序。 - 让模块既能被当作库复用,又能当命令行入口。
- Windows 下多进程会在每个子进程里重新导入模块 —— 没有守卫就会无限递归创建进程。
- 打包工具靠
__main__.py支持python -m package方式运行。
Python
# mypkg/__main__.py -> python -m mypkg 时执行
from mypkg.cli import main
if __name__ == "__main__":
main()常见写法
| 写法 | 用途 |
|---|---|
| if __name__ == "__main__": | 脚本入口 |
| if __name__ != "__main__": | 仅在作为库导入时初始化 |
| __all__ = [...] | 控制 from x import * 导出 |
| __version__ = "1.0" | 包版本号 |
__name__ 是模块级变量,不是函数。不要给它赋值 —— 依赖它判断的代码会出错。