In our posts on modules (Post #109, Post #110), we learned how to separate our code into multiple files. We saw that when you import
a module, Python executes that file’s code from top to bottom. This leads to an important question: what if a file contains code that should only run when you execute that file directly, and not when it’s imported by another script?
In this post, we will demystify one of the most common and important idioms in Python: the if __name__ == '__main__'
block. This is the standard way to make a Python file work as both a reusable module and a runnable script.
The Problem: Code That Runs on Import
Let’s demonstrate the problem. Imagine we add some test or example code to the bottom of our my_math_functions.py
file to show that our add
function works.
my_math_functions.py
:
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
def subtract(a, b):
"""Returns the difference of two numbers."""
return a - b
# Add some example code at the bottom of the file
print("--- Running my_math_functions.py as a script ---")
result = add(5, 3)
print(f"A test of the add function: 5 + 3 = {result}")
Now, let’s look at our main.py
file, which simply imports and uses the module.
main.py
:
import my_math_functions
print("--- Running main.py ---")
total = my_math_functions.subtract(100, 50)
print(f"The result from main.py is: {total}")
When you run main.py
from your terminal (python3 main.py
), you’ll see a surprising output:
--- Running my_math_functions.py as a script ---
A test of the add function: 5 + 3 = 8
--- Running main.py ---
The result from main.py is: 50
The test code from our module ran! This happens because the import
statement executes the entire my_math_functions.py
file. This is not what we want; we only want our main script’s output.
The Magic Variable: __name__
To solve this, Python provides a special, built-in variable for every script called __name__
(pronounced “dunder-name,” for double underscore).
This variable’s value is automatically set by Python and depends on how the file is being used:
- When a file is run directly from the command line (e.g.,
python3 my_script.py
), Python sets that script’s__name__
variable to the special string"__main__"
. - When a file is imported into another script, Python sets its
__name__
variable to the name of the module (i.e., the filename, like"my_math_functions"
).
The Solution: The if __name__ == "__main__"
Block
We can use this behavior to create a block of code that only runs when the file is the main program.
if __name__ == "__main__":
# This code will only run when the script is executed directly.
# It will NOT run when the script is imported.
This line of code literally asks Python, “Is this file the main program being run right now?” If the answer is True
, the code inside the block will run. If the file is just being imported, the condition will be False
, and the block will be skipped.
Putting It Into Practice
Let’s fix our my_math_functions.py
file by putting our test code inside this special if
block.
my_math_functions.py
(Corrected):
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
def subtract(a, b):
"""Returns the difference of two numbers."""
return a - b
# This block will ONLY run if this file is executed directly
if __name__ == "__main__":
print("--- Running my_math_functions.py as a script ---")
result = add(5, 3)
print(f"A test of the add function: 5 + 3 = {result}")
Now, let’s test both scenarios:
1. Importing the Module: Run main.py
again.
python3 main.py
This time, you will see that the test code from the module does not run. The import is clean.
--- Running main.py ---
The result from main.py is: 50
2. Running the Module Directly: Now, run my_math_functions.py
itself from your terminal.
python3 my_math_functions.py
This time, the test code will run, because for this execution, its __name__
is equal to '__main__'
.
--- Running my_math_functions.py as a script ---
A test of the add function: 5 + 3 = 8
What’s Next?
The if __name__ == '__main__'
block is a fundamental part of writing reusable Python modules. It gives you the power to create a file that can be cleanly imported by other scripts, while also containing code (like tests, examples, or main application logic) that can be run when you execute the file itself.
This post concludes the new concepts for Part 4. We’ve learned what functions are, how to pass data to them, how their scope works, and how to organize them into modules. It’s time to combine all these skills. In Post #112, we will recap Part 4 and build a modular calculator program.
Author

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com