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
signalmodule to enforce a time limit - Raises
TimeoutErrorif 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
TimeoutErrorand 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:
- Add
@timeout(5.0)to all your external API calls and database queries - Related articles: Decorators That Take Arguments in Python 2026 • Decorators in Python 2026 • Writing Functions in Python 2026