The __name__ == "__main__" Pattern
Overview
This special line of code helps control whether a file runs as the main program or as an imported module. You'll understand how it prevents unintended execution and allows your code to behave differently depending on how it's used, making your modules more flexible and professional.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- What __name__ is: Understand Python's special
__name__variable. - The pattern: Learn how
if __name__ == "__main__":works. - Why it matters: Understand when and why to use this pattern.
- Practical use: See how it prevents code from running when imported.
Why This Matters
When you create a module with functions, you might also want to include test code or example usage. But you don't want that test code to run when someone imports your module! The __name__ == "__main__" pattern lets you write code that only runs when the file is executed directly, not when it's imported. This is a professional Python practice!
Step 1: Understanding __name__
Python automatically sets a special variable called __name__ for every file:
# When you run a file directly:
# __name__ = "__main__"
# When you import a file as a module:
# __name__ = "module_name" (the filename)
Running Directly
When you run a Python file directly (like python myfile.py), Python sets __name__ to "__main__".
Importing as Module
When you import a file as a module (like import myfile), Python sets __name__ to the module's name (the filename without .py).
Check the Value
You can check __name__ to determine how the file is being used and run code conditionally!
Key Concept: The __name__ variable tells you how Python is using your file. If it's "__main__", the file is being run directly. Otherwise, it's being imported as a module!
Mini Practice #1: Checking __name__
Try It YourselfSee what __name__ is set to:
What happened? When you run this code directly, __name__ is set to "__main__", so the condition is true and it prints "This file is being run directly!". If this file were imported as a module, __name__ would be the module name instead!
Step 2: The __name__ == "__main__" Pattern
The pattern uses an if statement to check if the file is being run directly:
# File: calculator.py
def add(a, b):
"""Add two numbers."""
return a + b
def multiply(a, b):
"""Multiply two numbers."""
return a * b
# This code only runs when file is executed directly
if __name__ == "__main__":
print("Running calculator tests...")
print(f"5 + 3 = {add(5, 3)}")
print(f"5 * 3 = {multiply(5, 3)}")
Define Functions
Define your functions normally. These are always available when the module is imported.
Add the Pattern
Put test code or example usage inside if __name__ == "__main__": block.
Conditional Execution
Code in the block only runs when the file is executed directly, not when imported!
What Happens When Imported?
If someone writes import calculator, Python will:
- Load the functions (
addandmultiply) - Skip the code inside
if __name__ == "__main__":because__name__is"calculator", not"__main__"
This prevents test code from running when the module is imported!
Step 3: Why Use This Pattern?
This pattern solves a common problem:
# File: utils.py
def greet(name):
return f"Hello, {name}!"
# This runs even when imported!
print("Testing greet function...")
print(greet("Alice"))
# File: utils.py
def greet(name):
return f"Hello, {name}!"
# This only runs when executed directly
if __name__ == "__main__":
print("Testing greet function...")
print(greet("Alice"))
Remember: Without the pattern, test code runs every time someone imports your module. This can be annoying and slow down programs. With the pattern, test code only runs when you explicitly run the file yourself!
Mini Practice #2: Using the Pattern
Try It YourselfCreate a module with the pattern:
What happened? When you run this code directly, the test code inside if __name__ == "__main__": executes. If this file were imported as a module (like import mymodule), only the functions would be available, and the test code wouldn't run!
Step 4: Common Use Cases
Use this pattern for:
Test Code
Put test code in the block so it doesn't run when imported.
Example Usage
Show how to use your functions without running examples when imported.
Main Program Logic
If a file can be both a module and a standalone program, put the main logic in the block.
CLI Scripts
Command-line scripts that can also be imported use this pattern.
End-of-Lesson Exercises
Exercise 1: Use the Pattern
Create a function double(n) that returns n * 2. Then use the if __name__ == "__main__": pattern to test it with the value 7. Print the result.
Define the function, then add if __name__ == "__main__": with test code.
Exercise 2: Check __name__
Print the value of __name__, then use an if statement to print "Running directly" if __name__ == "__main__", otherwise print "Imported as module".
Print __name__, then use if __name__ == "__main__":