You should use if __name__ == "__main__": whenever you want a file to behave as both a reusable module and a runnable script.
Here are the three specific situations when you should use it:
1. To Prevent Code from Running During an Import
When you import a file, Python executes every line of code in that file. If you have "action" code (like print() or a function call) at the bottom of your module, it will run as soon as someone imports it.
The Problem:
# calculator.py
def add(a, b):
return a + b
print(add(5, 5)) # I want to test this, but...
If you import calculator in another file, it will immediately print 10, which is usually unwanted behavior for a library.
The Solution:
# calculator.py
def add(a, b):
return a + b
if __name__ == "__main__":
print(add(5, 5)) # Now this ONLY runs if you run 'python calculator.py'
2. For Testing and Debugging
It is a great place to put "Quick Tests" for the functions inside your module. You can write your logic at the top and then write a few test cases at the bottom inside the if block.
- When you are developing the module, you run the file directly to see if it works.
- Once it works, you import it into your main project, and the tests stay hidden.
3. To Define a Clear "Entry Point"
In larger programs, it’s best practice to have a main() function that starts everything. This keeps your global scope clean.
def main():
print("Starting the application...")
# Your logic here
if __name__ == "__main__":
main()
How it Works (The Magic)
Python automatically sets a special hidden variable called __name__ for every file:
-
If you run the file directly (e.g.,
python file.py):
Python sets__name__ = "__main__".
Result: The code inside theifblock runs. -
If you import the file (e.g.,
import file):
Python sets__name__ = "file"(the name of the file).
Result: The code inside theifblock is skipped.
Summary Recommendation:
- Do use it in files where you have logic/experiments at the bottom.
- Do use it in the "Main" entry file of your project.
- Don't need it in files that only contain function or class definitions and have no code that actually "does" anything outside of those functions.