Skip to content

bpo-39452: rewrite and expand __main__.rst #26883

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

Merged
merged 51 commits into from
Aug 24, 2021
Merged
Show file tree
Hide file tree
Changes from 32 commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
02e9edf
__main__docs: intro and first secton
jdevries3133 Jun 21, 2021
c95f69b
bpo-44494: rewrite of Doc/library/__main__.rst (first draft)
jdevries3133 Jun 23, 2021
235e866
bpo-44494: add blurb
jdevries3133 Jun 23, 2021
a292ab6
Update __main__.rst
geryogam Jun 30, 2019
d7a1999
Update __main__.rst
geryogam Jun 30, 2019
8398f08
Take Steven d’Aprano’s review into account
geryogam Sep 16, 2020
1fcb2af
Rewrap lines
geryogam Sep 16, 2020
2bde063
Remove trailing whitespaces
geryogam Sep 17, 2020
d29fd2a
bpo-39452: rewrite and expansion of __main__.rst
jdevries3133 Jun 23, 2021
4c60f2c
mention runpy
jdevries3133 Jun 29, 2021
2b5f710
add "design patterns" section, fix section title hierarchies
jdevries3133 Jun 29, 2021
7e495d7
add sentence about console_scripts
jdevries3133 Jun 29, 2021
56afeaa
misc formatting; change "Design Patterns" to "Idiomatic Usage"
jdevries3133 Jun 30, 2021
2a398ef
add section about sys.exit(main()) convention
jdevries3133 Jun 30, 2021
1a9956c
make last paragraph 'idiomatic usage'; add comment about maybe deleting
jdevries3133 Jun 30, 2021
c4b5cea
fix linting error (default context used in comment)
jdevries3133 Jun 30, 2021
1f012b4
revise example so that main() does not take arguments
jdevries3133 Jun 30, 2021
f095362
add console_scripts section, remove bad old example
jdevries3133 Jun 30, 2021
c42b706
minor proofreading changes
jdevries3133 Jun 30, 2021
7fe7f1c
implement changes suggest by @merwok
jdevries3133 Jun 30, 2021
c063da1
fix: typos
jdevries3133 Jun 30, 2021
7c6b451
fix wording, slim down example, add reference to relative import docs
jdevries3133 Jul 7, 2021
06bcb09
respond to review from @pradyunsg
jdevries3133 Jul 21, 2021
80756b3
Merge remote-tracking branch 'upstream/main' into bpo-39452__main__docs
jdevries3133 Jul 31, 2021
647c471
add `import __main__` section
jdevries3133 Aug 1, 2021
457bbc9
revisions and proofreading
jdevries3133 Aug 1, 2021
3d9b3b9
eliminate opinionated section about idiomatic usage of `__main__.py`
jdevries3133 Aug 1, 2021
dd68513
proofread `__main__.py` section
jdevries3133 Aug 1, 2021
6ee7090
Merge branch 'main' of github.com:python/cpython into bpo-39452__main…
jdevries3133 Aug 4, 2021
757b03a
incorporate suggested changes from @Fidget-Spinner
jdevries3133 Aug 10, 2021
8e86468
incorporate suggested changes from @yaseppochi
jdevries3133 Aug 10, 2021
f33a081
fix formatting
jdevries3133 Aug 10, 2021
14bad85
name equals main
jdevries3133 Aug 12, 2021
d150674
Merge branch 'main' of github.com:python/cpython into bpo-39452__main…
jdevries3133 Aug 12, 2021
7b987cb
Merge branch 'bpo-39452__main__docs' of github.com:jdevries3133/cpyth…
jdevries3133 Aug 12, 2021
b9db705
also change reference to name equals main section
jdevries3133 Aug 12, 2021
168c774
implement feedback from @holdenweb, python-dev, and @merwork
jdevries3133 Aug 12, 2021
c450171
fix trailing whitespace
jdevries3133 Aug 12, 2021
077e7a4
Remove .bak file
ambv Aug 24, 2021
eb42489
Thorough editing pass
ambv Aug 24, 2021
7c61e78
Move `__main__.py` section above the `import __main__` section
ambv Aug 24, 2021
45a9425
s/command line/command-line/
ambv Aug 24, 2021
073e9d7
Mention asyncio.__main__
ambv Aug 24, 2021
ccb9004
Restore proper document name
ambv Aug 24, 2021
f8630fa
Use proper .. seealso:: sections.
ambv Aug 24, 2021
1e86e02
Appease `make suspicious`
ambv Aug 24, 2021
9c87442
Spell out examples of top-level code environments
ambv Aug 24, 2021
0d4fc8a
Appease double dot alignment aesthetics
ambv Aug 24, 2021
4e51333
Replace lies with truth
ambv Aug 24, 2021
6f0f82c
Improve flow introducing what "top-level code environment" is
ambv Aug 24, 2021
46e7668
Use module names consistently in example
ambv Aug 24, 2021
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
192 changes: 175 additions & 17 deletions Doc/library/__main__.rst
Original file line number Diff line number Diff line change
@@ -1,25 +1,183 @@

