__main__ — 顶层代码环境


在 Python 中,特殊名称 __main__ 用于 2 重要构造:

  1. 程序顶层环境的名称,可以被校验使用 __name__ == '__main__' 表达式; 和

  2. the __main__.py 文件在 Python 包中。

Both of these mechanisms are related to Python modules; how users interact with them and how they interact with each other. They are explained in detail below. If you’re new to Python modules, see the tutorial section 模块 for an introduction.

__name__ == '__main__'

When a Python module or package is imported, __name__ is set to the module’s name. Usually, this is the name of the Python file itself without the .py extension:

>>> import configparser
>>> configparser.__name__
'configparser'