示例工程 30-plugin-registry-design

30-plugin-registry-design/01-decorator-registry/decorator_registry.py

python · 1.0 KB

"""用装饰器实现命令注册表。"""
 
from __future__ import annotations
 
from collections.abc import Callable
 
REGISTRY: dict[str, Callable[..., str]] = {}
 
 
def register(name: str) -> Callable[[Callable[..., str]], Callable[..., str]]:
    def decorator(func: Callable[..., str]) -> Callable[..., str]:
        if name in REGISTRY:
            raise ValueError(f"duplicate command: {name}")
        REGISTRY[name] = func
        return func
 
    return decorator
 
 
@register("hello")
def hello(name: str) -> str:
    return f"hello {name}"
 
 
@register("bye")
def bye(name: str) -> str:
    return f"bye {name}"
 
 
def run(name: str, *args: str) -> str:
    return REGISTRY[name](*args)
 
 
def main() -> None:
    print(f"commands: {sorted(REGISTRY)}")
    print(f"hello: {run('hello', 'Ada')}")
    try:
 
        @register("hello")
        def duplicate(name: str) -> str:
            return name
 
    except ValueError as exc:
        print(f"duplicate: {exc}")
 
 
if __name__ == "__main__":
    main()