蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHON本地 Python 环境python-type-hints.py
python-type-hints.py138 行
"""蓝色天空网 mbsky.com | Observe annotations and runtime behavior on owned values."""
import inspect
from pathlib import Path
import sys
from typing import Any, Dict, List, Optional, Set, Tuple, TypedDict, Union, get_args, get_origin, get_type_hints

sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks


hub: str = "dock"
retries: int = 2
enabled: bool = True
minutes: list[int] = [12, 20]
future_rate: int


def raw_notice(code, suffix):
    return f"{code}-{suffix}"


def notice(code: str, suffix: str) -> str:
    return f"{code}-{suffix}"


def combine(first: int, second: int) -> int:
    return first + second


def repeat(label: str, times: int = 1) -> str:
    return " ".join([label] * times)


def find_hub(label: str) -> str | None:
    return {"dock": "A1"}.get(label)


def read_label(label: str | None) -> str:
    return label if label is not None else "missing"


def describe(data: str | int | list[int]) -> None:
    if isinstance(data, str):
        print(f"text={data}")
    elif type(data) is int:
        print(f"integer={data}")
    elif isinstance(data, list) and all(type(item) is int for item in data):
        print(f"minutes={data}")
    else:
        raise TypeError("expected text, integer or list of integers")


class Delivery(TypedDict):
    hub: str
    minutes: int


def mean_minutes(deliveries: list[Delivery]) -> float | None:
    if not deliveries:
        return None
    return sum(delivery["minutes"] for delivery in deliveries) / len(deliveries)


def statistics(values: list[float]) -> dict[str, float]:
    return {"mean": sum(values) / len(values), "maximum": max(values)}


def main():
    import contextlib
    import io

    checks = Checks()
    checks.eq("annotated and plain functions agree on valid inputs",
              (raw_notice("P7", "ready"), notice("P7", "ready")), ("P7-ready", "P7-ready"))
    checks.eq("function parameter and return metadata",
              {name: value.__name__ for name, value in get_type_hints(notice).items()},
              {"code": "str", "suffix": "str", "return": "str"})
    checks.eq("module annotated variables preserve values", (hub, retries, enabled, minutes),
              ("dock", 2, True, [12, 20]))
    checks.eq("annotation without assignment records type", __annotations__["future_rate"] is int, True)
    checks.eq("annotation alone creates no readable value", "future_rate" in globals(), False)
    checks.eq("integer addition", combine(7, 8), 15)
    wrong: Any = "7"
    other: Any = "8"
    checks.eq("wrong annotated arguments still concatenate", combine(wrong, other), "78")
    checks.raises("mixed values fail at actual operator", TypeError, lambda: combine(wrong, 8))
    checks.eq("annotation does not convert return value", type(combine(wrong, other)).__name__, "str")
    checks.eq("repeat default explicit and zero", (repeat("dock"), repeat("dock", 3), repeat("dock", 0)),
              ("dock", "dock dock dock", ""))
    checks.eq("optional hit and miss", (find_hub("dock"), find_hub("missing")), ("A1", None))
    checks.eq("explicit None accepted", read_label(None), "missing")
    checks.raises("nullable argument without default remains required", TypeError, lambda: read_label())
    checks.eq("optional spelling equivalent to union", Optional[str] == Union[str, None] == (str | None), True)
    pairs = ((List[int], list[int], (int,)),
             (Dict[str, int], dict[str, int], (str, int)),
             (Tuple[int, str, bool], tuple[int, str, bool], (int, str, bool)),
             (Set[str], set[str], (str,)))
    for legacy, modern, expected in pairs:
        label = get_origin(modern).__name__
        checks.eq(f"legacy and modern {label} origins", get_origin(legacy) is get_origin(modern), True)
        checks.eq(f"legacy and modern {label} parameters",
                  get_args(legacy) == get_args(modern) == expected, True)
    collection: list[int] = [18]
    collection.append(wrong)
    checks.eq("element annotation is not a runtime filter", collection, [18, "7"])
    checks.raises("parameterized generic cannot be isinstance target", TypeError,
                  lambda: isinstance(collection, list[int]))
    for value, line in (("dock", "text=dock"), (12, "integer=12"), ([12, 20], "minutes=[12, 20]")):
        stream = io.StringIO()
        with contextlib.redirect_stdout(stream):
            result = describe(value)
        checks.eq("union branch " + type(value).__name__, (stream.getvalue().strip(), result), (line, None))
    checks.raises("list check needs item verification", TypeError, lambda: describe([wrong]))
    checks.raises("explicit validation rejects boolean case", TypeError, lambda: describe(True))
    checks.eq("TypedDict value is ordinary dict", type(Delivery(hub="A", minutes=12)) is dict, True)
    checks.eq("structured average empty and populated",
              (mean_minutes([]), mean_minutes([{"hub": "A", "minutes": 12}, {"hub": "B", "minutes": 20}])),
              (None, 16.0))
    missing_field: Any = [{"hub": "A"}]
    invalid_field: Any = [{"hub": "B", "minutes": "slow"}]
    checks.raises("missing field is runtime KeyError", KeyError, lambda: mean_minutes(missing_field))
    checks.raises("invalid field fails actual addition", TypeError, lambda: mean_minutes(invalid_field))
    checks.eq("annotated statistics on floats", statistics([2.0, 6.0]), {"mean": 4.0, "maximum": 6.0})

    eager = {"hits": []}
    exec("def mark():\n    hits.append('evaluated')\n    return int\ndef build(n: mark()):\n    return n\n", eager)
    checks.eq("3.12 default evaluates function annotation at definition", eager["hits"], ["evaluated"])
    postponed = {}
    exec("from __future__ import annotations\ndef build(n: int) -> int:\n    return n\n", postponed)
    checks.eq("future annotation remains string", inspect.get_annotations(postponed["build"]), {"n": "int", "return": "int"})
    checks.eq("read trusted postponed hint", get_type_hints(postponed["build"])["return"] is int, True)
    checks.finish("python-type-hints", runtime=sys.version, implementation=sys.implementation.name,
                  annotation_scope="actual CPython 3.12 interpreter observations; checker and editor states separate")


if __name__ == "__main__":
    main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 环境

入口文件:projects/python-lab/python-type-hints.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python-type-hints.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 环境。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习