Python: what does `if __name__ == "__main__":` do?

asked 5 months ago320 viewsen

1

I see this at the bottom of many scripts. What happens if I remove it?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 5 months ago

1 Answer

4
✓
✓ Accepted answer

Every module has a __name__ variable. When you run a file directly (python script.py), __name__ is "__main__". When another file imports it, __name__ is the module's name ("script").

So the block means: "run this only when the file is executed directly, not when it's imported."

def add(a, b):
    return a + b

if __name__ == "__main__":
    print(add(2, 3))  # runs with `python math_utils.py`, not on `import math_utils`

Without it, importing your module (from tests, say) would also run the script's side effects.

Sign in to tell others whether this worked.

answered 5 months ago

Sign in and verify your email to post an answer.