Understanding Python’s __name__ == '__main__': The Gateway to Script and Module 🧩📜
Introduction
If you’ve looked at Python scripts, you might have come across this line:
But what does it really mean? This blog demystifies this construct and explains its importance in distinguishing between script and module usage in Python.
The Role of __name__
In Python, every module has a built-in attribute called __name__
. When a module is run directly, __name__
is set to "__main__"
. However, if the module is imported, __name__
is set to the module’s name.
Why Use if __name__ == '__main__':
?
This construct allows you to:
Run Code Only When a Script is Executed Directly:
- Prevent Code from Running on Import: This is particularly useful if your script contains test code or standalone execution logic that shouldn’t run when the module is imported elsewhere.
Practical Example
Let’s say you have a script called calculator.py
with a main()
function that performs calculations. By wrapping the call to main()
in an if __name__ == "__main__":
block, the script will only perform calculations when run directly, not when imported as a module.