Scripts and __name__

A .py file as a program, and the if __name__ == "__main__" guard.

A script is a .py file you run. A module is a .py file you import. The same file can be both. The guard if __name__ == "__main__" runs only when the file is the program, not when it is imported.

Goal

Put work in main(), and only call main() under the __name__ guard.

A function, then a script

TAX = 0.16

def line_total(units, price):
    return round(units * price * (1 + TAX), 2)

print(line_total(2, 10.5))

That print runs every time the file is imported. That is messy once other code wants line_total without printing.

The guard

TAX = 0.16

def line_total(units, price):
    return round(units * price * (1 + TAX), 2)

def main():
    print("Nairobi kiosk")
    print(line_total(2, 10.5))

if __name__ == "__main__":
    main()

In this editor the whole buffer is the program, so __name__ is "__main__" and main() runs. When you later import this file as kiosk, main() will not run.

What __name__ is

print("__name__ is", __name__)

You should see __main__.

Tip

Keep side effects (prints, file writes, argparse) inside main(). Keep helpers pure so tests can call them.