示例工程 12-decorators-functools
12-decorators-functools/04-singledispatch/singledispatch.py
"""演示 singledispatch 按运行时类型分派,替代 if/elif。"""
from __future__ import annotations
from functools import singledispatch
@singledispatch
def describe(value: object) -> str:
return f"object:{type(value).__name__}"
@describe.register
def _(value: int) -> str:
return f"int:{value}"
@describe.register
def _(value: str) -> str:
return f"str:{value}"
@describe.register(list)
def _(value: list[object]) -> str:
return f"list:{len(value)}"
def main() -> None:
print(f"int: {describe(3)}")
print(f"str: {describe('x')}")
print(f"list: {describe([1, 2, 3])}")
print(f"float: {describe(3.5)}")
print(f"bool: {describe(True)}")
print(f"registry: {[cls.__name__ for cls in describe.registry]}")
print(f"float handler: {describe.dispatch(float).__name__}")
if __name__ == "__main__":
main()