python笔记:类型检验

2019-11-22 14:32:13 浏览数 (1)

在python3中,可以使用函数注解,类似这样:

代码语言:javascript复制
def print(input :str) -> int:
    pass

函数注解可以用内置方法获取,所以可以利用这个特性做一个类型检验的装饰器。 代码如下:

代码语言:javascript复制
import functools
import inspect

def typeassert(fn):
    """
    provide type assert, examples:

    #normal
    @typeassert
    def hello(name: str):
        return name   "world"

    #check return
    @typeassert
    def hello2(name: str, count: int=5) -> (int, int, int):
        print("{} {} say hello".format(count, name))
        return 0, 1, 2

    :param fn:input funcs
    :return:
    """
    @functools.wraps(fn)
    def wrap(*args, **kwargs):
        sig = inspect.signature(fn)
        parameters = sig.bind_partial(*args, **kwargs).arguments.items()
        anno = fn.__annotations__
        for element_name, value in parameters:
            if element_name in anno:
                if not isinstance(value, anno[element_name]):
                    raise TypeError(
                        "{}:{} type not {}".format(element_name, value, anno[element_name])
                        )

        ret = fn(*args, **kwargs)
        if 'return' not in anno:
            return ret

        anno_return = anno['return']
        if isinstance(anno_return, type):
            if not isinstance(ret, anno_return):
                raise TypeError("return value {} != {}".format(ret, anno_return))
        elif isinstance(anno_return, (list, tuple)):
            if len(ret) != len(anno_return):
                raise TypeError("return value count {} != {}".format(len(ret), len(anno_return)))
            for key, ret_value in enumerate(ret):
                if not isinstance(ret_value, anno_return[key]):
                    raise TypeError(
                        "return value index:{}({}) type not {}".format(key, ret_value, anno_return[key])
                        )
        return ret
    return wrap

0 人点赞