fix: 修复 _make_dispatcher 前向引用解析导致的 NameError
CI / Lint, Typecheck & Test (push) Has been cancelled

from __future__ import annotations 使注解变为字符串,dispatcher.__globals__ 是 tools.py 命名空间不含用户模块自定义类型(如 BumpVersionType),typer 调 get_type_hints 时 NameError。用原始函数 __globals__ 预解析后写入实际类型。
This commit is contained in:
2026-07-08 15:22:03 +08:00
parent ae4cc3aeeb
commit 8bfa0da590
+10 -1
View File
@@ -47,6 +47,7 @@ import enum
import inspect
import sys
import textwrap
import typing
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
@@ -403,7 +404,15 @@ def _make_dispatcher(tool_name: str, spec: ToolSpec) -> Callable[..., None]:
dispatcher.__signature__ = combined_sig # type: ignore[attr-defined]
dispatcher.__doc__ = spec.help or func.__doc__ or ""
dispatcher.__name__ = func.__name__
dispatcher.__annotations__ = {p.name: p.annotation for p in params}
# 预解析前向引用:from __future__ import annotations 使注解变为字符串,
# dispatcher.__globals__ 是 tools.py 命名空间,不含用户模块中的自定义类型
# (如 bumpversion.py 的 BumpVersionType),typer 调 get_type_hints 时会 NameError。
# 用原始函数的 __globals__ 解析后写入实际类型,避免运行时求值失败。
try:
resolved_hints: dict[str, Any] = typing.get_type_hints(func)
except Exception:
resolved_hints = {}
dispatcher.__annotations__ = {p.name: resolved_hints.get(p.name, p.annotation) for p in params}
return dispatcher