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

poze 5 months ago315 gadeen

1

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

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 5 months ago

1 Repons

4
✓
✓ Repons yo aksepte

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.

Konekte pou di lòt moun si li te mache.

answered 5 months ago

Sign in and verify your email to post an answer.