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