Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.