Skip to content

bpo-39452: Improve the __main__ module documentation #14487

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 17 additions & 16 deletions Doc/library/__main__.rst
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@

:mod:`__main__` --- Top-level script environment
================================================
:mod:`__main__` --- Top-level code environment
==============================================

.. module:: __main__
:synopsis: The environment where the top-level script is run.
:synopsis: The environment where top-level code is run.

--------------

``'__main__'`` is the name of the scope in which top-level code executes.
A module's __name__ is set equal to ``'__main__'`` when read from
standard input, a script, or from an interactive prompt.
``'__main__'`` is the name of the environment where top-level code is run. A
module's ``__name__`` is set equal to ``'__main__'`` when the module is
initialized from an interactive prompt, from standard input, from a file
argument, from a :option:`-c` argument or from a :option:`-m` argument, but not
when it is initialized from an import statement.

A module can discover whether or not it is running in the main scope by
A module can discover whether or not it is running in the main environment by
checking its own ``__name__``, which allows a common idiom for conditionally
executing code in a module when it is run as a script or with ``python
-m`` but not when it is imported::
executing code when the module is not initialized from an import statement::

if __name__ == "__main__":
# execute only if run as a script
main()
if __name__ == '__main__':
# Execute when the module is not initialized from an import statement.
main()

For a package, the same effect can be achieved by including a
``__main__.py`` module, the contents of which will be executed when the
module is run with ``-m``.
For a package, the same effect can be achieved by including a __main__.py
module, the contents of which will be executed when the package is initialized
from a file argument or from a :option:`-m` argument, but not when it is
initialized from an import statement.