Created
April 2, 2018 21:08
-
-
Save JadenGeller/cfb36316c95f189de02ea4f300209c4a to your computer and use it in GitHub Desktop.
Dynamic Type Checking
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
#!/usr/bin/python | |
import inspect | |
def typeAsserting(f): | |
signature = inspect.signature(f) | |
def wrapper(*args, **kwargs): | |
bound_args = signature.bind(*args, **kwargs) | |
for name, parameter_value in bound_args.arguments.items(): | |
expected_type = signature.parameters[name].annotation | |
if not isinstance(parameter_value, expected_type): | |
actual_type = type(parameter_value) | |
raise TypeError("Paramter '{name}={parameter_value}' has type {actual_type} instead of expected type {expected_type}.".format(**locals())) | |
return_value = f(*bound_args.args, **bound_args.kwargs) | |
expected_type = signature.return_annotation | |
if not isinstance(return_value, signature.return_annotation): | |
actual_type = type(return_value) | |
raise TypeError("Return value '{return_value}' has type {actual_type} instead of expected type {expected_type}.".format(**locals())) | |
return return_value | |
return wrapper | |
def typeConverting(f): | |
signature = inspect.signature(f) | |
def wrapper(*args, **kwargs): | |
bound_args = signature.bind(*args, **kwargs) | |
for name, val in bound_args.arguments.items(): | |
bound_args.arguments[name] = signature.parameters[name].annotation(val) | |
return signature.return_annotation(f(*bound_args.args, **bound_args.kwargs)) | |
return wrapper | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment