美文网首页
Python 严格的类型检测

Python 严格的类型检测

作者: Gascognya | 来源:发表于2020-10-18 15:24 被阅读0次

简单的反射使用案例

def strict(func):
    sig = inspect.signature(func)
    param_types = {
        key: value.annotation 
        for key, value in sig.parameters.items() 
        if value.annotation is not value.empty
    }
    return_type = sig.return_annotation

    @wraps(func)
    def wrapper(*args, **kwargs):
        param_values = sig.bind(*args, **kwargs)
        for name, value in param_values.arguments.items():
            if name in param_types:
                if not isinstance(value, param_types.get(name)):
                    raise TypeError(f'Argument "{name}" must be {param_types[name]} but got {type(value)}')
        res = func(*args, **kwargs)
        if not isinstance(res, return_type):
            raise TypeError(f'function need return {return_type} but got {type(res)}')
        return res

    return wrapper
@strict
def f(a: int, b: str = None, c: bool = False) -> str:
    return a

print(f("2", ""))
参数类型
返回值类型

相关文章

  • Python 严格的类型检测

    简单的反射使用案例

  • 类型检测typeof,instanceof,严格模式检测

    一,typeof typeof 只适用于检测基本数据类型,而引用类型返回都是object,只有function返回...

  • Python语法

    *** 环境 python解释器: *** 基础 python是动态强类型语言:运行时类型才被确定,类型校验严格,...

  • Python学习(八)

    异常处理 Python中的异常类型总结: Python内置异常类的层次结构: 异常检测 try-except语句 ...

  • Python-2nd

    Python是解释型语言, 弱类型语言----没有严格的数据类型定义和区分. print("你好啊,我是周润发")...

  • python imghdr 检测图片类型

    今天在写接口的时候,遇到一个问题,接口接收 Base64 编码的图片,然后保存到存储服务中,如何识别这个图片的格式...

  • Python 学习之路-01

    变量类型 严格意义上来讲,Python只有一种数据类型 标准数据一共有六种数字类型 Number字符串类...

  • Js类型相关总结

    Js的基本数据类型 复杂数据类型 类型检测 typeof 检测检测原理是根据变量存储时低位 instanceof检...

  • 类型检测

    一、方法1、typeof适合基本类型及function检测,遇到null失效。例子:typeof 100 ——"n...

  • 检测类型

    typeof:检测基本数据类型 例子: instanceof:检测引用类型 语法: result = variab...

网友评论

      本文标题:Python 严格的类型检测

      本文链接:https://www.haomeiwen.com/subject/xhdcmktx.html