Created
June 29, 2015 17:37
-
-
Save sharow/54ddcfef524ce5e5473e to your computer and use it in GitHub Desktop.
type annotation validator
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
#!/usr/bin/env python | |
# -*- Mode: python; tab-width: 4; indent-tabs-mode: nil; coding: utf-8; -*- | |
import inspect | |
from functools import wraps | |
class AnnotationValidateError(Exception): | |
pass | |
def validate(f): | |
@wraps(f) | |
def wrapper(*args, **kwarg): | |
sig = inspect.signature(f) | |
params = dict(zip(sig.parameters, args)) | |
for k, v in sig.parameters.items(): | |
if k in params: | |
if not v.annotation(params[k]): | |
e = 'annotation type {}={}, but given {}'.format(k, v.name, type(params[k])) | |
raise AnnotationValidateError(e) | |
ret = f(*args, **kwarg) | |
if sig.return_annotation is not sig.empty: | |
if type(ret) is not sig.return_annotation: | |
e = 'annotation return type={}, but returned={}'.format(sig.return_annotation, type(ret)) | |
raise AnnotationValidateError(e) | |
return ret | |
return wrapper |
Author
sharow
commented
Jun 29, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment