Created
October 29, 2016 12:45
-
-
Save pyldin601/6373a202de2bc85b97bc65b124999018 to your computer and use it in GitHub Desktop.
Type strict in python 3.5
This file contains hidden or 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
import inspect | |
def use_strict(func): | |
signature = inspect.signature(func) | |
def validate_args(*args): | |
params = signature.parameters.values() | |
types = map(lambda p: p.annotation, params) | |
zipped = zip(list(*args), types) | |
for i, t in enumerate(zipped): | |
if t[1] is not None and not isinstance(t[0], t[1]): | |
raise TypeError("Unexpected type of parameter") | |
def validate_return(result): | |
if signature.return_annotation is not None \ | |
and not isinstance(result, signature.return_annotation): | |
raise TypeError("Unexpected type of return value") | |
def func_wrapper(*args, **kwargs): | |
validate_args(args) | |
r = func(*args, **kwargs) | |
validate_return(r) | |
return r | |
return func_wrapper | |
@use_strict | |
def my_sum(x: int, y: int) -> int: | |
return x + y | |
# Will run ok | |
print(my_sum(10, 15)) | |
# Will raise error | |
# print(my_sum("foo", "bar")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment