Created
January 26, 2022 13:46
-
-
Save costa86/472ff1211e083041f385dd220dc142e1 to your computer and use it in GitHub Desktop.
Python decorator to validate argument types (args and kwargs)
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
def check_args_and_kwargs_types(func): | |
def inner(*args, **kwargs): | |
hints = typing.get_type_hints(func) | |
#args | |
keys = func.__code__.co_varnames | |
args_dict = {} | |
for k, v in zip(keys, args): | |
args_dict[k] = v | |
for i in args_dict: | |
if not isinstance(args_dict[i], hints[i]): | |
raise TypeError( | |
f"Arg '{i}' ({args_dict[i]}) must be a {hints[i].__name__}, got {type(args_dict[i]).__name__}" | |
) | |
#kwargs | |
for i in kwargs: | |
if not isinstance(kwargs[i], hints[i]): | |
raise TypeError( | |
f"Kwarg '{i}' ({kwargs[i]}) must be {hints[i].__name__}, got {type(kwargs[i]).__name__}" | |
) | |
func(*args, **kwargs) | |
return inner |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment