Skip to content

Instantly share code, notes, and snippets.

@MathiasYde
Last active January 11, 2022 11:57
Show Gist options
  • Save MathiasYde/a5363282cbe2cb5b0c3e6de8479e959b to your computer and use it in GitHub Desktop.
Save MathiasYde/a5363282cbe2cb5b0c3e6de8479e959b to your computer and use it in GitHub Desktop.
Assert or omit function call if paramaters are not met with certain type requirements
def of_types(*types, omit_error=False):
def decorator(function):
def wrapper(*args, **kwargs):
for arg, t in zip(args, types):
if not isinstance(arg, t):
if omit_error:
return
raise TypeError(f"Invalid arguement type {t}({arg}) in {function.__name__}{args}")
return function(*args, **kwargs)
return wrapper
return decorator
@of_types(str, int, omit_error=False)
def foo(x, y):
print(f"passed {x, y}")
foo("hello", 123)
foo("hello", "123")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment