Question
What `if __name__ == "__main__":` Does in Python
Question
In Python, what does this code do, and why would you include this if statement?
if __name__ == "__main__":
print("Hello, World!")
More broadly, how does this pattern affect whether code runs when a file is executed directly versus imported as a module?
Short Answer
By the end of this page, you will understand what __name__ is in Python, why if __name__ == "__main__": is a common pattern, and how it prevents certain code from running when a file is imported. You will also see how this idiom is used in real projects for testing, command-line scripts, and keeping modules reusable.
Concept
In Python, every file is a module, and each module has a special built-in variable called __name__.
Its value depends on how the file is being used:
- If the file is run directly with Python,
__name__is set to"__main__". - If the file is imported from another file,
__name__is set to the module's name, such as"math_tools".
That means this pattern:
if __name__ == "__main__":
print("Hello, World!")
says:
- Run this code only if this file is the main program being executed.
- Do not run it if this file is being imported into another program.
This matters because Python executes top-level code in a file when that file is imported. Without this check, any print statements, test code, setup logic, or script-only behavior would run during import, which is often not what you want.
A common use is to separate:
- reusable functions and classes
- from script startup code
This makes your file useful both as:
- a standalone script
- an importable module
Mental Model
Think of a Python file as a tool box with an optional demo mode.
- The functions and classes are the tools inside the box.
- The
if __name__ == "__main__":block is the part that says, "Only run the demo if someone opens this box directly." - If another file imports the box just to use the tools, the demo does not start.
So the check acts like a gate:
- direct run → open the gate
- import → keep the gate closed
Syntax and Examples
The basic syntax is:
if __name__ == "__main__":
# code to run only when this file is executed directly
Example 1: Direct execution vs import
# greetings.py
def say_hello(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print(say_hello("World"))
If you run this file directly:
python greetings.py
Output:
Hello, World!
But if another file imports it:
# app.py
import greetings
print(greetings.say_hello("Alice"))
Output:
Hello, Alice!
Notice that Hello, World! does print during the import. That is because the guarded block does not run.
Step by Step Execution
Consider this file:
# demo.py
print("File is being loaded")
def add(a, b):
return a + b
if __name__ == "__main__":
print("Running as main program")
print(add(2, 3))
Case 1: Run directly
Command:
python demo.py
What happens step by step:
- Python starts executing
demo.py. __name__is set to"__main__".print("File is being loaded")runs.- The function
addis defined. - Python checks
if __name__ == "__main__":. - The condition is
True. print("Running as main program")runs.add(2, 3)returns .
Real World Use Cases
Here are common situations where this pattern is useful:
Command-line scripts
A file may contain reusable functions but also support running from the terminal.
def convert_temperature(celsius):
return celsius * 9 / 5 + 32
if __name__ == "__main__":
print(convert_temperature(25))
Quick manual testing
Developers often add a small test block to try functions while building them.
def is_even(n):
return n % 2 == 0
if __name__ == "__main__":
print(is_even(4))
print(is_even(7))
Keeping helper modules clean
A utility file can expose functions without running extra code on import.
Training and demos
A module can be imported in lessons or notebooks, while still providing a runnable example when executed directly.
API and application entry points
Small Python apps may define reusable logic in functions and place startup code in the block.
Real Codebase Usage
In real codebases, developers often use this idiom to separate definition time from run time.
Common pattern: define functions, then call main()
def load_config():
return {"debug": True}
def main():
config = load_config()
print("App started", config)
if __name__ == "__main__":
main()
This helps with:
- reusability: other files can import
load_config()ormain() - testability: tests can import functions without triggering app startup
- clean imports: importing a module should not unexpectedly print, connect to services, or start work
Typical uses in projects
- Running a script from the command line
- Holding example usage for a module
- Keeping debugging prints out of imports
- Starting a batch job only when explicitly executed
- Avoiding accidental side effects during testing
Related pattern: guard side effects
Top-level code with side effects can cause problems:
()
Common Mistakes
Mistake 1: Thinking Python automatically runs a function called main
Python does not automatically call a function just because it is named main.
Broken expectation:
def main():
print("Hello")
Nothing runs unless you call it:
def main():
print("Hello")
if __name__ == "__main__":
main()
Mistake 2: Putting important code at the top level
Broken example:
print("Starting app")
If this file is imported, that line still runs. If that is not intended, move it into a guarded block.
Mistake 3: Misspelling __name__ or __main__
Broken code:
if _name_ == "_main_":
()
Comparisons
| Concept | What it does | When it runs | Best use |
|---|---|---|---|
| Top-level code | Executes immediately when the module is loaded | On direct run and on import | Definitions and truly necessary setup |
if __name__ == "__main__": block | Executes only for the main script | Only on direct run | Script-only behavior |
main() function | Groups startup logic into a function | Only when explicitly called | Clean organization |
main() vs if __name__ == "__main__":
These are related but different:
main()is just a normal function name by convention.if __name__ == "__main__":is the actual check that decides whether code should run.
Cheat Sheet
if __name__ == "__main__":
main()
Rules
__name__is a special Python variable.- When a file is run directly,
__name__ == "__main__". - When a file is imported,
__name__is the module name. - Code inside the block runs only for direct execution.
Best practice
def main():
# startup code here
pass
if __name__ == "__main__":
main()
Use it for
- command-line script entry points
- test or demo code
- avoiding unwanted behavior on import
Avoid
- misspelling
__name__or__main__ - putting too many statements directly in the block
- assuming
main()runs automatically
Remember
- imports execute top-level code
- guarded code does not run during import
FAQ
Why is __name__ equal to "__main__"?
Python sets __name__ to "__main__" for the file that starts execution. This lets that file know it is the main entry point.
Does Python require if __name__ == "__main__":?
No. Your program can work without it. It is used when you want code to run only on direct execution and not on import.
Does Python automatically call a main() function?
No. main() is just a normal function name. You must call it yourself, usually inside the if __name__ == "__main__": block.
What happens if I import a file without this check?
All top-level statements in that file run during import. That may cause unexpected output or side effects.
Should every Python file use this pattern?
Not necessarily. Use it when a file can be run as a script or when you need to protect script-only code from running on import.
Can I still define functions and classes outside the block?
Yes. That is the normal approach. Define reusable code at the top level and put execution logic in the guarded block.
Is this only for printing text?
No. It can protect any script-only behavior, such as parsing arguments, reading files, or starting an application.
What is the difference between a script and a module in Python?
Mini Project
Description
Build a small Python utility module that can be used in two ways: imported by another file or run directly from the terminal. This demonstrates exactly why if __name__ == "__main__": is useful.
Goal
Create a reusable Python file that exposes a function and also runs a short demo only when executed directly.
Requirements
- Create a function that returns the square of a number.
- Print a demo result only when the file is run directly.
- Import the function from another file and use it without triggering the demo output.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.