Skip to content

Instantly share code, notes, and snippets.

@bedekelly
Last active August 29, 2015 14:12
Show Gist options
  • Save bedekelly/6621a59df867a982acaa to your computer and use it in GitHub Desktop.
Save bedekelly/6621a59df867a982acaa to your computer and use it in GitHub Desktop.
Typechecking for Python
"""
Quick 'n dirty hack for a typecheck decorator.
Only tested on functions without kwargs. Use at own peril, etc.
Usage:
@typecheck
def some_function(x: str, y: int) -> str:
...
"""
from functools import wraps
from collections import namedtuple
Argument = namedtuple("Argument", "name type")
def typecheck(func):
@wraps(func)
def replacement(*args):
arg_names = func.__code__.co_varnames[:func.__code__.co_argcount]
requested_types = [Argument(name, func.__annotations__[name])
for name in arg_names]
for arg, requested_type in zip(args, requested_types):
if not isinstance(arg, requested_type.type):
raise TypeError("Argument {} is not type {}".format(
requested_type.name, requested_type.type))
retval = func(*args, **kwargs)
if not isinstance(retval, func.__annotations__['return']):
raise TypeError("Function must return type {}".format(
func.__annotations__['return']))
else:
return retval
return replacement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment