Python: what does `if __name__ == "__main__":` do?
posée 5 months ago319 vuesen
1
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
Marie Louis 2.2k
Sign in and verify your email to post an answer.