示例工程 06-functions-closures

06-functions-closures/03-keyword-only-api/keyword_only_api.py

python · 1.3 KB

"""演示仅位置参数 / 仅关键字参数与参数收集。"""
 
from __future__ import annotations
 
import inspect
 
 
def configure(
    host: str,
    /,
    port: int = 80,
    *,
    tls: bool = True,
    timeout: float = 5.0,
) -> dict[str, object]:
    """host 只能按位置传;tls/timeout 只能按关键字传。"""
    return {"host": host, "port": port, "tls": tls, "timeout": timeout}
 
 
def capture(*args: int, **kwargs: str) -> tuple[tuple[int, ...], dict[str, str]]:
    return args, kwargs
 
 
def error_messages() -> dict[str, str]:
    messages: dict[str, str] = {}
    try:
        configure(host="localhost")  # type: ignore[call-arg]  # 演示运行时 TypeError
    except TypeError as exc:
        messages["keyword_host"] = str(exc)
    try:
        configure("localhost", 80, True)  # type: ignore[call-arg]  # 演示运行时 TypeError
    except TypeError as exc:
        messages["positional_tls"] = str(exc)
    return messages
 
 
def signature_text() -> str:
    return str(inspect.signature(configure))
 
 
def main() -> None:
    print(f"signature: {signature_text()}")
    print(f"ok: {configure('localhost', 8080, tls=False, timeout=1.0)}")
    print(f"capture: {capture(1, 2, tag='x')}")
    for key, message in error_messages().items():
        print(f"{key}: {message}")
 
 
if __name__ == "__main__":
    main()