:mod:`__main__` --- Top-level script environment
================================================
:mod:`__main__` --- CLIs, import-time behavior, and ``__name__ == '__main__'``
==============================================================================

.. module:: __main__
:synopsis: The environment where the top-level script is run.
:synopsis: Command line interfaces, import-time behavior, and ``__name__ == '__main__'``

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

``'__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.
In Python, ``__main__`` is not a single mechanism in the language, but in fact
is part of two quite different constructs:

1. The ``__name__ == '__main__'`` expression
2. The ``__main__.py`` file in Python packages

Both of these mechanisms are related to Python modules; how users interact with
them and how they interact with each other. See section :ref:`tut-modules`.


.. _name_is_main:

``__name__ == '__main__'``
---------------------------

``'__main__'`` is the name of the environment where top-level code is run.
"Top-level code" means when a Python 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. In any of these situations, the module's
``__name__`` is set equal to ``'__main__'``.

The only other context in which Python code is run is when it is imported
through an import statement. In that case, ``__name__`` is set equal to the
module's name: usually the name of the file without the ``.py`` extension.

As a result, a module can discover whether or not it is running in the
top-level environment by checking its own ``__name__``, which allows a common
idiom for conditionally executing code when the module is not initialized from
an import statement::

if __name__ == '__main__':
# Execute when the module is not initialized from an import statement.
...


Idiomatic Usage
^^^^^^^^^^^^^^^

Putting as few statements as possible in the block below ``if __name___ ==
'__main__'`` can improve code clarity. Most often, a function named *main*
encapsulates the program's primary behavior::

# echo.py

import shlex
import sys


def echo(phrase: str):
"""A dummy wrapper around print."""
# for demonstration purposes, you can imagine that there is some
# valuable and reusable logic inside this function
print(phrase)


def main():
"""Echo the input arguments to standard output"""
echo(shlex.join(sys.argv))


if __name__ == '__main__':
sys.exit(main()) # next section explains the use of sys.exit

This has the added benefit of the *echo* function itself being isolated and
importable elsewhere. When ``echo.py`` is imported, the ``echo`` and ``main``
functions will be defined, but neither of them will be called, because
``__name__ != '__main__'``.


Packaging Considerations
^^^^^^^^^^^^^^^^^^^^^^^^

For detailed documentation on Python packaging, see the
`Python Packaging User Guide. <https://packaging.python.org/>`_

*main* functions are often used to create command line tools by specifying them
as entry points for console scripts. When this is done, pip inserts the
function call into a template script, where the return value of *main* is
passed into :func:`sys.exit`. For example::

sys.exit(main())

