# ===== CodeLab: Python 3.10 新特性:match 模式匹配与联合类型 =====
# 来源: https://aoerliang.dpdns.org/articles/python-310-features
# 以下代码片段按文章出现顺序拼接, 共 8 段

# ----- 片段 1 (python) -----
def describe(status):
    match status:
        case 200:
            return "OK"
        case 404:
            return "未找到"
        case int(n) if n >= 500:
            return f"服务器错误 {n}"
        case int(n):
            return f"其它状态码 {n}"
        case str(s):
            return f"状态字符串 {s!r}"
        case _:
            return "无法识别的状态"

# ----- 片段 2 (python) -----
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

def locate(p):
    match p:
        case Point(x=0, y=0):
            return "原点"
        case Point(x=0, y=y):
            return f"在 y 轴上,y={y}"
        case Point(x=x, y=y):
            return f"普通点 ({x}, {y})"
        case _:
            return "不是 Point 对象"

print(locate(Point(0, 0)))    # 原点
print(locate(Point(0, 5)))    # 在 y 轴上,y=5
print(locate(Point(3, 4)))    # 普通点 (3, 4)

# ----- 片段 3 (python) -----
def parse_command(args):
    match args:
        case ["quit"]:
            return "退出"
        case ["add", x, y]:
            return f"加法: {int(x) + int(y)}"
        case ["serve", port] if port.isdigit():
            return f"在端口 {port} 启动服务"
        case [name, *rest]:
            return f"{name},还有参数 {rest}"
        case _:
            return "无法识别"

print(parse_command(["add", "3", "4"]))    # 加法: 7
print(parse_command(["serve", "8080"]))    # 在端口 8080 启动服务

# ----- 片段 4 (python) -----
def parse_id(value: int | str) -> int:
    if isinstance(value, str):
        return int(value)
    return value

def find(key: str) -> dict | None:
    """返回字典,找不到时返回 None"""
    ...

# ----- 片段 5 (python) -----
def check(x):
    if isinstance(x, int | str):
        print("整数或字符串")
    else:
        print("其它类型")

# ----- 片段 6 (python) -----
names = ["a", "b"]
scores = [90, 85, 95]

for n, s in zip(names, scores, strict=True):
    print(n, s)
# ValueError: zip() argument 2 is longer than argument 1

# ----- 片段 7 (python) -----
with (
    open("a.txt") as fa,
    open("b.txt") as fb,
):
    print(fa.read(), fb.read())

# ----- 片段 8 (bash) -----
pyenv install 3.10.16
pyenv global 3.10.16
python3.10 --version
python3.10 -m pip install --upgrade pip
python3.10 -m venv .venv && source .venv/bin/activate
