How would you write a decorator that validates a function's arguments against its type hints at RUNTIME, since Python doesn't enforce type hints by default?
Short answer
Inspect the function's __annotations__ dict inside the wrapper, and for each parameter with a type hint, check the actual passed argument's type using isinstance() (typically via inspect.signature() to correctly map positional/keyword args to their parameter names), raising a…
Advertisement
AModel answer
Inspect the function's __annotations__ dict inside the wrapper, and for each parameter with a type hint, check the actual passed argument's type using isinstance() (typically via inspect.signature() to correctly map positional/keyword args to their parameter names), raising a TypeError on mismatch.
import inspect, functools
def enforce_types(func):
sig = inspect.signature(func)
@functools.wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
for name, value in bound.arguments.items():
expected = func.__annotations__.get(name)
if expected and not isinstance(value, expected):
raise TypeError(f"{name} must be {expected}, got {type(value)}")
return func(*args, **kwargs)
return wrapper
@enforce_types
def add(a: int, b: int) -> int:
return a + bReal-world example
Adding runtime type safety to a critical internal function's inputs in a codebase without adopting a full static type-checking pipeline.
Likely follow-ups
- Why might this manual approach be preferred over (or a stepping stone toward) a dedicated library like pydantic for this purpose?
Related topics