Created
February 14, 2014 09:30
-
-
Save agronholm/8998264 to your computer and use it in GitHub Desktop.
Type checking decorator for Python 3 annotations
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
from functools import wraps | |
import inspect | |
def typechecked(func): | |
argspec = inspect.getfullargspec(func) | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
for i, (arg, argname) in enumerate(zip(args, argspec.args)): | |
type_ = argspec.annotations.get(argname) | |
if type_ and not isinstance(args[i], type_): | |
raise TypeError('Expected {!r} for argument "{}", got {!r} instead'.format(type_, argname, type(arg))) | |
for argname, arg in kwargs.items(): | |
type_ = argspec.annotations.get(argname) | |
if type_ and not isinstance(arg, type_): | |
raise TypeError('Expected {!r} for argument "{}", got {!r} instead'.format(type_, argname, type(arg))) | |
return func(*args, **kwargs) | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment