How to Use __name__ in Python

Contents
In this article, you will learn how to use __name__ in Python.
How to Use __name__
The __name__ is a special built-in variable in Python that is automatically set when a module is executed. It is a string that holds the name of the module as a string. The value of __name__ can be either “__main__” or the name of the module, depending on how the module is being executed.
Here’s how you can use __name__ in Python:
if __name__ == "__main__":
# code that only runs when this module is run as the main program
# (not imported as a module)
# ...
else:
# code that only runs when this module is imported as a module
# ...
This can be useful when writing scripts or reusable code modules. When a module is executed as the main program, the code inside the if __name__ == “__main__”: block will be executed, but when the module is imported as a module into another script, the code inside the if __name__ == “__main__”: block will not be executed, but the rest of the code will.
For example, consider the following module, example.py:
def some_function():
print("This function is defined in the module")
if __name__ == "__main__":
print("This module is being run as the main program")
some_function()
If you run example.py as the main program, you will get the following output:
This module is being run as the main program
This function is defined in the module
If you import example as a module into another script, you will not see the output This module is being run as the main program, but you will be able to call the some_function:
import example
example.some_function()
# Output: This function is defined in the module