Skip to content

Commit bff3522

Browse files
committed
add help for __name__
1 parent 2aee131 commit bff3522

File tree

3 files changed

+172
-1
lines changed

3 files changed

+172
-1
lines changed

Doc/tools/extensions/pydoc_topics.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
"integers",
7171
"lambda",
7272
"lists",
73+
"name_equals_main",
7374
"naming",
7475
"nonlocal",
7576
"numbers",

Lib/pydoc.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1851,6 +1851,7 @@ def _introdoc():
18511851

18521852
def collect_dunders(symbols):
18531853
dunders = {
1854+
'__name__': ('name_equals_main', ''),
18541855
'__main__': ('__main__', ''),
18551856
'__call__': ('callable-types', 'SPECIALMETHODS'),
18561857
}

Lib/pydoc_data/topics.py

Lines changed: 170 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Autogenerated by Sphinx on Sat Aug 16 20:05:29 2025
1+
# Autogenerated by Sphinx on Mon Aug 18 00:55:48 2025
22
# as part of the release process.
33

44
topics = {
@@ -7211,6 +7211,175 @@ def <lambda>(parameters):
72117211
from left to right and placed into the list object in that order.
72127212
When a comprehension is supplied, the list is constructed from the
72137213
elements resulting from the comprehension.
7214+
''',
7215+
'name_equals_main': r'''"__name__ == '__main__'"
7216+
************************
7217+
7218+
When a Python module or package is imported, "__name__" is set to the
7219+
module’s name. Usually, this is the name of the Python file itself
7220+
without the ".py" extension:
7221+
7222+
>>> import configparser
7223+
>>> configparser.__name__
7224+
'configparser'
7225+
7226+
If the file is part of a package, "__name__" will also include the
7227+
parent package’s path:
7228+
7229+
>>> from concurrent.futures import process
7230+
>>> process.__name__
7231+
'concurrent.futures.process'
7232+
7233+
However, if the module is executed in the top-level code environment,
7234+
its "__name__" is set to the string "'__main__'".
7235+
7236+
7237+
What is the “top-level code environment”?
7238+
=========================================
7239+
7240+
"__main__" is the name of the environment where top-level code is run.
7241+
“Top-level code” is the first user-specified Python module that starts
7242+
running. It’s “top-level” because it imports all other modules that
7243+
the program needs. Sometimes “top-level code” is called an *entry
7244+
point* to the application.
7245+
7246+
The top-level code environment can be:
7247+
7248+
* the scope of an interactive prompt:
7249+
7250+
>>> __name__
7251+
'__main__'
7252+
7253+
* the Python module passed to the Python interpreter as a file
7254+
argument:
7255+
7256+
$ python helloworld.py
7257+
Hello, world!
7258+
7259+
* the Python module or package passed to the Python interpreter with
7260+
the "-m" argument:
7261+
7262+
$ python -m tarfile
7263+
usage: tarfile.py [-h] [-v] (...)
7264+
7265+
* Python code read by the Python interpreter from standard input:
7266+
7267+
$ echo "import this" | python
7268+
The Zen of Python, by Tim Peters
7269+
7270+
Beautiful is better than ugly.
7271+
Explicit is better than implicit.
7272+
...
7273+
7274+
* Python code passed to the Python interpreter with the "-c" argument:
7275+
7276+
$ python -c "import this"
7277+
The Zen of Python, by Tim Peters
7278+
7279+
Beautiful is better than ugly.
7280+
Explicit is better than implicit.
7281+
...
7282+
7283+
In each of these situations, the top-level module’s "__name__" is set
7284+
to "'__main__'".
7285+
7286+
As a result, a module can discover whether or not it is running in the
7287+
top-level environment by checking its own "__name__", which allows a
7288+
common idiom for conditionally executing code when the module is not
7289+
initialized from an import statement:
7290+
7291+
if __name__ == '__main__':
7292+
# Execute when the module is not initialized from an import statement.
7293+
...
7294+
7295+
See also:
7296+
7297+
For a more detailed look at how "__name__" is set in all situations,
7298+
see the tutorial section Modules.
7299+
7300+
7301+
Idiomatic Usage
7302+
===============
7303+
7304+
Some modules contain code that is intended for script use only, like
7305+
parsing command-line arguments or fetching data from standard input.
7306+
If a module like this was imported from a different module, for
7307+
example to unit test it, the script code would unintentionally execute
7308+
as well.
7309+
7310+
This is where using the "if __name__ == '__main__'" code block comes
7311+
in handy. Code within this block won’t run unless the module is
7312+
executed in the top-level environment.
7313+
7314+
Putting as few statements as possible in the block below "if __name__
7315+
== '__main__'" can improve code clarity and correctness. Most often, a
7316+
function named "main" encapsulates the program’s primary behavior:
7317+
7318+
# echo.py
7319+
7320+
import shlex
7321+
import sys
7322+
7323+
def echo(phrase: str) -> None:
7324+
"""A dummy wrapper around print."""
7325+
# for demonstration purposes, you can imagine that there is some
7326+
# valuable and reusable logic inside this function
7327+
print(phrase)
7328+
7329+
def main() -> int:
7330+
"""Echo the input arguments to standard output"""
7331+
phrase = shlex.join(sys.argv)
7332+
echo(phrase)
7333+
return 0
7334+
7335+
if __name__ == '__main__':
7336+
sys.exit(main()) # next section explains the use of sys.exit
7337+
7338+
Note that if the module didn’t encapsulate code inside the "main"
7339+
function but instead put it directly within the "if __name__ ==
7340+
'__main__'" block, the "phrase" variable would be global to the entire
7341+
module. This is error-prone as other functions within the module
7342+
could be unintentionally using the global variable instead of a local
7343+
name. A "main" function solves this problem.
7344+
7345+
Using a "main" function has the added benefit of the "echo" function
7346+
itself being isolated and importable elsewhere. When "echo.py" is
7347+
imported, the "echo" and "main" functions will be defined, but neither
7348+
of them will be called, because "__name__ != '__main__'".
7349+
7350+
7351+
Packaging Considerations
7352+
========================
7353+
7354+
"main" functions are often used to create command-line tools by
7355+
specifying them as entry points for console scripts. When this is
7356+
done, pip inserts the function call into a template script, where the
7357+
return value of "main" is passed into "sys.exit()". For example:
7358+
7359+
sys.exit(main())
7360+
7361+
Since the call to "main" is wrapped in "sys.exit()", the expectation
7362+
is that your function will return some value acceptable as an input to
7363+
"sys.exit()"; typically, an integer or "None" (which is implicitly
7364+
returned if your function does not have a return statement).
7365+
7366+
By proactively following this convention ourselves, our module will
7367+
have the same behavior when run directly (i.e. "python echo.py") as it
7368+
will have if we later package it as a console script entry-point in a
7369+
pip-installable package.
7370+
7371+
In particular, be careful about returning strings from your "main"
7372+
function. "sys.exit()" will interpret a string argument as a failure
7373+
message, so your program will have an exit code of "1", indicating
7374+
failure, and the string will be written to "sys.stderr". The
7375+
"echo.py" example from earlier exemplifies using the
7376+
"sys.exit(main())" convention.
7377+
7378+
See also:
7379+
7380+
Python Packaging User Guide contains a collection of tutorials and
7381+
references on how to distribute and install Python packages with
7382+
modern tools.
72147383
''',
72157384
'naming': r'''Naming and binding
72167385
******************

0 commit comments

Comments
 (0)