timeout() Decorator – A Real-World Example in Python 2026

Writing Functions Mar 16, 2026

timeout() Decorator – A Real-World Example in Python 2026

The timeout() decorator is one of the most practical real-world decorators. It prevents functions from running longer than a specified time, which is essential for API calls, database queries, external service calls, and any operation that might hang.

TL;DR — Real-World timeout() Decorator

  • Uses signal module to enforce a time limit
  • Raises TimeoutError if the function exceeds the limit
  • Works cleanly with the @timeout(seconds) syntax
  • Properly cleans up the alarm even if an exception occurs

1. Production-Ready timeout() Decorator


import signal
import time
from functools import wraps
from typing import Callable, Any

def timeout(seconds: float = 5.0):
    """Decorator that raises TimeoutError if the function runs too long."""
    
    def decorator(func: Callable) -> Callable:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            def timeout_handler(signum, frame):
                raise TimeoutError(f"Function '{func.__name__}' timed out after {seconds} seconds")
            
            # Set the alarm
            signal.signal(signal.SIGALRM, timeout_handler)
            signal.alarm(int(seconds))
            
            try:
                return func(*args, **kwargs)
            finally:
                # Always disable the alarm
                signal.alarm(0)
        
        return wrapper
    
    return decorator

2. Real-World Usage Examples


@timeout(3.0)
def call_external_api(url: str):
    """Simulate calling a slow or unreliable external service."""
    import time
    time.sleep(4)           # This will trigger timeout
    return {"status": "success"}

@timeout(10.0)
def process_large_file(filename: str):
    """Process a file with a generous timeout."""
    # ... heavy processing ...
    return "Processed"

# Usage
try:
    result = call_external_api("https://slow-api.example.com")
except TimeoutError as e:
    print(e)                    # Function 'call_external_api' timed out after 3 seconds

3. Best Practices for timeout() in 2026

  • Use reasonable timeouts based on the operation type (2–5s for APIs, 10–30s for heavy processing)
  • Always catch TimeoutError and handle it gracefully
  • Combine with retry decorators for resilient systems
  • Use different timeout values for different environments (dev vs production)
  • Consider async timeout alternatives (asyncio.wait_for) for async code

Conclusion

The timeout() decorator is a perfect real-world example of a decorator factory. It demonstrates how to add critical safety behavior (preventing hangs) without polluting your business logic. In 2026, using @timeout() on any external call or potentially long-running operation is considered a standard best practice for building reliable Python applications.

Next steps:

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices