The __name__ Pattern
Make modules that work both as imports and as standalone scripts
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
The problem: code that runs on import
When Python imports a module, it executes every line in that file. If your module contains a function call at the top level, that call runs during import — even if the importing file doesn't want it to.
# math_utils.py
def add(a, b):
return a + b
print(add(2, 3)) # This runs every time someone imports math_utilsAny file that writes import math_utils now prints 5 as a side effect. That's almost never what you want.
The solution: __name__
Every Python file has a built-in variable called __name__. Its value depends on how the file runs:
| How the file runs | Value of __name__ |
|---|---|
Run directly: python math_utils.py | "__main__" |
Imported: import math_utils | "math_utils" |
You use this to guard code that should only run when the file is the main script:
def add(a, b):
return a + b
if __name__ == "__main__":
print(add(2, 3)) # Only runs when you execute this file directlyNow import math_utils loads the add function without printing anything. But running python math_utils.py still prints 5.
Why this pattern exists everywhere
The __name__ guard is Python's convention for making files dual-purpose: importable as a library and runnable as a script. You will see it in almost every Python project. The RAG app you will build later uses it in main.py to start the program.
A common use is to put test code or demo code inside the guard. During development, you run the file directly to test it. In production, other files import its functions cleanly.
Instructions
Build a temperature converter that works as both a module and a standalone script.
- Define a function named
celsius_to_fahrenheitthat takes a parametercelsius. Returncelsius * 9 / 5 + 32. - Define a function named
fahrenheit_to_celsiusthat takes a parameterfahrenheit. Return(fahrenheit - 32) * 5 / 9. - Add the
if __name__ == "__main__":guard. - Inside the guard, call
print()withcelsius_to_fahrenheit(0). - Inside the guard, call
print()withcelsius_to_fahrenheit(100). - Inside the guard, call
print()withfahrenheit_to_celsius(212).
# Step 1: Define celsius_to_fahrenheit(celsius) # Step 2: Define fahrenheit_to_celsius(fahrenheit) # Step 3: Add the __name__ guard # Step 4: Print celsius_to_fahrenheit(0) # Step 5: Print celsius_to_fahrenheit(100) # Step 6: Print fahrenheit_to_celsius(212)
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding