Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created April 2, 2018 21:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/cfb36316c95f189de02ea4f300209c4a to your computer and use it in GitHub Desktop.
Save JadenGeller/cfb36316c95f189de02ea4f300209c4a to your computer and use it in GitHub Desktop.
Dynamic Type Checking
#!/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