From 9aac81b249db98b2ee8607887b71d3b3fb835d84 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:49:52 -0500 Subject: [PATCH 1/4] Make a command's argparse spec public as Cmd.get_argparse_command_spec() @with_argparser and @with_annotated record an ArgparseCommandSpec on the command function: the source of its parser, and whether argparse is given the command's arguments with their quotes. It was readable only through a private attribute. Code which describes an application's commands, as the MCP server example in #1855 does, needs preserve_quotes to say how a subcommand is typed. - Cmd.get_argparse_command_spec(func) returns the spec, or None for a command which neither decorator made. A disabled command's stand-in carries its spec. - CommandParsers.get() and argparse completion use it in place of the private attribute. - docs/features/argument_processing.md shows how to ask, and CHANGELOG.md has an entry under 4.5.0. --- CHANGELOG.md | 3 ++ cmd2/cmd2.py | 24 ++++++++++-- docs/features/argument_processing.md | 13 +++++++ tests/test_argparse.py | 58 ++++++++++++++++++++++++++++ 4 files changed, 95 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4cb3d289a..df7b78884 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ - Enhancements - Added `Cmd.get_command_category()`, which returns the help category a command is listed under. It was the private `_get_command_category()`. + - Added `Cmd.get_argparse_command_spec()`, which returns what `@with_argparser` or + `@with_annotated` recorded for a command: the source of its parser, and whether argparse is + given its arguments with their quotes. ## 4.4.5 (2026-12-02) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 6d870a5b7..efa4714a4 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -297,7 +297,7 @@ def get(self, command_method: BoundCommandFunc[...]) -> Cmd2ArgumentParser | Non return None command = command_method.__name__[len(COMMAND_FUNC_PREFIX) :] - spec: ArgparseCommandSpec | None = getattr(command_method, constants.ARGPARSE_COMMAND_ATTR_SPEC, None) + spec = self._cmd_app.get_argparse_command_spec(command_method) if spec is None: return None @@ -2690,14 +2690,15 @@ def _perform_completion( if command_func is not None and parser is not None: # Get arguments for complete() - spec: ArgparseCommandSpec = getattr(command_func, constants.ARGPARSE_COMMAND_ATTR_SPEC) + spec = self.get_argparse_command_spec(command_func) + preserve_quotes = spec is not None and spec.preserve_quotes cmd_set = self.find_commandset_for_command(command) # Create the argparse completer completer = parser.completer_class(parser, self) completer_func = functools.partial( - completer.complete, tokens=raw_tokens[1:] if spec.preserve_quotes else tokens[1:], cmd_set=cmd_set + completer.complete, tokens=raw_tokens[1:] if preserve_quotes else tokens[1:], cmd_set=cmd_set ) else: completer_func = self.completedefault # type: ignore[assignment] # ty: ignore[invalid-assignment] @@ -3676,6 +3677,23 @@ def get_command_category(self, func: BoundCommandFunc[...]) -> str: return category + def get_argparse_command_spec(self, func: BoundCommandFunc[...]) -> ArgparseCommandSpec | None: + """Return the spec which an argparse decorator recorded for a command. + + [@with_argparser][cmd2.with_argparser] and [@with_annotated][cmd2.with_annotated] record + the source of the command's parser and whether argparse is given the command's arguments + with their quotes (``preserve_quotes``). The parser which the command uses is + ``self.command_parsers.get(func)``. + + :param func: the bound ``do_*`` method of the command, as returned by + [get_command_func()][cmd2.Cmd.get_command_func]. While a command is disabled, + the function which stands in for it carries its spec. + :return: the command's spec, or None for a command which neither decorator made, such as one + made with [@with_argument_list][cmd2.with_argument_list] + """ + spec: ArgparseCommandSpec | None = getattr(func, constants.ARGPARSE_COMMAND_ATTR_SPEC, None) + return spec + def onecmd(self, statement: Statement | str, *, add_to_history: bool = True) -> bool: """Execute the actual do_* method for a command. diff --git a/docs/features/argument_processing.md b/docs/features/argument_processing.md index 6992dbae4..1f6b69fa8 100644 --- a/docs/features/argument_processing.md +++ b/docs/features/argument_processing.md @@ -37,6 +37,19 @@ All of these decorators accept an optional **preserve_quotes** argument which de Setting this argument to `True` is useful for cases where you are passing the arguments to another command which might have its own argument parsing. +For a command made with `@with_argparser` or `@with_annotated`, +[get_argparse_command_spec()][cmd2.Cmd.get_argparse_command_spec] returns what the decorator +recorded, so code which describes an application's commands can ask whether argparse is given a +command's arguments with their quotes. Get the command's function from +[get_command_func()][cmd2.Cmd.get_command_func], and skip a name for which there is none: + +```py +func = self.get_command_func(name) +if func is not None: + spec = self.get_argparse_command_spec(func) + keeps_quotes = spec is not None and spec.preserve_quotes +``` + ## with_argparser decorator The [@with_argparser][cmd2.with_argparser] decorator can accept the following for its first diff --git a/tests/test_argparse.py b/tests/test_argparse.py index d94a2fadb..543bbbe88 100644 --- a/tests/test_argparse.py +++ b/tests/test_argparse.py @@ -5,6 +5,7 @@ import pytest import cmd2 +from cmd2.argparse_utils import ArgparseCommandSpec from .conftest import ( run_cmd, @@ -518,3 +519,60 @@ def test_pytest_mock_invalid(mocker) -> None: def test_pytest_mock_valid(mocker, spec_param) -> None: mocker.patch.object(ArgparseApp, "namespace_provider", **spec_param) ArgparseApp() + + +def _spec(app: cmd2.Cmd, command: str) -> ArgparseCommandSpec | None: + func = app.get_command_func(command) + assert func is not None + return app.get_argparse_command_spec(func) + + +def test_get_argparse_command_spec_says_whether_argparse_gets_the_quotes(argparse_app) -> None: + tag = _spec(argparse_app, "tag") + assert tag is not None + assert tag.preserve_quotes + assert tag.parser_source is ArgparseApp.tag_parser + say = _spec(argparse_app, "say") + assert say is not None + assert not say.preserve_quotes + + +def test_get_argparse_command_spec_of_an_annotated_command() -> None: + class AnnotatedApp(cmd2.Cmd): + @cmd2.with_annotated(preserve_quotes=True) + def do_keep(self, word: str) -> None: + self.poutput(word) + + spec = _spec(AnnotatedApp(), "keep") + assert spec is not None + assert spec.preserve_quotes + + +def test_get_argparse_command_spec_of_a_command_set_command() -> None: + class QuotesSet(cmd2.CommandSet): + @cmd2.with_argparser(cmd2.Cmd2ArgumentParser(), preserve_quotes=True) + def do_kept(self, _: argparse.Namespace) -> None: + pass + + spec = _spec(cmd2.Cmd(command_sets=[QuotesSet()]), "kept") + assert spec is not None + assert spec.preserve_quotes + + +def test_get_argparse_command_spec_of_a_disabled_command(argparse_app) -> None: + argparse_app.disable_command("tag", "tag is disabled") + spec = _spec(argparse_app, "tag") + assert spec is not None + assert spec.preserve_quotes + + +def test_get_argparse_command_spec_of_a_command_without_a_parser(argparse_app) -> None: + # @with_argument_list takes preserve_quotes too, but makes no parser and records no spec. + assert _spec(argparse_app, "preservelist") is None + assert _spec(argparse_app, "arglist") is None + + class PlainApp(cmd2.Cmd): + def do_plain(self, statement: cmd2.Statement) -> None: + self.poutput(statement.args) + + assert _spec(PlainApp(), "plain") is None From daa6c79fc837745c64c3b44f5352ac574427c660 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:01:14 -0500 Subject: [PATCH 2/4] Freeze ArgparseCommandSpec, and give get_argparse_command_spec() only bound methods - ArgparseCommandSpec is frozen. Through the getter, one application could change the spec which every application shares, so that it and completion reported what the command did not do. - CommandParsers.get() reads the spec directly again. The argparse decorators pass it their own function, which is not bound, and the public accessor takes a bound method; calling it from there also called an override of it during Cmd.__init__(). --- CHANGELOG.md | 3 ++- cmd2/argparse_utils.py | 2 +- cmd2/cmd2.py | 8 +++++--- tests/test_argparse.py | 31 +++++++++++++++++++++++++++++++ 4 files changed, 39 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df7b78884..871a47603 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,8 @@ It was the private `_get_command_category()`. - Added `Cmd.get_argparse_command_spec()`, which returns what `@with_argparser` or `@with_annotated` recorded for a command: the source of its parser, and whether argparse is - given its arguments with their quotes. + given its arguments with their quotes. `ArgparseCommandSpec` is now frozen, so what a + decorator recorded cannot be changed through it. ## 4.4.5 (2026-12-02) diff --git a/cmd2/argparse_utils.py b/cmd2/argparse_utils.py index cb00eeb89..cee16a398 100644 --- a/cmd2/argparse_utils.py +++ b/cmd2/argparse_utils.py @@ -291,7 +291,7 @@ def get_choices(self) -> Choices: ] -@dataclass(kw_only=True) +@dataclass(kw_only=True, frozen=True) class ArgparseCommandSpec: """Metadata for an argparse-based command function. diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index efa4714a4..ab185f824 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -297,7 +297,9 @@ def get(self, command_method: BoundCommandFunc[...]) -> Cmd2ArgumentParser | Non return None command = command_method.__name__[len(COMMAND_FUNC_PREFIX) :] - spec = self._cmd_app.get_argparse_command_spec(command_method) + # The argparse decorators pass their own function here, which is not bound, so the spec is read from it + # directly: Cmd.get_argparse_command_spec() is given only bound methods. + spec: ArgparseCommandSpec | None = getattr(command_method, constants.ARGPARSE_COMMAND_ATTR_SPEC, None) if spec is None: return None @@ -3688,8 +3690,8 @@ def get_argparse_command_spec(self, func: BoundCommandFunc[...]) -> ArgparseComm :param func: the bound ``do_*`` method of the command, as returned by [get_command_func()][cmd2.Cmd.get_command_func]. While a command is disabled, the function which stands in for it carries its spec. - :return: the command's spec, or None for a command which neither decorator made, such as one - made with [@with_argument_list][cmd2.with_argument_list] + :return: the command's spec, which is frozen, or None for a command which neither decorator + made, such as one made with [@with_argument_list][cmd2.with_argument_list] """ spec: ArgparseCommandSpec | None = getattr(func, constants.ARGPARSE_COMMAND_ATTR_SPEC, None) return spec diff --git a/tests/test_argparse.py b/tests/test_argparse.py index 543bbbe88..19b2bcc93 100644 --- a/tests/test_argparse.py +++ b/tests/test_argparse.py @@ -1,6 +1,9 @@ """Cmd2 testing for argument parsing""" import argparse +import dataclasses +import inspect +from typing import Any import pytest @@ -576,3 +579,31 @@ def do_plain(self, statement: cmd2.Statement) -> None: self.poutput(statement.args) assert _spec(PlainApp(), "plain") is None + + +def test_get_argparse_command_spec_cannot_be_changed_through_one_application(argparse_app) -> None: + other = ArgparseApp() + spec = _spec(argparse_app, "tag") + assert spec is not None + with pytest.raises(dataclasses.FrozenInstanceError): + spec.preserve_quotes = False # type: ignore[misc] + other_spec = _spec(other, "tag") + assert other_spec is not None + assert other_spec.preserve_quotes + + +def test_cmd2_gives_get_argparse_command_spec_only_bound_methods() -> None: + class WatchedApp(ArgparseApp): + def __init__(self) -> None: + self.given: list[object] = [] + super().__init__() + + def get_argparse_command_spec(self, func: Any) -> ArgparseCommandSpec | None: + self.given.append(func) + return super().get_argparse_command_spec(func) + + app = WatchedApp() + run_cmd(app, 'tag mytag "hello"') # the first use of the command, which builds its parser + app.complete("", "tag ", 4, 4) + assert app.given + assert all(inspect.ismethod(func) for func in app.given) From 41695f0cf63b193c66b87ae43aa24ece39215da4 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:09:45 -0500 Subject: [PATCH 3/4] Say that a frozen ArgparseCommandSpec still shares its parser source Freezing the spec stops its fields being reassigned, not a change to the parser which @with_argparser was given: that is the spec's parser_source itself, and each application copies it when it builds the command's parser. The changelog entry and the docstring of get_argparse_command_spec() now say so, and send a reader who wants to change one application's parser to self.command_parsers.get(func). --- CHANGELOG.md | 6 ++++-- cmd2/cmd2.py | 10 ++++++---- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 871a47603..8aca4b743 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,10 @@ It was the private `_get_command_category()`. - Added `Cmd.get_argparse_command_spec()`, which returns what `@with_argparser` or `@with_annotated` recorded for a command: the source of its parser, and whether argparse is - given its arguments with their quotes. `ArgparseCommandSpec` is now frozen, so what a - decorator recorded cannot be changed through it. + given its arguments with their quotes. `ArgparseCommandSpec` is now frozen, so its fields + cannot be reassigned. A parser given to `@with_argparser` is the spec's `parser_source` + itself, shared by every application which has not built the command's parser yet: to change + one application's parser, change the one which `self.command_parsers.get(func)` returns. ## 4.4.5 (2026-12-02) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index ab185f824..eb76c4282 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -3684,14 +3684,16 @@ def get_argparse_command_spec(self, func: BoundCommandFunc[...]) -> ArgparseComm [@with_argparser][cmd2.with_argparser] and [@with_annotated][cmd2.with_annotated] record the source of the command's parser and whether argparse is given the command's arguments - with their quotes (``preserve_quotes``). The parser which the command uses is - ``self.command_parsers.get(func)``. + with their quotes (``preserve_quotes``). The spec's fields cannot be reassigned, but its + ``parser_source`` is what the decorator was given, which every application shares. The + parser which this application's command uses is ``self.command_parsers.get(func)``, and is + the one to change. :param func: the bound ``do_*`` method of the command, as returned by [get_command_func()][cmd2.Cmd.get_command_func]. While a command is disabled, the function which stands in for it carries its spec. - :return: the command's spec, which is frozen, or None for a command which neither decorator - made, such as one made with [@with_argument_list][cmd2.with_argument_list] + :return: the command's spec, or None for a command which neither decorator made, such as one + made with [@with_argument_list][cmd2.with_argument_list] """ spec: ArgparseCommandSpec | None = getattr(func, constants.ARGPARSE_COMMAND_ATTR_SPEC, None) return spec From 6904ef92baacf9fa5ca348a12e38a26b50fea41e Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:25:24 -0500 Subject: [PATCH 4/4] Say what parser_source is for each argparse decorator @with_argparser records the parser or factory it was given. @with_annotated records a factory which cmd2 makes from the command's type hints, so its parser_source is not the command's function. The docstring of get_argparse_command_spec() now names each case. --- cmd2/cmd2.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index eb76c4282..e8e473447 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -3684,10 +3684,15 @@ def get_argparse_command_spec(self, func: BoundCommandFunc[...]) -> ArgparseComm [@with_argparser][cmd2.with_argparser] and [@with_annotated][cmd2.with_annotated] record the source of the command's parser and whether argparse is given the command's arguments - with their quotes (``preserve_quotes``). The spec's fields cannot be reassigned, but its - ``parser_source`` is what the decorator was given, which every application shares. The - parser which this application's command uses is ``self.command_parsers.get(func)``, and is - the one to change. + with their quotes (``preserve_quotes``). The spec's fields cannot be reassigned. Its + ``parser_source`` is shared by every application: + + - for ``@with_argparser``, the parser or the factory which the decorator was given + - for ``@with_annotated``, a factory which cmd2 made from the command's type hints, not the + command's function + + The parser which this application's command uses is ``self.command_parsers.get(func)``, and + is the one to change. :param func: the bound ``do_*`` method of the command, as returned by [get_command_func()][cmd2.Cmd.get_command_func]. While a command is disabled,