Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion cmd2/annotated.py
Original file line number Diff line number Diff line change
Expand Up @@ -1726,8 +1726,16 @@ def _resolve_parameters(
# cmd2_handler, so it must exist. Here so it also fires when the function has zero parameters.
if base_command and "cmd2_handler" not in sig.parameters:
raise TypeError(f"with_annotated(base_command=True) requires a 'cmd2_handler' parameter in {func.__qualname__}")
# Resolve hints only for the parameters that become arguments
ignored = {next(iter(sig.parameters), None), *skip_params}
ignored.discard(None)
relevant_annotations = {name: ann for name, ann in getattr(func, "__annotations__", {}).items() if name not in ignored}
try:
hints = get_type_hints(func, include_extras=True)
hints = get_type_hints(
types.SimpleNamespace(__annotations__=relevant_annotations),
globalns=getattr(func, "__globals__", {}),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If func is wrapped by another decorator using @functools.wraps, its __globals__ attribute points to the decorator's module, not the original function's module. Because globalns is explicitly provided here, get_type_hints() won't traverse the __wrapped__ chain to find the correct globals. This will cause forward references (e.g., string annotations) to fail with NameError or resolve to the wrong type.

Suggested change:

ignored = {next(iter(sig.parameters), None), *skip_params}
ignored.discard(None)
relevant_annotations = {name: ann for name, ann in getattr(func, "__annotations__", {}).items() if name not in ignored}
unwrapped = inspect.unwrap(func)
try:
    hints = get_type_hints(
        types.SimpleNamespace(__annotations__=relevant_annotations),
        globalns=getattr(unwrapped, "__globals__", {}),
        include_extras=True,
    )

The key change is created unrwapped = inspect.unwrap(func) before the try and then using unwrapped instead of func in the call to getattr.

include_extras=True,
)
except (NameError, AttributeError, TypeError) as exc:
raise TypeError(
f"Failed to resolve type hints for {func.__qualname__}. Ensure all annotations use valid, importable types."
Expand Down
18 changes: 18 additions & 0 deletions tests/test_annotated.py
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,24 @@ def do_broken(self, name: "NonExistentType"): # noqa: F821
with pytest.raises(TypeError, match="Failed to resolve type hints"):
build_parser_from_function(do_broken)

def test_unresolvable_hint_on_ignored_self_is_tolerated(self) -> None:
"""An unresolvable annotation on the bound parameter (self/cls) must not abort
parser generation, since it is never turned into an argument. This happens when
``self`` is annotated with a forward reference that is only importable under
``TYPE_CHECKING``.
"""

def do_cmd(self: "UnimportableCmd", name: str, count: int = 1): # noqa: F821
pass

# Without the lenient retry this raises "Failed to resolve type hints".
parser = build_parser_from_function(do_cmd)
dests = {action.dest for action in parser._actions if action.dest != "help"}
assert dests == {"name", "count"}
ns = parser.parse_args(["alice"])
assert ns.name == "alice"
assert ns.count == 1

def test_validate_base_command_type_hints_failure_raises(self) -> None:
"""Base-command validation should raise, not swallow, type hint failures."""
from cmd2.annotated import _resolve_parameters
Expand Down
Loading