The __name__ Pattern
Exit

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_utils

Any 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 runsValue 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 directly

Now 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.

  1. Define a function named celsius_to_fahrenheit that takes a parameter celsius. Return celsius * 9 / 5 + 32.
  2. Define a function named fahrenheit_to_celsius that takes a parameter fahrenheit. Return (fahrenheit - 32) * 5 / 9.
  3. Add the if __name__ == "__main__": guard.
  4. Inside the guard, call print() with celsius_to_fahrenheit(0).
  5. Inside the guard, call print() with celsius_to_fahrenheit(100).
  6. Inside the guard, call print() with fahrenheit_to_celsius(212).