Navigation

Python

How to Use Python's __name__ == "__main__"

Unlock the secret to writing Python files that play dual roles - importable modules by day, executable scripts by night.

Table Of Contents

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

  1. Module testing: Add unit tests that run only when testing the module directly
  2. CLI tools: Create command-line interfaces for your libraries
  3. Demo code: Show how to use your module without affecting importers
  4. 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!

More from Python