Created
March 1, 2024 21:20
-
-
Save NucciTheBoss/7967d3aa3063d8641ef4fe97a141fa90 to your computer and use it in GitHub Desktop.
Type checking decorator - a simple Python decorator for validating the type of passed arguments for functions and methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Works with builtin types and classes. Does not support type checking with annotations. | |
# If you are using types composed with the `typing` module, a more advanced validator should be used | |
def assert_type(*typed_args, **typed_kwargs): | |
"""Check the type of args and kwargs passed to a function/method.""" | |
def decorator(func: Callable): | |
sig = inspect.signature(func) | |
bound_types = sig.bind_partial(*typed_args, **typed_kwargs).arguments | |
@functools.wraps(func) | |
def wrapper(*args, **kwargs): | |
bound_values = sig.bind(*args, **kwargs).arguments | |
for name in bound_types.keys() & bound_values.keys(): | |
if not isinstance(bound_values[name], bound_types[name]): | |
raise TypeError(f"{bound_values[name]} is not {bound_types[name]}.") | |
return func(*args, **kwargs) | |
return wrapper | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment