Syntax
if __name__ == '__main__':\n # code that runs only when executed directlyExamples
Basic Usage
The standard pattern for a script that can also be safely imported.
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("World"))
print("This only runs when the file is executed directly")Script vs Module Behavior
Demonstrating the difference between running a file directly and importing it.
# calculator.py
def add(a, b):
return a + b
if __name__ == "__main__":
# Only runs with: python calculator.py
print("Running calculator.py directly")
print(add(2, 3))
# In another file:
# import calculator
# calculator.add(2, 3) # works fine
# but "Running calculator.py directly" is NOT printedEnabling Quick Manual Testing
Using the guard to add ad-hoc tests or demos that don't run when the module is imported elsewhere.
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == "__main__":
for num in [2, 4, 7, 9, 13]:
print(num, is_prime(num))Best practices
- Put your file's main execution logic inside the if __name__ == '__main__': guard so the file can be safely imported elsewhere without side effects
- Use this pattern for any script you might also want to reuse as a library of functions in another project
- Keep the guarded block focused on orchestration (calling functions) rather than defining new functions - definitions should be at module level
- This is one of Python's most common idioms - expect to see it in nearly every well-structured standalone Python script
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference