__name__ == '__main__'
In Python, the __name__ == '__main__'
construct is commonly used to control the behavior of a script. It allows a Python file to act as either a standalone program or a module that can be imported into other programs. Understanding how and when to use __name__ == '__main__'
is essential for writing reusable and modular code.
__name__
?The __name__
variable in Python is a built-in special variable. It is used to determine whether a Python script is being run directly or being imported as a module into another script.
__name__
variable is set to '__main__'
.__name__
variable is set to the name of the script (i.e., the filename without the .py
extension).if __name__ == '__main__'
The if __name__ == '__main__'
construct is a conditional statement that checks if the script is being executed as the main program. If the script is executed directly, the code block under this condition is executed. If the script is imported as a module, the code block is skipped.
if __name__ == '__main__':
# Code to be executed when the script is run directly
__name__ == '__main__'
Consider a script called my_module.py
that contains a function and some logic to print a message.
# my_module.py
def greet(name):
print(f"Hello, {name}!")
if __name__ == '__main__':
# This will run only if the script is executed directly
greet("Alice")
If you run my_module.py
directly from the command line:
$ python my_module.py
Output:
Hello, Alice!
If you import my_module.py
into another script:
# another_script.py
import my_module
my_module.greet("Bob")
The output will only show:
Hello, Bob!
Notice that the greet("Alice")
inside if __name__ == '__main__'
was not executed because my_module.py
was imported, not run directly.
if __name__ == '__main__'
Using __name__ == '__main__'
allows you to write reusable code that can either be run standalone or imported into other scripts without executing unnecessary code.
# calculate.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
if __name__ == '__main__':
# Only run the following code if the script is executed directly
print("This script is being run directly")
result = add(5, 3)
print(f"5 + 3 = {result}")
Now, calculate.py
can be imported into another script without executing the code inside if __name__ == '__main__'
:
# another_script.py
import calculate
result = calculate.add(10, 5)
print(f"10 + 5 = {result}")
In this case, the code inside the if __name__ == '__main__'
block is not executed when calculate.py
is imported, keeping the behavior modular.
A common use case is testing functions in a module. If you want to run some tests or example usage when the module is executed directly, but not when it is imported, you can use this construct.
# math_utils.py
def square(x):
return x * x
def cube(x):
return x * x * x
if __name__ == '__main__':
# This test code runs only when the file is executed directly
print(square(4)) # Output: 16
print(cube(3)) # Output: 27
When you run math_utils.py
directly:
$ python math_utils.py
It will execute the test code under if __name__ == '__main__'
. However, if you import math_utils.py
into another script, only the functions square()
and cube()
are available, and the test code is ignored.
The __name__ == '__main__'
pattern enables a Python file to serve dual purposes: as both a module and a script. This is especially useful for building reusable libraries while still allowing testing or demonstration of functionality when executed directly.
Direct Execution: When you run a Python script directly, the Python interpreter sets __name__
to '__main__'
in that script.
Import as a Module: When the script is imported as a module, the interpreter sets __name__
to the name of the file/module (without the .py
extension).
Thus, the block inside if __name__ == '__main__'
only executes when the script is executed directly, but not when imported.
Here’s an example of how a file can act both as a module and as a script with tests or demo code.
# demo.py
def add(x, y):
return x + y
def multiply(x, y):
return x * y
if __name__ == '__main__':
# Code for standalone execution or testing
print("Running as a script")
print(f"Add: {add(5, 3)}")
print(f"Multiply: {multiply(5, 3)}")
else:
# Code for importing as a module
print("Imported as a module")
demo.py
directly:$ python demo.py
Output:
Running as a script
Add: 8
Multiply: 15
demo.py
into another script:# main.py
import demo
# We can use the functions, but the code inside `if __name__ == '__main__'` won't run.
print(demo.add(10, 2))
Output:
Imported as a module
12
if __name__ == '__main__'
block.if __name__ == '__main__'
to organize code that should only run when the script is executed directly, such as tests or examples.Using if __name__ == '__main__'
is a good practice when you have a script that may serve as both a standalone program and a reusable module.
With __name__ == '__main__'
, you can keep your Python code clean, modular, and reusable across different projects, while still allowing it to function properly when run directly. This is a powerful feature that helps maintain code organization and reusability.