| 1 | # Annotated Argument Processing |
| 2 | |
| 3 | !!! warning "Experimental" |
| 4 | |
| 5 | The `@with_annotated` decorator and its supporting `Argument` / `Option` metadata classes are |
| 6 | **experimental**. The public API, the surface of accepted type annotations, and the generated |
| 7 | argparse behavior may all change in future releases without a deprecation cycle. Pin a specific |
| 8 | `cmd2` version if you depend on the exact current semantics, and expect to revisit your usage on |
| 9 | upgrades. |
| 10 | |
| 11 | For production code that needs stable behavior, use |
| 12 | [@with_argparser](argument_processing.md#with_argparser-decorator) instead. |
| 13 | |
| 14 | The [@with_annotated][cmd2.with_annotated] decorator builds an argparse parser automatically from |
| 15 | the decorated function's type annotations. No manual `add_argument()` calls are required, and the |
| 16 | command body receives typed keyword arguments directly instead of an `argparse.Namespace`. |
| 17 | |
| 18 | The two decorators are interchangeable -- here is the same command written both ways: |
| 19 | |
| 20 | === "@with_annotated" |
| 21 | |
| 22 | ```py |
| 23 | @with_annotated |
| 24 | def do_greet(self, name: str, count: int = 1, loud: bool = False): |
| 25 | for _ in range(count): |
| 26 | msg = f"Hello {name}" |
| 27 | self.poutput(msg.upper() if loud else msg) |
| 28 | ``` |
| 29 | |
| 30 | === "@with_argparser" |
| 31 | |
| 32 | ```py |
| 33 | parser = Cmd2ArgumentParser() |
| 34 | parser.add_argument('name', help='person to greet') |
| 35 | parser.add_argument('--count', type=int, default=1, help='repetitions') |
| 36 | parser.add_argument('--loud', action='store_true', help='shout') |
| 37 | |
| 38 | @with_argparser(parser) |
| 39 | def do_greet(self, args): |
| 40 | for _ in range(args.count): |
| 41 | msg = f"Hello {args.name}" |
| 42 | self.poutput(msg.upper() if args.loud else msg) |
| 43 | ``` |
| 44 | |
| 45 | The annotated version is more concise, gives you typed parameters, and supports several advanced |
| 46 | cmd2 features directly, including `ns_provider`, `with_unknown_args`, and typed subcommands. Pick |
| 47 | `@with_argparser` when you need a stable, well-established API or fine-grained control over the |
| 48 | parser; pick `@with_annotated` when you want type-hint-driven ergonomics and can accept the |
| 49 | experimental status. |
| 50 | |
| 51 | ## Basic usage |
| 52 | |
| 53 | Parameters without defaults become positional arguments. Parameters with defaults become `--option` |
| 54 | flags. Keyword-only parameters (after `*`) always become options, and without a default they become |
| 55 | required options. |
| 56 | |
| 57 | Underscores in parameter names are converted to dashes in the generated flag, so `dry_run` becomes |
| 58 | `--dry-run`. The Python identifier you read inside the function body keeps its underscored form |
| 59 | (`args.dry_run`). To opt out, pass explicit names via `Option("--my_flag", ...)`. |
| 60 | |
| 61 | ```py |
| 62 | from cmd2.annotated import with_annotated |
| 63 | |
| 64 | class MyApp(cmd2.Cmd): |
| 65 | @with_annotated |
| 66 | def do_greet(self, name: str, count: int = 1, loud: bool = False): |
| 67 | """Greet someone.""" |
| 68 | for _ in range(count): |
| 69 | msg = f"Hello {name}" |
| 70 | self.poutput(msg.upper() if loud else msg) |
| 71 | ``` |
| 72 | |
| 73 | The command `greet Alice --count 3 --loud` parses `name="Alice"`, `count=3`, `loud=True` and passes |
| 74 | them as keyword arguments. |
| 75 | |
| 76 | ## How annotations map to argparse |
| 77 | |
| 78 | The decorator converts Python type annotations into `add_argument()` calls: |
| 79 | |
| 80 | | Type annotation | Generated argparse setting | |
| 81 | | ------------------------------------------------------- | ---------------------------------------------------------- | |
| 82 | | `str` | default (no `type=` needed) | |
| 83 | | `int`, `float` | `type=int` or `type=float` | |
| 84 | | `bool` with a default | boolean optional flag via `BooleanOptionalAction` | |
| 85 | | positional `bool` | parsed from `true/false`, `yes/no`, `on/off`, `1/0` | |
| 86 | | `Path` | `type=Path` | |
| 87 | | `Enum` subclass | `type=converter`, `choices` from member values | |
| 88 | | `EnumA \| EnumB` (all members `Enum`) | first member to accept a token wins; `choices` merged | |
| 89 | | `decimal.Decimal` | `type=decimal.Decimal` | |
| 90 | | `Literal[...]` | `type=literal-converter`, `choices` from values | |
| 91 | | `list[T]` / `set[T]` / `frozenset[T]` / `tuple[T, ...]` | `nargs='+'` (or `'*'` if it has a default or is `\| None`) | |
| 92 | | `tuple[T, T]` | fixed `nargs=N` with `type=T` | |
| 93 | | `T \| None` (no default) | positional with `nargs='?'` (accepts 0-or-1 tokens) | |
| 94 | | `T \| None = None` | `--flag` option with `default=None` | |
| 95 | |
| 96 | When collection types are used with `@with_annotated`, parsed values are passed to the command |
| 97 | function as: |
| 98 | |
| 99 | - `list[T]` as `list` |
| 100 | - `set[T]` as `set` |
| 101 | - `frozenset[T]` as `frozenset` |
| 102 | - `tuple[T, ...]` as `tuple` |
| 103 | |
| 104 | Unsupported patterns raise `TypeError`, including: |
| 105 | |
| 106 | - unions with multiple non-`None` members such as `str | int`, unless every member is an `Enum` |
| 107 | subclass (e.g. `EnumA | EnumB`), which resolves by trying each member's converter in order |
| 108 | - mixed-type tuples such as `tuple[int, str]` |
| 109 | - `Annotated[T, meta] | None`; write `Annotated[T | None, meta]` instead |
| 110 | - `Annotated[T, Argument(nargs=N)]` where `N` is `'*'`, `'+'`, or an integer `>= 1` and `T` is not a |
| 111 | collection type. `nargs` values that produce a list of values need a collection annotation such as |
| 112 | `list[T]` or `tuple[T, ...]`. |
| 113 | - an optional fixed-arity positional, such as `Annotated[tuple[int, int], Argument()] = (1, 2)`, |
| 114 | `Annotated[tuple[int, int] | None, Argument()]`, or any positional `Argument(nargs=N)` with a |
| 115 | default or `| None`. argparse cannot make a fixed-arity positional optional (there is no `nargs` |
| 116 | for "absent or exactly `N` tokens"), so use a variable-arity type like `tuple[T, ...]`, drop the |
| 117 | default, or make it an option (give it a default without `Argument()`). |
| 118 | - `Annotated[tuple[T, T], Argument(nargs=N)]` where `N` differs from the number of elements declared |
| 119 | by the tuple. The tuple type already pins `nargs`; user metadata cannot change it. |
| 120 | |
| 121 | The parameter names `dest` and `subcommand` are reserved and may not be used as annotated parameter |
| 122 | names. `cmd2_statement` receives the parsed [cmd2.Statement][] object, and `cmd2_subcommand_func` |
| 123 | (only on a command decorated with `@with_annotated(base_command=True)`) receives the subcommand |
| 124 | handler. |
| 125 | |
| 126 | ## Annotated metadata |
| 127 | |
| 128 | For finer control, use `typing.Annotated` with [Argument][cmd2.annotated.Argument] or |
| 129 | [Option][cmd2.annotated.Option] metadata: |
| 130 | |
| 131 | ```py |
| 132 | from typing import Annotated |
| 133 | from cmd2.annotated import Argument, Option, with_annotated |
| 134 | |
| 135 | class MyApp(cmd2.Cmd): |
| 136 | def sport_choices(self) -> cmd2.Choices: |
| 137 | return cmd2.Choices.from_values(["football", "basketball"]) |
| 138 | |
| 139 | @with_annotated |
| 140 | def do_play( |
| 141 | self, |
| 142 | sport: Annotated[str, Argument( |
| 143 | choices_provider=sport_choices, |
| 144 | help_text="Sport to play", |
| 145 | )], |
| 146 | venue: Annotated[str, Option( |
| 147 | "--venue", "-v", |
| 148 | help_text="Where to play", |
| 149 | completer=cmd2.Cmd.path_complete, |
| 150 | )] = "home", |
| 151 | ): |
| 152 | self.poutput(f"Playing {sport} at {venue}") |
| 153 | ``` |
| 154 | |
| 155 | Both `Argument` and `Option` accept the same cmd2-specific fields as `add_argument()`: `choices`, |
| 156 | `choices_provider`, `completer`, `table_columns`, `suppress_tab_hint`, `metavar`, `nargs`, and |
| 157 | `help_text`. They also accept `converter` / `preprocess` for |
| 158 | [custom conversion](#custom-conversion-converter-and-preprocess) and `allow_unknown_entry` for |
| 159 | [enum aliases](#enum-aliases-and-special-keywords-allow_unknown_entry). |
| 160 | |
| 161 | `Option` additionally accepts `action`, `required`, and positional `*names` for custom flag strings |
| 162 | (e.g. `Option("--color", "-c")`). |
| 163 | |
| 164 | ### Enum aliases and special keywords (`allow_unknown_entry`) |
| 165 | |
| 166 | By default an `Enum` parameter accepts only member values and member names. To let an enum also |
| 167 | accept aliases, alternate spellings, or special keywords, define the standard Python |
| 168 | [`_missing_`](https://docs.python.org/3/library/enum.html#enum.Enum._missing_) hook on the enum and |
| 169 | opt in with `allow_unknown_entry=True`: |
| 170 | |
| 171 | ```py |
| 172 | import enum |
| 173 | from typing import Annotated |
| 174 | from cmd2.annotated import Argument, with_annotated |
| 175 | |
| 176 | class Color(enum.Enum): |
| 177 | red = "red" |
| 178 | green = "green" |
| 179 | blue = "blue" |
| 180 | |
| 181 | @classmethod |
| 182 | def _missing_(cls, value): |
| 183 | # map a special keyword onto a real member; return None to reject |
| 184 | return cls.red if str(value).lower() == "auto" else None |
| 185 | |
| 186 | class MyApp(cmd2.Cmd): |
| 187 | @with_annotated |
| 188 | def do_theme(self, choice: Annotated[Color, Argument(allow_unknown_entry=True)]) -> None: |
| 189 | self.poutput(f"theme set to {choice.value}") |
| 190 | ``` |
| 191 | |
| 192 | `theme auto` now resolves through `_missing_` to `Color.red`, while `theme red` (value) and |
| 193 | `theme green` (name) keep working as before. A token that `_missing_` declines (returns `None`) is |
| 194 | still rejected with the usual "choose from ..." error. Any exception `_missing_` itself raises |
| 195 | propagates as-is (it is not masked as an "invalid choice"). The flag has no effect on non-`Enum` |
| 196 | annotations, and an `Enum` that does not override `_missing_` inherits the default (which returns |
| 197 | `None`), so the flag is simply inert for it. It also applies when the enum is a collection element |
| 198 | (e.g. `Annotated[list[Color], Argument(allow_unknown_entry=True)]`). |
| 199 | |
| 200 | Because `_missing_` aliases are dynamic, they are not added to the advertised `choices`, so they do |
| 201 | not appear in `--help` or tab-completion; the canonical member values remain the listed choice set. |
| 202 | |
| 203 | ### Unions of Enums |
| 204 | |
| 205 | A parameter annotated as a union whose members are all `Enum` subclasses (e.g. `EnumA | EnumB`) is |
| 206 | accepted. Each member keeps its own converter, and a token is resolved by the **first member that |
| 207 | accepts it**: |
| 208 | |
| 209 | ```py |
| 210 | @with_annotated |
| 211 | def do_pick(self, choice: Suit | Rank) -> None: |
| 212 | if isinstance(choice, Suit): |
| 213 | self.poutput(f"suit {choice.name}") |
| 214 | else: |
| 215 | self.poutput(f"rank {choice.name}") |
| 216 | ``` |
| 217 | |
| 218 | Because resolution is first-match-wins, **order matters**: if a token is a valid value (or name) for |
| 219 | more than one member, the member listed first in the union wins, and the later member's identical |
| 220 | token becomes unreachable. `allow_unknown_entry` and each member's `_missing_` hook still apply per |
| 221 | member; a member whose `_missing_` _raises_ on a token (rather than returning `None`) simply |
| 222 | declines it, so the next member is still tried and the raise does not abort the whole union. Only |
| 223 | when every member declines is the usual "choose from ..." error raised. Only `Enum` members are |
| 224 | supported; a union containing a `Literal` or any non-`Enum` type is still rejected as ambiguous. |
| 225 | |
| 226 | When the two value sets overlap, prefer [typed subcommands](#annotated-subcommands) (one `Enum` per |
| 227 | subcommand) so the choice is explicit and collision-free. |
| 228 | |
| 229 | ### Actions |
| 230 | |
| 231 | When an `Option(action=...)` uses a zero-argument argparse action that takes no value from the |
| 232 | command line (`count`, `store_true`, `store_false`, `store_const`, `append_const`), |
| 233 | `@with_annotated` strips the value-oriented metadata it inferred from the type before calling |
| 234 | `add_argument()`: |
| 235 | |
| 236 | - the `type` converter, |
| 237 | - the static `choices`, and |
| 238 | - any inferred tab-completer (such as the path completer for `Path`) or `choices_provider`. |
| 239 | |
| 240 | This matches argparse behavior (which rejects a completer on a value-less action) and avoids |
| 241 | parser-construction errors such as combining `action='count'` with `type=int`. Actions that _do_ |
| 242 | consume values (`append` / `extend` on a `list[T]`, or a plain value option) keep the inferred |
| 243 | converter and completer. |
| 244 | |
| 245 | Pairing `const` with an explicit `nargs` on a scalar `Option` selects argparse's optional-value |
| 246 | idiom instead of `store_const`. `Annotated[str | None, Option("--log", nargs='?', const="CONSOLE")]` |
| 247 | keeps the `store` action and the inferred `type` converter, so the flag is three-way: |
| 248 | |
| 249 | - absent yields the default, |
| 250 | - a bare `--log` yields the `const`, and |
| 251 | - `--log VALUE` yields the converted `VALUE`. |
| 252 | |
| 253 | The `const` is stored verbatim (it is not run through the converter), so it must already match the |
| 254 | declared type. Without an explicit `nargs`, `const` alone still infers the value-less `store_const` |
| 255 | (present yields the `const`, and supplying a value is an error). |
| 256 | |
| 257 | `Option(action=...)` also accepts a custom `argparse.Action` subclass. The class is passed straight |
| 258 | through to `add_argument()` and owns storage of the parsed value, so the type-inferred collection |
| 259 | casting and the action-specific type/const/shape constraints are skipped; the inferred `type=` |
| 260 | converter, default, and `required` are still applied so the class receives them like any hand-built |
| 261 | `add_argument()` call. |
| 262 | |
| 263 | ```py |
| 264 | class UpperAction(argparse.Action): |
| 265 | def __call__(self, parser, namespace, values, option_string=None): |
| 266 | setattr(namespace, self.dest, values.upper()) |
| 267 | |
| 268 | @with_annotated |
| 269 | def do_shout(self, name: Annotated[str, Option("--name", action=UpperAction)] = ""): |
| 270 | self.poutput(name) |
| 271 | ``` |
| 272 | |
| 273 | `action='help'` and `action='version'` are not supported by `@with_annotated`; use `@with_argparser` |
| 274 | if you need them. |
| 275 | |
| 276 | ### Reserved keyword arguments |
| 277 | |
| 278 | `Argument()` and `Option()` refuse a handful of `add_argument()` kwargs that the decorator derives |
| 279 | from the function signature itself, so misusing them surfaces as a clear `TypeError` instead of a |
| 280 | silent override. The refused kwargs are: |
| 281 | |
| 282 | - `type` -- comes from the parameter annotation; for a custom string-to-value callable use |
| 283 | [`converter`](#custom-conversion-converter-and-preprocess) (or `preprocess` to transform the token |
| 284 | first) |
| 285 | - `dest` -- comes from the parameter name |
| 286 | - `action` and `required` on `Argument` -- only `Option` accepts them; positional arguments have no |
| 287 | action and are required unless they carry a default or `| None` |
| 288 | |
| 289 | Every other `add_argument()` parameter passes through, including any custom parameter registered via |
| 290 | [register_argparse_argument_parameter][cmd2.argparse_utils.register_argparse_argument_parameter]. |
| 291 | |
| 292 | ### Defaults |
| 293 | |
| 294 | A `default` may be supplied either through the function signature or as a metadata kwarg. The two |
| 295 | forms are equivalent: |
| 296 | |
| 297 | ```py |
| 298 | # Signature default |
| 299 | def do_x(self, name: Annotated[str, Option("--name")] = "HI"): ... |
| 300 | |
| 301 | # Metadata default (same behaviour) |
| 302 | def do_x(self, name: Annotated[str, Option("--name", default="HI")]): ... |
| 303 | ``` |
| 304 | |
| 305 | Specifying both at the same time is a conflict and raises `TypeError`. `argparse.SUPPRESS` is |
| 306 | rejected as a default from either source, because suppressing the namespace attribute would call the |
| 307 | function without the keyword argument it expects. |
| 308 | |
| 309 | Parser-construction kwargs such as `add_help`, `prefix_chars`, `fromfile_prefix_chars`, |
| 310 | `argument_default`, `conflict_handler`, and `allow_abbrev` are not exposed by `@with_annotated`. Set |
| 311 | them on a custom `parser_class` subclass and pass it via `parser_class=`. |
| 312 | |
| 313 | ### Choices and enums |
| 314 | |
| 315 | When a user-supplied `choices_provider` or `completer` is given for an inferred `Enum` or `Literal`, |
| 316 | the inferred static `choices` list is dropped so completion is driven by the provider or completer. |
| 317 | The inferred `type` converter is preserved, so parsed values still coerce to the declared type |
| 318 | (`Literal[1, 2]` yields an `int`, an `Enum` yields its member) and values outside the type are |
| 319 | rejected at parse time. |
| 320 | |
| 321 | An explicit `choices=` is reconciled with the inferred type rather than fighting it: |
| 322 | |
| 323 | - The values are run through the inferred `type` converter so they match argparse's post-conversion |
| 324 | comparison. `Annotated[int, Option("--n", choices=["1", "2"])]` is normalized to `choices=[1, 2]`, |
| 325 | so `--n 1` is accepted. A choice the converter rejects (`choices=["1", "nope"]` on an `int`) is a |
| 326 | build-time `TypeError`. Values already of the declared type are left as-is. |
| 327 | - An explicit `choices=` takes precedence over a _type-inferred_ completer (such as the `Path` |
| 328 | completer): the choices are kept (so they validate and drive completion) and the inferred |
| 329 | completer is dropped. A `choices_provider`/`completer` you pass yourself still wins over |
| 330 | `choices=`. |
| 331 | |
| 332 | An `Enum` parameter accepts both member **values** and member **names** on the command line |
| 333 | (`Color.RED` with value `"red"` is selected by either `red` or `RED`); tab-completion and `--help` |
| 334 | list the values. |
| 335 | |
| 336 | ### Custom conversion (`converter` and `preprocess`) |
| 337 | |
| 338 | With `@with_argparser` you can pass any callable as `add_argument(type=...)` to parse a token into a |
| 339 | custom value. `@with_annotated` derives `type=` from the annotation instead, and rejects a raw |
| 340 | `type=` in the metadata (it would silently shadow the inferred converter). Two hooks give the same |
| 341 | power without that footgun: |
| 342 | |
| 343 | - `converter` -- a `Callable[[str], Any]` that **replaces** the inferred `type=` converter. |
| 344 | - `preprocess` -- a `Callable[[str], str]` that runs **before** the inferred converter. |
| 345 | |
| 346 | They differ in what survives. A `converter` owns the whole conversion, so the inferred `choices` and |
| 347 | completer (which described the inferred value-space) are dropped. A `preprocess` only transforms the |
| 348 | raw token, so the inferred `type=`, `choices`, completer, and coercion are all kept. |
| 349 | |
| 350 | #### `converter`: replace the conversion |
| 351 | |
| 352 | Use `converter` when the annotation's built-in conversion is wrong for your input, or when the type |
| 353 | has no built-in conversion at all. Because the converter owns the conversion, the annotation no |
| 354 | longer has to be one of the supported scalar types -- any type is legal, and the usual "unsupported |
| 355 | type" error is suppressed: |
| 356 | |
| 357 | ```py |
| 358 | import datetime |
| 359 | from typing import Annotated |
| 360 | from cmd2.annotated import Argument, Option, with_annotated |
| 361 | |
| 362 | def parse_size(value: str) -> int: |
| 363 | """Parse an integer with an optional K/M/G suffix.""" |
| 364 | multiplier = {"K": 1_000, "M": 1_000_000, "G": 1_000_000_000}.get(value[-1:].upper(), 1) |
| 365 | return int(value[:-1] if multiplier != 1 else value) * multiplier |
| 366 | |
| 367 | class MyApp(cmd2.Cmd): |
| 368 | @with_annotated |
| 369 | def do_alloc(self, size: Annotated[int, Argument(converter=parse_size)]) -> None: |
| 370 | self.poutput(f"Allocating {size} bytes") # `alloc 64K` -> 64000 |
| 371 | |
| 372 | @with_annotated |
| 373 | def do_at(self, when: Annotated[datetime.datetime, Option("--when", converter=datetime.datetime.fromisoformat)]): |
| 374 | self.poutput(when.isoformat()) # `datetime` has no inferred converter, so converter= makes it legal |
| 375 | ``` |
| 376 | |
| 377 | argparse applies `type=` per token, so on a `list[T]` the converter runs on each value. To take a |
| 378 | **single** token and have the converter return a whole collection (the one-token-to-many idiom), |
| 379 | annotate with a non-collection type such as `Any` -- a collection annotation like `set[int]` would |
| 380 | instead infer `nargs` and split the input across several tokens: |
| 381 | |
| 382 | ```py |
| 383 | from typing import Annotated, Any |
| 384 | |
| 385 | def parse_intset(value: str) -> set[int]: |
| 386 | return {int(piece) for piece in value.split(",")} |
| 387 | |
| 388 | @with_annotated |
| 389 | def do_select(self, idx: Annotated[Any, Option("--idx", converter=parse_intset)]) -> None: |
| 390 | self.poutput(sorted(idx)) # `select --idx 1,3,5` -> [1, 3, 5] |
| 391 | ``` |
| 392 | |
| 393 | An explicit `choices=` is still reconciled against the converter (its values are run through the |
| 394 | converter), so you can re-add a restricted choice set after replacing the conversion. |
| 395 | |
| 396 | #### `preprocess`: normalize before the inferred conversion |
| 397 | |
| 398 | Use `preprocess` when the inferred conversion is correct but the raw token needs massaging first. |
| 399 | The inferred `type=`, `choices`, and completer are kept, so an `Enum` keeps its choices and |
| 400 | completion while accepting normalized input, and a `Path` keeps its completer: |
| 401 | |
| 402 | ```py |
| 403 | import os |
| 404 | from typing import Annotated |
| 405 | from cmd2.annotated import Argument, with_annotated |
| 406 | |
| 407 | class MyApp(cmd2.Cmd): |
| 408 | @with_annotated |
| 409 | def do_tag(self, color: Annotated[Color, Argument(preprocess=str.lower)]) -> None: |
| 410 | self.poutput(color.value) # `tag RED` works, and `tag <TAB>` still lists the colors |
| 411 | |
| 412 | @with_annotated |
| 413 | def do_open(self, path: Annotated[Path, Argument(preprocess=os.path.expanduser)]) -> None: |
| 414 | self.poutput(path) # `open ~/file` expands, path completion still works |
| 415 | ``` |
| 416 | |
| 417 | With a plain `str` (no inferred converter) the `preprocess` callable simply becomes the `type=`. |
| 418 | |
| 419 | `converter` and `preprocess` are **mutually exclusive** on one parameter -- a converter already |
| 420 | receives the raw token, so fold the preprocessing into it. Neither may be combined with a value-less |
| 421 | action (`store_true`, `store_false`, `count`, `store_const`, `append_const`), which consumes no |
| 422 | token to convert. Both raise `TypeError` at decoration time. |
| 423 | |
| 424 | ## Decorator options |
| 425 | |
| 426 | `@with_annotated` currently supports: |
| 427 | |
| 428 | - `ns_provider` -- prepopulate the namespace before parsing, mirroring `@with_argparser` |
| 429 | - `preserve_quotes` -- if `True`, quotes in arguments are preserved |
| 430 | - `with_unknown_args` -- if `True`, unrecognised arguments are passed as `_unknown` |
| 431 | - `subcommand_to` -- register the function as an annotated subcommand under a parent command |
| 432 | - `base_command` -- create a base command whose parser also adds subparsers and exposes |
| 433 | `cmd2_subcommand_func`. A `cmd2_subcommand_func` parameter is only valid on a command decorated |
| 434 | with `base_command=True`; declaring one elsewhere raises `TypeError`. |
| 435 | - `subcommand_required` -- whether a subcommand must be supplied (only with `base_command=True`, |
| 436 | default `True`) |
| 437 | - `subcommand_metavar` -- metavar shown for the subcommands group (only with `base_command=True`, |
| 438 | default `"SUBCOMMAND"`) |
| 439 | - `subcommand_title` -- title for the subcommands `--help` section (only with `base_command=True`). |
| 440 | Setting either this or `subcommand_description` moves the subcommands out of the positional |
| 441 | arguments section into a section of their own, as it does in argparse. |
| 442 | - `subcommand_description` -- description for the subcommands `--help` section (only with |
| 443 | `base_command=True`). Supplying this without `subcommand_title` gives that section argparse's |
| 444 | default title, `subcommands`. |
| 445 | - `help` -- help text for an annotated subcommand (only valid with `subcommand_to`) |
| 446 | - `aliases` -- aliases for an annotated subcommand (only valid with `subcommand_to`) |
| 447 | - `deprecated` -- mark the subcommand as deprecated in `--help` (only valid with `subcommand_to`) |
| 448 | - `groups` -- `Group` instances assigning argument names to argument groups |
| 449 | - `mutually_exclusive_groups` -- `Group` instances of mutually exclusive arguments |
| 450 | - `parser_class` -- a custom parser class (defaults to the configured default) |
| 451 | - `**parser_kwargs` -- every other `Cmd2ArgumentParser` constructor kwarg, forwarded through PEP 692 |
| 452 | [`Unpack[Cmd2ParserKwargs]`][cmd2.annotated.Cmd2ParserKwargs]. See |
| 453 | [Parser customization](#parser-customization) below for the full list and the `description` / |
| 454 | `prog` special cases. |
| 455 | |
| 456 | ```py |
| 457 | @with_annotated(with_unknown_args=True) |
| 458 | def do_rawish(self, name: str, _unknown: list[str] | None = None): |
| 459 | self.poutput((name, _unknown)) |
| 460 | ``` |
| 461 | |
| 462 | ## Parser customization |
| 463 | |
| 464 | Every `Cmd2ArgumentParser` constructor kwarg flows straight through `@with_annotated` and |
| 465 | `build_parser_from_function` via PEP 692 |
| 466 | [`Unpack[Cmd2ParserKwargs]`][cmd2.annotated.Cmd2ParserKwargs]. The |
| 467 | [`Cmd2ParserKwargs`][cmd2.annotated.Cmd2ParserKwargs] `TypedDict` is the single source of truth for |
| 468 | the forwarded kwargs and gives type-checkers/IDEs autocomplete on the decorator's call site: adding |
| 469 | a new ctor kwarg to `Cmd2ArgumentParser` only needs a matching field on `Cmd2ParserKwargs`, and the |
| 470 | annotated decorator picks it up automatically. |
| 471 | |
| 472 | The forwarded kwargs are `description`, `epilog`, `prog`, `usage`, `parents`, `argument_default`, |
| 473 | `prefix_chars`, `fromfile_prefix_chars`, `conflict_handler`, `add_help`, `allow_abbrev`, |
| 474 | `exit_on_error`, `formatter_class`, `completer_class`, and on Python ≥ 3.14 `suggest_on_error` / |
| 475 | `color`. Two of them layer extra behavior on top of the raw passthrough: |
| 476 | |
| 477 | - `description` -- when omitted, it is filled from the function's docstring (detailed below); pass |
| 478 | an explicit value to override. |
| 479 | - `prog` -- rejected when `subcommand_to` is set; cmd2's subcommand machinery rewrites `prog` from |
| 480 | the parent command hierarchy, so any value here would be silently overwritten. |
| 481 | |
| 482 | `parser_class` stays as its own explicit kwarg because it selects the class itself rather than a |
| 483 | value passed to it. Argument groups are declared with [Group][cmd2.annotated.Group]; pass `title` |
| 484 | and `description` for a titled help section (omit them for an untitled group): |
| 485 | |
| 486 | ```py |
| 487 | from cmd2.annotated import Group, with_annotated |
| 488 | |
| 489 | class App(cmd2.Cmd): |
| 490 | @with_annotated( |
| 491 | description="Open a network connection.", |
| 492 | epilog="Example: connect example.com --port 2222", |
| 493 | groups=(Group("host", "port", title="connection", description="where to connect"),), |
| 494 | ) |
| 495 | def do_connect(self, host: str, port: int = 22, verbose: bool = False): |
| 496 | self.poutput(f"connecting to {host}:{port}") |
| 497 | ``` |
| 498 | |
| 499 | If you omit `description`, the first paragraph of the function's docstring (everything up to the |
| 500 | first blank line) is used as the parser description; subsequent paragraphs are dropped so rst field |
| 501 | directives like `:param name:` don't leak into `--help`. Pass `description=""` to suppress the |
| 502 | automatic fill, or `description="..."` to override it. |
| 503 | |
| 504 | ```py |
| 505 | @with_annotated |
| 506 | def do_greet(self, name: str): |
| 507 | """Greet someone by name. |
| 508 | |
| 509 | :param name: who to greet |
| 510 | """ |
| 511 | self.poutput(f"hello {name}") |
| 512 | # parser.description == "Greet someone by name." |
| 513 | ``` |
| 514 | |
| 515 | `mutually_exclusive_groups` also takes `Group` instances. Pass `Group(..., required=True)` to make |
| 516 | the mutex group itself required -- argparse will then enforce that exactly one of its members must |
| 517 | be supplied. `required=True` is rejected on a plain (non-mutex) `Group` because `add_argument_group` |
| 518 | has no `required` flag. |
| 519 | |
| 520 | ```py |
| 521 | @with_annotated( |
| 522 | mutually_exclusive_groups=(Group("verbose", "quiet", required=True),), |
| 523 | ) |
| 524 | def do_run(self, verbose: bool = False, quiet: bool = False): ... |
| 525 | ``` |
| 526 | |
| 527 | Give a `mutually_exclusive_groups` `Group` a `title`/`description` to render it as a titled help |
| 528 | section -- argparse's one supported nesting, a mutex _inside_ an argument group. You declare it |
| 529 | once, with no paired `groups=` entry. Use `Option(action="store_true")` on each `bool` member so the |
| 530 | choice reads as `[--json | --csv]` instead of expanding to `--json`/`--no-json` and |
| 531 | `--csv`/`--no-csv`: |
| 532 | |
| 533 | ```py |
| 534 | @with_annotated( |
| 535 | mutually_exclusive_groups=( |
| 536 | Group("json", "csv", title="output", description="how to write results"), |
| 537 | ), |
| 538 | ) |
| 539 | def do_render( |
| 540 | self, |
| 541 | json: Annotated[bool, Option(action="store_true")] = False, |
| 542 | csv: Annotated[bool, Option(action="store_true")] = False, |
| 543 | ): ... |
| 544 | ``` |
| 545 | |
| 546 | To put non-mutex parameters in the same section, declare a `groups=` entry with all of them and |
| 547 | leave the title off the mutex; argparse nests the mutex inside that group. Declaring the section in |
| 548 | both places, a mutex that sits only partly in a `groups=` entry, or one that spans two of them, each |
| 549 | raises `ValueError`. The other three nestings (an argument group inside another group or a mutex, or |
| 550 | a mutex inside a mutex) are removed in argparse on Python 3.14 and cannot be expressed here. |
| 551 | |
| 552 | A `Group` member names a command-line **argument**. For a plain parameter the argument is the |
| 553 | parameter, so the name is the same either way. An `ArgumentBlock` parameter is different: it is |
| 554 | expanded into one argument per field (field name == argument name), so you name its fields rather |
| 555 | than the block: |
| 556 | |
| 557 | ```python |
| 558 | @dataclass |
| 559 | class Conn(ArgumentBlock): |
| 560 | host: Annotated[str, Option("--host")] = "localhost" |
| 561 | port: Annotated[int, Option("--port")] = 8080 |
| 562 | |
| 563 | @with_annotated(groups=(Group("host", "port", title="connection"),)) |
| 564 | def do_connect(self, conn: Conn) -> None: ... |
| 565 | ``` |
| 566 | |
| 567 | Naming the block parameter itself (`Group("conn")`) raises `ValueError`: the parameter is expanded |
| 568 | away and has no argument of its own. Naming a block's fields individually is also what lets you say |
| 569 | which fields are alternatives -- put `Group("json", "csv")` in `mutually_exclusive_groups` and only |
| 570 | those two exclude each other, rather than every field of the block they happen to live in. |
| 571 | |
| 572 | The group-spec **shape** rules -- a member listed twice, a member assigned to two groups, |
| 573 | `required=True` on a plain group, and the mutex nesting rules above -- are validated when the |
| 574 | decorator runs, so a misshapen group raises `ValueError` at class definition time instead of on |
| 575 | first command use. Those checks read only the `Group` specs, never the signature or the type hints, |
| 576 | so forward-referenced annotations still decorate cleanly. |
| 577 | |
| 578 | The rules that depend on what a member _is_ fire when the parser is built, because a block's field |
| 579 | names cannot be known without resolving its type hint: that every member names a real argument, and |
| 580 | that a member of a mutually exclusive group is omittable (has a default or is `T | None`). |
| 581 | |
| 582 | `parents=` mirrors argparse's standard parents mechanism for sharing argument definitions across |
| 583 | parsers. `argument_default=argparse.SUPPRESS` is not supported and raises `TypeError`. It removes an |
| 584 | absent argument from the parsed namespace, but `@with_annotated` builds the call from the function |
| 585 | signature, so every declared parameter is expected at invocation; an argument vanishing from the |
| 586 | namespace can never be valid here (mirroring the per-argument `default=argparse.SUPPRESS` |
| 587 | rejection). Any other `argument_default` value is forwarded to the parser unchanged. |
| 588 | |
| 589 | The remaining argparse kwargs cover less-common needs but are wired through unchanged: |
| 590 | |
| 591 | - `prefix_chars="+-"` accepts options that start with `+` (e.g. `+verbose`); pair with an explicit |
| 592 | `Option("+verbose")` to declare such flags. |
| 593 | - `fromfile_prefix_chars="@"` lets a user write `mycmd @args.txt` and have the file's contents |
| 594 | spliced in as arguments. |
| 595 | - `conflict_handler="resolve"` lets a parent parser's option be redefined locally without an error |
| 596 | -- useful with `parents=` when you want to override an inherited flag. |
| 597 | - `add_help=False` drops the auto-added `-h`/`--help` action (cmd2's standard parser keeps it on by |
| 598 | default). |
| 599 | - `allow_abbrev=False` requires users to type the full long-option name (no `--verb` for |
| 600 | `--verbose`). |
| 601 | - `exit_on_error=False` makes parse failures raise `argparse.ArgumentError` instead of calling |
| 602 | `sys.exit`; useful when embedding the parser inside another flow. |
| 603 | |
| 604 | ## Annotated subcommands |
| 605 | |
| 606 | `@with_annotated` can also build typed subcommand trees without manually constructing subparsers. |
| 607 | |
| 608 | ```py |
| 609 | @with_annotated(base_command=True) |
| 610 | def do_manage(self, *, cmd2_subcommand_func): |
| 611 | if cmd2_subcommand_func: |
| 612 | cmd2_subcommand_func() |
| 613 | |
| 614 | @with_annotated(subcommand_to="manage", help="list projects") |
| 615 | def manage_list(self): |
| 616 | self.poutput("listing") |
| 617 | ``` |
| 618 | |
| 619 | For nested subcommands, `subcommand_to` can be space-delimited, for example |
| 620 | `subcommand_to="manage project"`. The intermediate level must also be declared as a subcommand that |
| 621 | creates its own subparsers: |
| 622 | |
| 623 | ```py |
| 624 | @with_annotated(subcommand_to="manage", base_command=True, help="manage projects") |
| 625 | def manage_project(self, *, cmd2_subcommand_func): |
| 626 | if cmd2_subcommand_func: |
| 627 | cmd2_subcommand_func() |
| 628 | |
| 629 | @with_annotated(subcommand_to="manage project", help="add a project") |
| 630 | def manage_project_add(self, name: str): |
| 631 | self.poutput(f"added {name}") |
| 632 | ``` |
| 633 | |
| 634 | ## Argument blocks |
| 635 | |
| 636 | When several commands share the same group of arguments, a reusable _argument block_ removes the |
| 637 | duplication. Subclass the `cmd2.ArgumentBlock` trait on a `@dataclass` and annotate a parameter with |
| 638 | it. Each field becomes a flat command-line argument (field name == argument name), and the parsed |
| 639 | values are reconstructed into an instance of the dataclass that is passed to the command: |
| 640 | |
| 641 | ```py |
| 642 | from dataclasses import dataclass |
| 643 | from typing import Annotated |
| 644 | from pathlib import Path |
| 645 | |
| 646 | import cmd2 |
| 647 | from cmd2 import with_annotated |
| 648 | from cmd2.annotated import Option |
| 649 | |
| 650 | |
| 651 | @dataclass |
| 652 | class CommonArgs(cmd2.ArgumentBlock): |
| 653 | verbose: Annotated[bool, Option("-v", "--verbose")] = False |
| 654 | output: Annotated[Path | None, Option("--output")] = None |
| 655 | |
| 656 | |
| 657 | class App(cmd2.Cmd): |
| 658 | @with_annotated |
| 659 | def do_build(self, target: str, common: CommonArgs): |
| 660 | self.poutput(f"{target} verbose={common.verbose} output={common.output}") |
| 661 | ``` |
| 662 | |
| 663 | `build app --verbose --output /tmp/x` reconstructs `CommonArgs(verbose=True, output=Path("/tmp/x"))` |
| 664 | and passes it as `common`. The block parameter itself is never an argument, only its fields are. |
| 665 | |
| 666 | A field carries the usual `Annotated[T, Option(...)]` / `Annotated[T, Argument(...)]` metadata and |
| 667 | behaves exactly as a top-level parameter of the same shape would. The dataclass is the single source |
| 668 | of truth for defaults: a field with a default (`default` or `default_factory`) is filled by the |
| 669 | dataclass constructor at call time, so `default_factory` yields a fresh value per invocation and |
| 670 | `__post_init__` runs. A field with no default becomes a required argument. |
| 671 | |
| 672 | Inheritance is the reuse mechanism: a subclass of a block is itself a block, so a shared base block |
| 673 | can be extended per command without repeating its fields. |
| 674 | |
| 675 | ```py |
| 676 | @dataclass |
| 677 | class TracedArgs(CommonArgs): |
| 678 | trace: bool = False # do_test gets verbose, output, and trace |
| 679 | ``` |
| 680 | |
| 681 | A few rules keep blocks unambiguous: |
| 682 | |
| 683 | - The `ArgumentBlock` trait, not "is a dataclass", is the trigger. A plain `@dataclass` is left |
| 684 | alone and can still be used as an ordinary single value (for example via |
| 685 | `Argument(converter=...)`). |
| 686 | - A block must be the _bare_ annotation of a regular parameter. Wrapping it in |
| 687 | `Annotated`/`Optional`/a union, or using it as `*args`/`**kwargs`, raises a clear error. |
| 688 | - Because fields expand flat, a field name that collides with another parameter or another block's |
| 689 | field raises an error when the parser is built, rather than silently sharing a destination. |
| 690 | - A field name that matches the block parameter itself (e.g. `opts` on a block received as |
| 691 | `opts: Opts`) is rejected: the field's flat argument and the parameter that receives the block |
| 692 | instance would share one destination. |
| 693 | - A field's default must live on the dataclass field (`= value` or `= field(default_factory=...)`), |
| 694 | not in the `Option`/`Argument` metadata or via an action default (`append`/`count`). The dataclass |
| 695 | owns defaults so each call gets a fresh value, so a metadata- or action-supplied default on a |
| 696 | field that has no dataclass default is rejected. |
| 697 | - A field whose type is itself a block is not expanded (no recursion); it is rejected as an |
| 698 | unsupported type. |
| 699 | |
| 700 | ### Sharing a block with subcommands (`cmd2_base_args` / `cmd2_parent_args`) |
| 701 | |
| 702 | A base command and its subcommands parse into one shared namespace. To share a block down the chain, |
| 703 | name the parameter `cmd2_base_args` on the command that owns the flags and `cmd2_parent_args` on |
| 704 | each subcommand that should receive it, annotating both with the same block type: |
| 705 | |
| 706 | ```py |
| 707 | @dataclass |
| 708 | class SharedOpts(cmd2.ArgumentBlock): |
| 709 | verbose: Annotated[bool, Option("-v", "--verbose")] = False |
| 710 | level: Annotated[int, Option("--level")] = 1 |
| 711 | |
| 712 | |
| 713 | class App(cmd2.Cmd): |
| 714 | @with_annotated(base_command=True) |
| 715 | def do_root(self, cmd2_subcommand_func, cmd2_base_args: SharedOpts): |
| 716 | if cmd2_subcommand_func: |
| 717 | cmd2_subcommand_func() |
| 718 | |
| 719 | @with_annotated(subcommand_to="root", help="show the inherited block") |
| 720 | def root_show(self, cmd2_parent_args: SharedOpts): |
| 721 | self.poutput(f"verbose={cmd2_parent_args.verbose} level={cmd2_parent_args.level}") |
| 722 | ``` |
| 723 | |
| 724 | `root --verbose --level 5 show` prints `verbose=True level=5`: the options parsed on `root` flow |
| 725 | into the subcommand in a typed way without being redeclared. `cmd2_base_args` adds the block's flags |
| 726 | to its own command's parser, while `cmd2_parent_args` adds _no_ arguments and is reconstructed from |
| 727 | the values an ancestor parsed (`root --verbose show`, not `root show --verbose`). A |
| 728 | `cmd2_parent_args` subcommand whose ancestors never declare a matching `cmd2_base_args` raises a |
| 729 | clear error the first time it runs. This is the typed alternative to forwarding parent-level state |
| 730 | through `ns_provider`. |
| 731 | |
| 732 | Each shared block field parses into a destination qualified by its block type, so two |
| 733 | `cmd2_base_args` blocks of different types at different levels of one chain can use the same field |
| 734 | name without colliding. An inherited block always receives its own type's value, regardless of what |
| 735 | a same-named field on another block at an intervening level parsed. Reusing the same block type at |
| 736 | two levels shares one destination, so the nearest level that sets the flag wins. |
| 737 | |
| 738 | A subcommand can also declare its own regular block alongside the inherited one. The two are |
| 739 | independent: the inherited block's flags are supplied on the parent, while the subcommand's own |
| 740 | block adds its flags to the subcommand's parser. |
| 741 | |
| 742 | ```py |
| 743 | @dataclass |
| 744 | class RunOpts(cmd2.ArgumentBlock): |
| 745 | retries: Annotated[int, Option("--retries")] = 0 |
| 746 | |
| 747 | |
| 748 | class App(cmd2.Cmd): |
| 749 | @with_annotated(base_command=True) |
| 750 | def do_root(self, cmd2_subcommand_func, cmd2_base_args: SharedOpts): |
| 751 | if cmd2_subcommand_func: |
| 752 | cmd2_subcommand_func() |
| 753 | |
| 754 | @with_annotated(subcommand_to="root") |
| 755 | def root_run(self, name: str, cmd2_parent_args: SharedOpts, run: RunOpts): |
| 756 | # --verbose/--level come from `root`; --retries is this subcommand's own flag |
| 757 | self.poutput(f"run {name} verbose={cmd2_parent_args.verbose} retries={run.retries}") |
| 758 | ``` |
| 759 | |
| 760 | `root --verbose run job --retries 3` parses `--verbose` on `root` and `--retries` on `run`. |
| 761 | |
| 762 | ## Lower-level parser building |
| 763 | |
| 764 | [cmd2.annotated.build_parser_from_function][cmd2.annotated.build_parser_from_function] builds the |
| 765 | parser directly from a function without registering a command. It accepts the same `groups`, |
| 766 | `mutually_exclusive_groups`, `parser_class`, and forwarded |
| 767 | [`Unpack[Cmd2ParserKwargs]`][cmd2.annotated.Cmd2ParserKwargs] as `@with_annotated`. Like the |
| 768 | decorator, it skips the first parameter as the method receiver (`self`/`cls`). |
| 769 | |
| 770 | ```py |
| 771 | from cmd2.annotated import build_parser_from_function |
| 772 | |
| 773 | def greet(self, name: str, count: int = 1): |
| 774 | """Greet someone.""" |
| 775 | |
| 776 | parser = build_parser_from_function(greet) |
| 777 | namespace = parser.parse_args(["Alice", "--count", "3"]) |
| 778 | # namespace.name == "Alice", namespace.count == 3 |
| 779 | ``` |
| 780 | |
| 781 | ## Automatic completion from types |
| 782 | |
| 783 | With `@with_annotated`, arguments annotated as `Path` or `Enum` get automatic completion without |
| 784 | needing an explicit `choices_provider` or `completer`. |
| 785 | |
| 786 | Specifically: |
| 787 | |
| 788 | - `Path` (or any `Path` subclass) triggers filesystem path completion |
| 789 | - `MyEnum` (any `enum.Enum` subclass) triggers completion from enum member values |
| 790 | |
| 791 | With `@with_argparser`, provide `choices`, `choices_provider`, or `completer` explicitly when you |
| 792 | want completion behavior. |
| 793 | |
| 794 | ## Stability and feedback |
| 795 | |
| 796 | Because this feature is experimental: |
| 797 | |
| 798 | - Behavior of edge cases (mixed-type tuples, deeply-nested `Annotated`, conflicting metadata) may |
| 799 | change. |
| 800 | - Diagnostic error messages may be reworded. |
| 801 | - The set of supported type annotations may be expanded or trimmed. |
| 802 | |
| 803 | If you depend on `@with_annotated`, please share feedback and edge cases via the |
| 804 | [issue tracker](https://github.com/python-cmd2/cmd2/issues) so behavior can be locked in before the |
| 805 | feature graduates out of experimental. |