02. if __name__ == "__main__"¶
Overview¶
The following document explains the mechanism behind the special code snippet that commonly appears in Python scripts.
if __name__ == "__main__":
# The following code block runs only when this script is executed directly, when the condition is match
pass
Explanation¶
The snippet is related to the concept of the top-level code environment, which is the scope in which the interpreter executes the script directly.
This included 2 parts in the condition: __name__ and special literal of "__main__"
(1) The __name__ variable
The __name__ variable is a built-in variable that holds the name of the current module. When a module is imported, the interpreter sets the __name__ variable to the name of the module.
There are two ways to set the __name__ variable:
- When a module is imported, the interpreter sets the
__name__variable to the name of the module.
Note: This is usually the name of the Python file itself without the .py extension.
If the file is part of a package, __name__ will also include the parent package’s path.
- When a module is executed in the top-level code environment, the interpreter sets the
__name__variable to"__main__".
(2) The literal string of "__main__"
For the description, __main__ is the name of the environment where top-level code is run.
Top-level code” is the first user-specified Python module that starts running.
It’s "top-level" because it imports all other modules that the program needs.
Sometimes "top-level code" is called an entry point to the application.
The top-level code environment is created in one of following ways:
-
The scope of an interactive prompt
-
The Python module passed to the Python interpreter as a file argument
-
The Python module or package passed to the Python interpreter with the -m argument
-
Python code read by the Python interpreter from standard input
-
Python code passed to the Python interpreter with the -c argument.
For the example, reference to __main__.html detail from Python
Based on that, the idiom checks if the __name__ variable equals "__main__", confirming that the script is the top-level module.
This idiom has two main use cases:
-
Preventing unintended code execution during module imports: By checking if the current module is the top-level module, you can ensure that certain code snippets are only executed when the module is run directly (i.e., not when it's imported as a module by another script).
-
Adding script-specific logic: By using this idiom, you can include code that's specific to the script and won't affect module imports.
Please see the detail example more at Realpython if-name-main-python document
Note
For the practice, I has usually it's to with define custom arguments on runtime of execute python scripts