Main Guard (if __name__ == "__main__")

phrase

say it: “MAYN GARD” /ˈmeɪn ˈɡɑrd/ or “IF DUN-der NAYM DUB-ul EE-kwulz DUN-der MAYN” /ˈɪf ˈdʌndər ˈneɪm ˈdʌbəl ˈikwəlz ˈdʌndər ˈmeɪn/

The line if __name__ == "__main__": at the bottom of a Python file, which runs the code under it only when the file is run directly, not when another file imports it.

What does if __name__ == "__main__": do?

This line runs the code under it only when you run the file directly, not when another file imports it. It keeps a module's "try it out" code from running on import.

def greet(name):
    return f"Hi, {name}"

if __name__ == "__main__":
    print(greet("tester"))   # only when you run this file itself

In a sentence

  • “Mia put her test calls under a main guard, so importing her pricing module no longer printed sample totals.”
  • “Without a main guard, the demo menu in bakery.py ran every time another file imported it.”

Level: Journeyman · More Python terms at this level

Updated