Python 311 新特性之模式匹配和类型提示检查

2023-08-09 13:33:44 浏览数 (2)

1. 模式匹配

# 关键字 match 后跟变量名。如果匹配,则将执行 case 块内的语句

# 带有变量的案例(例如:case _: 或 case other:)需要是列表中的最后一个 case。它匹配任何值,其中该值与先前的情况不匹配,并在变量中捕获该值。

代码语言:javascript复制
def process(x):
    match x:
        case 0:
            print("What received is zero!")
        case [1, 2]:
            print("What received is list [1,2]!")
        case {'key': 'value'}:
            print("What received is dict {'key': 'value'}!")
        case float() | int():  # 判断是否是float 或 int
            print("float or int!")
        case _:
            print("Something else is received!")


def process_nested(x):
    match x:
        case {"name": str_, "age": int_, "scores": [a, b]}:
            print("Valid data structure!")
        case _:
            print("Invalid data structure!")
if __name__ == "__main__":
    process([1, 2])
    process("x")
    process(0)
    process(38.6)
    process({'key': 'value'})

    process_nested({"name": "张三", "age": 28, "scores": [78.0]})
    process_nested({"name": "张三", "age": 28, "scores": [78.0, 97]})

2. 类型提示和检查

指定函数参数和返回值的类型

代码语言:javascript复制
def add(a: int, b: int) -> int:
    return a   b


def add_(a: int | float, b: int | float) -> float:
    return a   b

if __name__ == "__main__":
    print(add(12, 3.1))  # 这里会提示 Expected type "int", got "float" instead
    print(add_(12, 3.1))

0 人点赞