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

posée 5 months ago319 vuesen

1

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

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 5 months ago

1 réponse

4
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

answered 5 months ago

Sign in and verify your email to post an answer.