Part 07 / Topic 5 of 9
if __name__ == "__main__":
Every module has a built-in variable __name__.
- When you run a file directly, its
__name__is"__main__". - When the file is imported, its
__name__is the module name, e.g."shop_utils".
So code under if __name__ == "__main__": runs only when you run the file, not when someone imports it. Use it for demos and self-tests. It is like a shop's "staff only" door: staff (you, running the file) go through, customers (other files importing it) do not.
Real-world example: a module that tests itself, but stays quiet when imported.
def add_gst(price):
return round(price * 1.18, 2)
if __name__ == "__main__":
print("Self-test:", add_gst(100)) # Self-test: 118.0
| How the file is used | Value of __name__ |
Block runs? |
|---|---|---|
python shop_utils.py |
"__main__" |
✅ Yes |
import shop_utils |
"shop_utils" |
❌ No |
From now on, every example and solution puts its demo code under this check, usually by calling a main() function.
🔍 Going deeper:
python -m shop_utilsalso runs a module as"__main__", but finds it by module name throughsys.pathinstead of by file path. That is howpython -m venvandpython -m pip(below) work.
Done here? The practice set for Part 7 — 7 exercises with solutions — is on the part page.