Since the call to *main* is wrapped in :func:`sys.exit`, the expectation is
that your function will return some value acceptable as an input to
:func:`sys.exit`; typically, an integer or ``None`` (which is implicitly
returned if your function does not have a return statement).

By proactively following this convention ourselves, our module will have the
same behavior when run directly (``python3 echo.py``) as it will have if we
later package it as a console script entry-point in a pip-installable package.
That is why the ``echo.py`` example from earlier used the ``sys.exit(main())``
convention.


``import __main__``
-------------------

All the values in the ``__main__`` namespace can be imported elsewhere in
Python packages. See section :ref:`name_is_main` for a list of where the
``__main__`` package is in different Python execution scenarios.

Here is an example package that consumes the ``__main__`` namespace::

# namely.py

import __main__

def did_user_define_their_name():
return 'my_name' in dir(__main__)

def print_user_name():
if did_user_define_their_name():
print(__main__.my_name)
else:
print('Tell us your name by defining the variable `my_name`!')

The Python REPL is one example of a "top-level environment", so anything
defined in the REPL becomes part of the ``__main__`` package::

>>> import namely
>>> namely.did_user_define_their_name()
False
>>> namely.print_user_name()
Tell us your name by defining the variable `my_name`!
>>> my_name = 'David'
>>> namely.did_user_define_their_name()
True
>>> namely.print_user_name()
David

The ``__main__`` package is used in the implementation of :mod:`pdb` and
:mod:`rlcompleter`.


``__main__.py`` in Python Packages
----------------------------------

If you are not familiar with Python packages, see section :ref:`tut-packages`.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps we can move discussion on __main__.py semantics to the docs on python packages, and retain only a mention + reference here? Adding __main__.py to an existing example package would avoid the need to describe a new hypothetical package here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is a good idea. On the other hand, I like how this doc compares and contrasts __name__ == '__main__' and __main__.py all in the same place. I'd be interested in what the core dev who reviews this has to say about that.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing to think about as a far as moving this to the documentation about packages is that the documentation about packages uses an audio library as its example. I'm not sure whether shoehorning a CLI into an audio library would be natural? Just something to consider as we think about that route.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yaseppochi is +1 on keeping this as it is. See #26883 (comment) point #4

Most commonly, the ``__main__.py`` file is used to provide a command line
interface for a package. Consider the following hypothetical package,
"bandclass":

.. code-block:: text

bandclass
├── __init__.py
├── __main__.py
└── student.py

``__main__.py`` will be executed when the package itself is invoked
directly from the command line using the :option:`-m` flag. For example::

python3 -m bandclass

This command will cause ``__main__.py`` to run. For more details about the
:option:`-m` flag, see :mod:`runpy`. How you utilize this mechanism will depend
on the nature of the package you are writing, but in this hypothetical case, it
might make sense to allow the teacher to search for students::

# bandclass/__main__.py

import sys
from .student import search_students

A module can discover whether or not it is running in the main scope 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::
student_name = sys.argv[2] if len(sys.argv) >= 2 else ''
print(f'Found student: {search_students(student_name)}')

if __name__ == "__main__":
# execute only if run as a script
main()
Note that ``from .student import search_students`` is an example of a relative
import. This import style must be used when referencing modules within a
package. For more details, see :ref:`tut-modules`; or, more specifically,
:ref:`intra-package-references`.

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 an example of a package using ``__main__.py`` in our standard library, see
:mod:`venv`, and its invocation via ``python3 -m venv [directory]``.
2 changes: 2 additions & 0 deletions Doc/tutorial/modules.rst
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,8 @@ importing module needs to use submodules with the same name from different
packages.


.. _intra-package-references:

Intra-package References
------------------------

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Rewrote ``Doc/library/__main__.rst``. Broadened scope of the document to
explicitly discuss and differentiate between ``__main__.py`` in packages
versus the ``__name__ == '__main__'`` expression (and the idioms that
surround it).