Skip to content

Instantly share code, notes, and snippets.

@sharow
Created June 29, 2015 17:37
Show Gist options
  • Save sharow/54ddcfef524ce5e5473e to your computer and use it in GitHub Desktop.
Save sharow/54ddcfef524ce5e5473e to your computer and use it in GitHub Desktop.
type annotation validator
#!/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
@sharow
Copy link
Author

sharow commented Jun 29, 2015

def foo(x: int) -> str:
    return str(x)
print(foo(100))  # ok
print(foo('bar'))  # AnnotationValidateError

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment