Typing stubs for the decorator library
types-decorator provides high-quality static type annotations (stubs) for the popular `decorator` Python library. It enables type checkers like MyPy and Pyright to analyze code using `decorator` for type correctness, enhancing maintainability and catching potential errors early. Maintained by the `typeshed` project, these stubs are automatically released to PyPI regularly, often daily, to reflect updates in the upstream library. The current version is 5.2.0.20260408.
Warnings
- breaking Typeshed stub packages, including `types-decorator`, can sometimes introduce changes that might cause your code to fail type checking, even if the runtime `decorator` library itself hasn't changed. This is due to updates in the stub definitions for improved accuracy or to align with new Python typing features.
- gotcha When creating custom decorators manually (without using `decorator.decorator`), a common pitfall is that the decorated function loses its original metadata (like `__name__`, `__doc__`, `__module__`) and signature. This can hinder debugging, introspection, and tools that rely on function signatures.
- gotcha When applying multiple decorators to a single function, their order of application matters. Decorators are applied in reverse order of their appearance in the code, meaning the decorator closest to the function definition is applied first, and the topmost decorator is applied last.
Install
-
pip install types-decorator -
pip install decorator types-decorator
Imports
- decorator
from decorator import decorator
Quickstart
import time
import logging
from decorator import decorator
logging.basicConfig(level=logging.INFO)
@decorator
def warn_slow(func, timelimit=60, *args, **kw):
"""A decorator factory that logs if a function call exceeds a timelimit."""
t0 = time.time()
result = func(*args, **kw)
dt = time.time() - t0
if dt > timelimit:
logging.warning('%s took %.2f seconds (exceeded %d s)', func.__name__, dt, timelimit)
else:
logging.info('%s took %.2f seconds', func.__name__, dt)
return result
@warn_slow
def process_data(duration: float):
"""Simulates a data processing operation."""
time.sleep(duration)
return f"Processed data in {duration} seconds"
@warn_slow(timelimit=1) # Override default timelimit
def analyze_report(duration: float):
"""Simulates a report analysis with a custom timelimit."""
time.sleep(duration)
return f"Analyzed report in {duration} seconds (custom timelimit)"
# Example usage:
print(process_data(0.5))
print(process_data(2.0))
print(analyze_report(0.8))
print(analyze_report(1.5))