Table Of Contents
- The Module vs Script Identity Crisis
- The Magic Guard Clause
- Understanding the Magic
- Common Use Cases
- Pro Tips
- Expand Your Python Skills
The Module vs Script Identity Crisis
Ever written a Python file with useful functions, then added test code at the bottom - only to have it run every time someone imports your module? There's an elegant solution that every Python developer should know.
The Magic Guard Clause
# calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
def main():
# Code that runs when script is executed directly
print("Calculator Demo")
result1 = add(5, 3)
result2 = multiply(4, 7)
print(f"5 + 3 = {result1}")
print(f"4 × 7 = {result2}")
# This block only runs when script is executed directly
if __name__ == "__main__":
main()
# When imported: __name__ = "calculator"
# When run directly: __name__ = "__main__"
# Advanced usage with command line arguments
import sys
def process_file(filename):
with open(filename, 'r') as f:
return f.read()
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python script.py <filename>")
sys.exit(1)
filename = sys.argv[1]
content = process_file(filename)
print(f"Processed {len(content)} characters")
# Testing example
def complex_calculation(x, y):
return x ** 2 + y ** 2
if __name__ == "__main__":
# Run tests when executed directly
assert complex_calculation(3, 4) == 25
assert complex_calculation(0, 0) == 0
print("All tests passed!")
Understanding the Magic
When Python runs a file:
- Direct execution:
python calculator.py
→__name__ = "__main__"
- Import:
import calculator
→__name__ = "calculator"
This simple mechanism enables powerful patterns:
Common Use Cases
- Module testing: Add unit tests that run only when testing the module directly
- CLI tools: Create command-line interfaces for your libraries
- Demo code: Show how to use your module without affecting importers
- Development helpers: Include debugging or profiling code
Pro Tips
- Always use a
main()
function for organization - Handle command-line arguments properly
- Include helpful usage messages
- Consider using
argparse
for complex CLIs
Expand Your Python Skills
Master Python's import system, explore Python testing patterns, and learn about Python's module organization.
Share this article
Add Comment
No comments yet. Be the first to comment!