Skip to Content
Python if __name__ == "__main__": What It Does and When You Need It
Intermediate
0 likes
Tutorials

Python if __name__ == "__main__": What It Does and When You Need It

Importing a file runs it. if __name__ == "__main__" keeps a file's script part from running when another file imports it. Use it with a main() function, and know the cases where you don't need it.

if __name__ == "__main__": means "run this part only when the file is started directly, not when it's imported". You need it as soon as a file is used in two ways: as a script you run, and as a module another file imports from. If a file is only ever one of those, you can skip it.

Skip ahead: If you already know what __name__ is and just want the pattern, go to "The pattern with main()".

The problem it solves

Here's a small file with a useful function, plus some code to try it:

def add_vat(amount, rate=0.12):
    return round(amount * (1 + rate), 2)


print("Testing add_vat:", add_vat(100))

Running it directly is fine:

python prices.py
Testing add_vat: 112.0

Now another file wants to use the function:

from prices import add_vat

print("Invoice total:", add_vat(250))
Testing add_vat: 112.0
Invoice total: 280.0

The test line printed too. Importing a file runs it, top to bottom. That's how Python creates the function in the first place. Every print, every calculation, every input() at the top level of prices.py runs again, inside someone else's program. If that test code sent an email or deleted a file, it would do that too.

What __name__ is

Every Python file has a variable called __name__, set by Python before your code runs:

  • When you run the file directly, __name__ is "__main__".
  • When the file is imported, __name__ is the module's name, like "prices".
print("__name__ is", __name__)
import who
python who.py
python use_who.py
__name__ is __main__
__name__ is who

So if __name__ == "__main__": is just an if that asks: was I started directly?

The fix

def add_vat(amount, rate=0.12):
    return round(amount * (1 + rate), 2)


if __name__ == "__main__":
    print("Testing add_vat:", add_vat(100))
Invoice total: 280.0

Now python prices.py still prints the test line, and importing it doesn't. One file, two uses, no surprises.

The pattern with main()

For a real script, put the work in a function called main() and call it from the check:

import sys


def add_vat(amount, rate=0.12):
    return round(amount * (1 + rate), 2)


def main(args):
    if not args:
        print("Usage: python report.py AMOUNT [AMOUNT ...]")
        return 1
    for text in args:
        print(f"{text} -> {add_vat(float(text))}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
python report.py 100 250.5
100 -> 112.0
250.5 -> 280.56

Why a function, and not just code under the if?

  1. Variables stay local. Code directly under the if creates global variables, and functions above it can accidentally use them. Inside main(), they can't.
  2. You can test it. A test can call main(["100"]) and check the result, without starting a new process.
  3. The return value becomes the exit code. sys.exit(0) means success, anything else means failure. Other tools, like scheduled tasks and CI, read that.

💡 Tip: sys.argv[1:] is the list of words typed after the file name. Passing it into main() instead of reading sys.argv inside the function is what makes the function easy to test with any list you want.

When you don't need it

  • A file that is only ever imported, like a module full of functions. There's nothing to protect.
  • A one-off script nobody imports. It doesn't hurt to add, but it's not required.
  • Tests run by pytest. pytest imports your test files and calls the test functions itself.

You do need it in one case that surprises people: code that uses multiprocessing or ProcessPoolExecutor on Windows and macOS. Those start new Python processes that import your main file. Without the check, each new process starts the work again. Python stops this with a RuntimeError rather than letting it run away, but it's the same rule: top-level code runs on import.

Common mistakes

  • Spelling. It's two underscores on each side: __name__ and "__main__". One underscore is just a different variable.
  • **Putting function definitions inside the if.** Then importing the file gives you nothing to import.
  • Thinking it makes code private. It only controls what runs on start. Anything defined at the top level can still be imported.

What happens if you skip it

The day someone else, or you, imports your script to reuse one function, the script runs its whole job inside their program. If that job only prints, it's confusing. If it writes files or sends requests, it's a real problem.

Which of your scripts would do something you didn't ask for if another file imported it today?

About

What __name__ is, why importing a file runs its top-level code, and the main() pattern with sys.argv and exit codes. After this, one file can be both a script and an importable module.

Responsible
Christopher R
Last Update
09/18/2026
Reading Time
4 min
Was this helpful?
​ 0 ​ 0

Comments (0)

Sign in to comment

No comments yet.