Skip to content

Instantly share code, notes, and snippets.

@johnpena
Last active August 29, 2015 14:05
Show Gist options
  • Save johnpena/415353c0ae6ee7fcbfb9 to your computer and use it in GitHub Desktop.
Save johnpena/415353c0ae6ee7fcbfb9 to your computer and use it in GitHub Desktop.
Crappy runtime typing for python
import functools
class ArgumentLengthMismatchException(Exception):
pass
class InvalidParameterTypeException(Exception):
pass
def typed(*type_args):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if len(args) != len(type_args):
raise ArgumentLengthMismatchException(
"The number of arguments passed to function {func_name} did not match the number of types defined for it.".format(
func_name=func.func_name
)
)
for i, (arg, arg_type) in enumerate(zip(args, type_args)):
if type(arg) != arg_type:
raise InvalidParameterTypeException(
"Argument {arg_number} passed to function {func_name} had type {actual_type}, but the type signature was {signature_type}".format(
arg_number=i,
func_name=func.func_name,
actual_type=type(arg),
signature_type=arg_type
)
)
return func(*args, **kwargs)
return wrapper
return decorator
@typed(int, int)
def add(a, b):
return a + b
# In [1]: add(1, 2)
# Out[1]: 3
#
# In [2]: add(1, 1, 1)
# ---------------------------------------------------------------------------
# ArgumentLengthMismatchException Traceback (most recent call last)
# <ipython-input-367789e5329c> in <module>()
# ----> 1 add(1, 1, 1)
#
# <ipython-input-21042874bf6a> in wrapper(*args, **kwargs)
# 16 raise ArgumentLengthMismatchException(
# 17 "The number of arguments passed to function {func_name} did not match the number of types defined for it.".format(
# ---> 18 func_name=func.func_name
# 19 )
# 20 )
#
# ArgumentLengthMismatchException: The number of arguments passed to function add did not match the number of types defined for it.
#
# In [3]: add(1, '2')
# ---------------------------------------------------------------------------
# InvalidParameterTypeException Traceback (most recent call last)
# <ipython-input-bc3442d797f0> in <module>()
# ----> 1 add(1, '2')
#
# <ipython-input-21042874bf6a> in wrapper(*args, **kwargs)
# 27 func_name=func.func_name,
# 28 actual_type=type(arg),
# ---> 29 signature_type=arg_type
# 30 )
# 31 )
#
# InvalidParameterTypeException: Argument 1 passed to function add had type <type 'str'>, but the type signature was <type 'int'>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment