Skip to content

Commit abf27fe

Browse files
fix: fix annotated typing (#1692)
* chore: fix annotated typing c * fix(annotated): drop unnecessary string annotations, add changelog Address review feedback on PR #1692: - Remove forward-reference quotes from _WithAnnotatedDecorator.__call__ since Callable, _CommandParams, and _CommandReturn are already in scope - Add a Bug Fixes changelog entry for the with_annotated type-hint fix --------- Co-authored-by: Todd Leonhardt <todd.leonhardt@gmail.com>
1 parent 99173cc commit abf27fe

2 files changed

Lines changed: 19 additions & 2 deletions

File tree

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@
55
- **complete_in_thread**: (boolean) if `True`, then completion will run in a separate
66
thread. If `False` then completion runs in the main thread and causes it to block if slow.
77
Defaults to `True`.
8+
9+
- Bug Fixes
10+
- Fixed type hinting so that methods decorated with `with_annotated` no longer trigger spurious
11+
mypy errors and preserve their original signature.
12+
813
- Experimental features
914
- `@with_annotated` now supports `frozenset[T]` collection parameters, alongside the existing
1015
`list[T]`, `set[T]`, and `tuple[T, ...]` collection types.

cmd2/annotated.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,8 @@ def do_paint(
198198
Any,
199199
ClassVar,
200200
Literal,
201+
ParamSpec,
202+
Protocol,
201203
TypedDict,
202204
TypeVar,
203205
Union,
@@ -2137,8 +2139,18 @@ def handler(self_arg: Any, ns: Any) -> Any:
21372139
return handler, subcmd_name, parser_builder
21382140

21392141

2142+
_CommandParams = ParamSpec("_CommandParams")
2143+
_CommandReturn = TypeVar("_CommandReturn")
2144+
2145+
2146+
class _WithAnnotatedDecorator(Protocol):
2147+
"""The signature-preserving decorator ``with_annotated(...)`` returns (generic per call)."""
2148+
2149+
def __call__(self, fn: Callable[_CommandParams, _CommandReturn], /) -> Callable[_CommandParams, _CommandReturn]: ...
2150+
2151+
21402152
@overload
2141-
def with_annotated(func: Callable[..., Any]) -> Callable[..., Any]: ...
2153+
def with_annotated(func: Callable[_CommandParams, _CommandReturn]) -> Callable[_CommandParams, _CommandReturn]: ...
21422154

21432155

21442156
@overload
@@ -2161,7 +2173,7 @@ def with_annotated(
21612173
subcommand_title: str | None = ...,
21622174
subcommand_description: str | None = ...,
21632175
**parser_kwargs: Unpack[Cmd2ParserKwargs],
2164-
) -> Callable[[Callable[..., Any]], Callable[..., Any]]: ...
2176+
) -> _WithAnnotatedDecorator: ...
21652177

21662178

21672179
def with_annotated(

0 commit comments

Comments
 (0)