Two key constructs in Python refer to as __main__:
the name of the program’s top-level environment, as determined by the __name__ == ‘__main__’ statement; and in Python packages, the main .py file
Both of these techniques with Python modules, specifically how users interact with them and how they interact with one another. They describe in full further down. If you’re new to Python modules, start with the Modules part of the tutorial.
'__main__' == __name__
When a Python module or package import, the name of the module is set to __name__. Without the.py extension, this is usually the name of the Python file itself:
In Python scripts, the if __name__ == “__main__” expression is fairly common. It can, however, be perplexing at times. The purpose of this article is to explain the behavior of the statement and to discuss when it should use. So let’s get this party started!
Contents
What does it mean to work in a “top-level coding environment”?
The name of the environment in which top-level code runs is __main__. The first user-specified Python module that runs call “top-level code.” It’s “top-level” because it imports all of the program’s other modules. An application’s “entry point” is sometimes referred to as “top-level code.”
The top-level code environment can be one of the following:
- an interactive prompt’s scope:
- >>> ‘__main__’ __name__
- the Python module supplied as a file parameter to the Python interpreter:
- helloworld.py $ python3
Hello, universe!
the -m parameter specifies a Python module or packages to provide to the Python interpreter:
python3 -m python3 -m python3 -m tarfile.py is a Python script that may use to create a tar file. [-h] [-v] (…)
The Python interpreter reads the following Python code from standard input:
| python3 echo “import this”
Tim Peters’ The Zen of Python
Beautiful is preferable to ugly.
Explicit is preferable to implicit.
The -c parameter used to pass Python code to the Python interpreter:
python3 -c “import this” $ python3 -c “import this”
Tim Peters’ The Zen of Python
Beautiful is preferable to ugly.
Explicit is preferable to implicit.
The top-level module’s __name__ is set to ‘__main__’ in each of these cases.
As a result, a module can check its own __name__ to see if it is running in the top-level environment, allowing a popular idiom for conditionally executing functions when the module is not created from an import statement:
Use of Idioms
Some modules include code that is exclusively meant to use scripts, such as processing command-line arguments or retrieving data from standard input. If a module like this is from another module, say to unit test it, the script code would execute accidentally.
This is when the code block if __name__ == ‘__main__’ comes in handy. This block’s code will not run unless the module run in the top-level environment.
If __name___ == ‘__main__’, including as few statements as feasible in the block below can improve code clarity and correctness. Typically, the main function encompasses the program’s core behavior:
# python echo.py
import sys import shlex
“””A dummy wrapper around print.””” def echo(str) -> None: “””A dummy wrapper around print.”””
# You might imagine that there is some # valuable and reusable logic inside this function print for demonstration reasons (phrase)
“””Echo the input parameters to standard output””” def main() -> int: “””Echo the input arguments to standard output”””
echo(sys.argv) return 0 phrase = shlex.join(sys.argv)
if __name__ is equal to ‘__main__’:
sys.exit(main()) # The following section demonstrates how to utilise sys.exit.
The phrase variable would be global to the entire module if the module didn’t enclose code inside the main function and instead put it immediately within the if __name__ == ‘__main__’ block. Other functions within the module may mistakenly use the global variable instead of a local name, making this error-prone. This issue solves using the main function.
Using the main function has the added benefit of isolating and exporting the echo function separately. The echo and main functions will define when echo.py but neither will invoke because name != ‘ main ‘.