PythonMastery

Guard script code with if __name__ == "__main__"

Code at the top level of a file runs on every import. Put the script part under if __name__ == "__main__" and the same file works as a script and a module.

Any code at the top level of a file runs the moment the file is imported, not just when you run it. That's how a helper module ends up printing reports or deleting files when someone only wanted one of its functions. The guard keeps the "run me" part for when the file really is the program.

Before

Picture a file, prices.py, that someone else imports for its function:

python
def with_vat(net, rate=0.20):
    return round(net * (1 + rate), 2)

# quick manual test, left at the top level
print("testing:", with_vat(100))
output
testing: 120.0

Every import prices now prints testing: 120.0 in somebody else's program.

After

python
def with_vat(net, rate=0.20):
    return round(net * (1 + rate), 2)

def main():
    for net in (100, 49.99, 12.5):
        print(net, "->", with_vat(net))

if __name__ == "__main__":
    main()
output
100 -> 120.0
49.99 -> 59.99
12.5 -> 15.0

Run the file and main() runs. Import it and you get with_vat, with no side effects.

Why it works

Python sets __name__ on every module. When a file is imported, __name__ is its module name, "prices". When it's the file you ran, __name__ is "__main__". You can see the value directly:

python
print(__name__)
output
__main__

Putting the script code in a main() function also keeps its variables local, so they can't leak into, or clash with, the rest of the module.

When not to use it

Notebook cells, the code boxes on this site and one-off scripts nobody will import don't need it. It earns its place the moment a file is both something you run and something another file imports. See Modules for how imports find and run files.

Learn it properly: Modules & Imports