strict_types.py 文件源码

python
阅读 27 收藏 0 点赞 0 评论 0

项目:indy-common 作者: hyperledger-archives 项目源码 文件源码
def __call__(self, function):

        if not self.shouldCheck:
            return function

        type_hints = typing.get_type_hints(function)

        def precheck(*args, **kwargs):

            all_args = kwargs.copy()
            all_args.update(dict(zip(function.__code__.co_varnames, args)))
            runtime_args = ((n, type(v)) for n, v in all_args.items())

            for arg_name, arg_type in runtime_args:
                if arg_name not in type_hints:
                    continue
                if not self.is_subtype(arg_type, type_hints[arg_name]):
                    raise TypeError('In {} type of {} is {} and not {}'.
                                    format(function.__qualname__,
                                           arg_name,
                                           arg_type,
                                           type_hints[arg_name]))

        def postcheck(result):
            if 'return' in type_hints:
                if not self.is_subtype(type(result), type_hints['return']):
                    raise TypeError('Type of result is {} and not {}'.
                                    format(type(result), type_hints['return']))
            return result

        if inspect.iscoroutinefunction(function):
            async def type_checker(*args, **kwargs):
                precheck(*args, **kwargs)
                result = await function(*args, **kwargs)
                return postcheck(result)
        else:
            def type_checker(*args, **kwargs):
                precheck(*args, **kwargs)
                result = function(*args, **kwargs)
                return postcheck(result)

        return type_checker
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号