Last active
January 11, 2022 11:57
-
-
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
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 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