In Python, __main__
serves a crucial purpose. It is used to check whether a Python script is being run directly as the main program or is being imported as a module in another script. This distinction matters because it allows you to control the execution of your script.
Let's illustrate this with a simple example:
# File: mymodule.py
def my_func():
print("This is a function in the module.")
if __name__ == '__main__':
print('This script is running directly.')
else:
print('This script is being imported as a module.')
When you run mymodule.py
directly (e.g., python mymodule.py
in your command line), the Python interpreter sets the special __name__
variable to __main__
. So, the if __name__ == '__main__':
condition becomes True, and "This script is running directly" gets printed.
However, when this script is imported as a module in another script as follows:
# File: another_script.py
import mymodule
mymodule.my_func()
and you run another_script.py
, the Python interpreter sets the __name__
variable to the name of the script being imported (mymodule
in this case). The if __name__ == '__main__':
condition is not satisfied, and "This script is being imported as a module" gets printed.
This feature allows a script to behave differently depending on whether it's run as the main program or imported as a module, providing greater control and flexibility. For example, you might have some code that tests the functions in your module but should not be executed when the module is imported by another script. By placing this test code inside a if __name__ == '__main__':
block, you can ensure it won't run when the module is imported.
As a best practice, it's wise to use if __name__ == '__main__':
to keep your script tidy, distinguish between code that defines your module's functionality and the testing or demo code, and prevent unnecessary code execution when the module is imported.