strict_types.py 文件源码

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

项目:old-sovrin 作者: sovrin-foundation 项目源码 文件源码
def __call__(self, function):

        if not self.shouldCheck:
            return function

        hints = get_type_hints(function)

        def precheck(*args, **kwargs):

            all_args = kwargs.copy()
            all_args.update(dict(zip(function.__code__.co_varnames, args)))

            for argument, argument_type in ((i, type(j)) for i, j in all_args.items()):
                if argument in hints:
                    if not issubclass(argument_type, hints[argument]):
                        raise TypeError('Type of {} is {} and not {}'.
                                        format(argument,
                                               argument_type,
                                               hints[argument]))

        def postcheck(result):
            if 'return' in hints:
                if not isinstance(result, hints['return']):
                    raise TypeError('Type of result is {} and not {}'.
                                    format(type(result), 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
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号