Skip to content

Instantly share code, notes, and snippets.

@costa86
Created January 26, 2022 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save costa86/472ff1211e083041f385dd220dc142e1 to your computer and use it in GitHub Desktop.
Save costa86/472ff1211e083041f385dd220dc142e1 to your computer and use it in GitHub Desktop.
Python decorator to validate argument types (args and kwargs)
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