Python __name__ and __main__
We often see Python code like this:
In Python, __name__ and __main__ are two special variables related to module and script execution.
__name__ and __main__ are typically used to control how code is executed, especially when a module can be run as a standalone script or imported by other modules.
1. The __name__ Variable
Section titled “1. The __name__ Variable”__name__ is a built-in variable used to represent the name of the current module.
The value of __name__ depends on how the module is used:
When the module is run as the main program: the value of __name__ is set to “__main__”.
When the module is imported: the value of __name__ is set to the module’s filename (excluding the .py extension).
Suppose we have a module.py file:
The output would be:
2. The Meaning of __main__
Section titled “2. The Meaning of __main__”__main__ is a special string used to indicate that the current module is being run as the main program.
__main__ is typically used together with the __name__ variable to determine whether a module is being imported or run as a standalone script.
3. The Common Pattern of if __name__ == “__main__”:
Section titled “3. The Common Pattern of if __name__ == “__main__”:”In Python, it is common practice to add the following code block at the end of a module:
Example
Section titled “Example”This pattern allows the module to not execute certain code when imported, and only execute that code when run as a standalone script.
Example
Section titled “Example”Suppose we have a module named example.py:
example.py Module File:
Section titled “example.py Module File:”Running example.py Directly
Section titled “Running example.py Directly”If you run example.py directly, the output will be:
In this case, the value of __name__ is “__main__”, so the code in the if __name__ == “__main__”: block is executed.
Importing example.py
Section titled “Importing example.py”If you import example.py in another script, for example:
Example
Section titled “Example”The output will be:
In this case, the value of __name__ is “example” (the module name), so the code in the if __name__ == “__main__”: block is not executed.
Summary
Section titled “Summary”-
__name__is a built-in variable that represents the name of the current module. -
When the module is run as the main program, the value of
__name__is"__main__". -
When the module is imported, the value of
__name__is the module’s filename. -
Using
if __name__ == "__main__":controls whether certain code is executed when the module is imported, and only executes that code when running as a standalone script.