Python Glossary Русский

all Python 3Modules & importsconstruct

if __name__ == "__main__":

running

Guards code that should run only when the file is executed as a program (python file.py or python -m mod), not when it is imported.

Syntax

def main():
    ...

if __name__ == "__main__":
    main()

Python sets __name__ to the module name on import ('tool', 'pkg.tool') and to the string '__main__' for a file run directly or via python -m. Without the guard, all top-level code runs on every import: tests that import your script, or a neighbour module that needs one function, suddenly run the whole program — with input(), file writes and long computations. multiprocessing on Windows and macOS starts children with the spawn method: every child re-imports the main module, so without the guard processes spawn recursively and Python fails with RuntimeError. Usually the guard holds a single call to main(), so the logic can be imported and tested on its own.

Examples

import sys
sys.path.insert(0, '.')  # искать модули и в текущем каталоге
with open('tool.py', 'w', encoding='utf-8') as f:
    f.write("def main():\n    print('программа запущена')\n"
            "print('__name__ =', __name__)\n"
            "if __name__ == '__main__':\n    main()\n")
import tool  # → __name__ = tool — а main() под защитой не вызвана
print(__name__)  # → __main__ — этот файл запущен как программа
tool.main()  # → программа запущена — функцию можно вызвать явно

See also

Open in the full glossarydocs.python.orgReport an inaccuracy