__name__
and __main__
in PythonIn Python, __name__
and __main__
are special variables that help control the execution of code. They play a crucial role in determining whether a Python file is being run as a standalone script or being imported as a module. This article explains their purpose with examples.
__name__
?In Python, every module has a built-in variable called __name__
. It represents the name of the module. If the module is being run directly, __name__
is set to '__main__'
. If it is being imported, __name__
is set to the module's name.
__name__
# file: mymodule.py print("The value of __name__ is:", __name__)
When you run mymodule.py
directly:
$ python mymodule.py The value of __name__ is: __main__
If you import mymodule
in another file:
# file: main.py import mymodule
Output:
The value of __name__ is: mymodule
if __name__ == '__main__'
The if __name__ == '__main__'
construct is used to execute certain code blocks only when the file is run directly, not when it is imported as a module.
# file: mymodule.py def greet(): print("Hello from mymodule!") if __name__ == '__main__': print("This script is being run directly.") greet()
When you run mymodule.py
directly:
$ python mymodule.py This script is being run directly. Hello from mymodule!
If you import mymodule
in another file:
# file: main.py import mymodule
Output:
# No output from the main block of mymodule.py
You can use the if __name__ == '__main__'
block to test functions or classes within a module.
# file: math_utils.py def add(a, b): return a + b if __name__ == '__main__': # Test the add function print("Testing add function:") print("3 + 5 =", add(3, 5))
Scripts intended to be run independently often include this construct to prevent unintended execution when imported.
# file: script.py def main(): print("Running as a standalone script.") if __name__ == '__main__': main()
Using this construct, you can separate reusable functions from script-specific logic, making the module more versatile.
__name__
variable is set to '__main__'
when the file is run directly.if __name__ == '__main__'
block ensures that certain code runs only when the script is executed directly.Understanding __name__
and __main__
is crucial for Python programming. They provide a clean way to differentiate between standalone execution and module usage, making your code more organized and reusable.