Created
October 31, 2013 00:39
-
-
Save minism/7242750 to your computer and use it in GitHub Desktop.
Python runtime type checking concept
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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