Skip to content

Instantly share code, notes, and snippets.

@minism
Created October 31, 2013 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minism/7242750 to your computer and use it in GitHub Desktop.
Save minism/7242750 to your computer and use it in GitHub Desktop.
Python runtime type checking concept
# Runtime type checking concept
from functools import wraps
def signature(*types):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for i, t in enumerate(types):
if i >= len(args):
raise TypeError("%s typed arguments expected (%s given)" % (len(types), len(args)))
if not isinstance(args[i], t):
raise TypeError("%s() arg %s expected to be %r (%r given)" % (func.__name__, i + 1, type(args[i]), t))
return func(*args, **kwargs)
return wrapper
return decorator
@signature(int, int)
def foo(a, b):
print a + b
foo(2, 3)
foo(2, '3')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment