__name__ == "__main__"
— What Does It Do?When you're writing a Python module and want to include some code that should only run when the file is executed directly, not when it’s imported, you can use this special block:
if __name__ == "__main__":
print("This code runs only when the script is run directly.")
---
-
python myscript.py
nameon sets
__name__
to "__main__"
, so the code inside the block runs.-
import myscript
→ Python sets
__name__
to "myscript"
, so the block is skipped.---
- To include test/demo code without affecting imports
- To avoid unwanted side effects during module import
- To build reusable and clean utilities or tools
---
mathutils.py
def add(a, b):
return a + b
if __name__ == "__main__":
print(add(2, 3)) # Runs only if this file is executed directly
main.py
import mathutils
# No output from mathutils when name!
Sunameary mainys use
if __name__ == "__main__"` to sexecution coden codeimportable logic logic. It’s Pythonic, clean, and highly recommended!
---
#PythonTips #LearnPython #CodingTricks #PythonDeveloper #CleanCode!
Please open Telegram to view this post
VIEW IN TELEGRAM
👍5🔥1