From 73c6c454a016e92316eeeeea43c29f6ad3fcbd35 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:29:43 -0500 Subject: [PATCH 1/8] Resolve the defining class of unbound nested methods --- CHANGELOG.md | 2 ++ cmd2/utils.py | 8 ++++++-- tests/test_commandset.py | 24 ++++++++++++++++++++++++ tests/test_utils_defining_class.py | 17 +++++++++++++++++ 4 files changed, 49 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b283e489..48af2e759 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ - Tab completion now works when a `choices_provider` or `completer` is a module-level lambda. `get_defining_class()` also handles functions whose module cannot be found and unbound methods of nested classes without raising `AttributeError`. + - Unbound completers defined on a nested `CommandSet` now receive the registered command set as + `self`. Previously, they received the application, which could cause tab completion to fail. - `history /` and `History.regex_search("/")` now return only history entries containing a forward slash. Previously, a lone slash was treated as an empty regex and matched every entry. - Macros now expand `{1}` correctly when it is followed by an escaped `{{1}}`. For example, diff --git a/cmd2/utils.py b/cmd2/utils.py index da1212a58..59dcbc449 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -1589,8 +1589,12 @@ def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: return cls meth = getattr(meth, "__func__", meth) # fallback to __qualname__ parsing if inspect.isfunction(meth): - # The name isn't necessarily in the module, as with a module-level lambda whose __qualname__ is "" - owner = getattr(inspect.getmodule(meth), meth.__qualname__.split(".", 1)[0].rsplit(".", 1)[0], None) + # Outer.Inner.method belongs to Outer.Inner. Only the part before a local scope is reachable from the module. + owner: object = inspect.getmodule(meth) + for name in meth.__qualname__.partition(".")[0].split(".")[:-1]: + if owner is None: + break + owner = getattr(owner, name, None) if isinstance(owner, type): return owner return cast(type, getattr(meth, "__objclass__", None)) # handle special descriptor objects diff --git a/tests/test_commandset.py b/tests/test_commandset.py index 0f6f1747e..36a3bd41f 100644 --- a/tests/test_commandset.py +++ b/tests/test_commandset.py @@ -754,6 +754,30 @@ def test_static_subcommands(static_subcommands_app) -> None: assert completions.to_strings() == Completions.from_values(["diced", "quartered"]).to_strings() +class ColorPlugin: + class Commands(cmd2.CommandSet): + def __init__(self, colors: list[str]) -> None: + super().__init__() + self.colors = colors + + def complete_color(self, text: str, line: str, begidx: int, endidx: int) -> Completions: + return self._cmd.basic_complete(text, line, begidx, endidx, self.colors) + + paint_parser = cmd2.Cmd2ArgumentParser() + paint_parser.add_argument("color", completer=complete_color) + + @cmd2.with_argparser(paint_parser) + def do_paint(self, ns: argparse.Namespace) -> None: + self._cmd.poutput(ns.color) + + +def test_nested_command_set_completer(manual_command_sets_app) -> None: + manual_command_sets_app.register_command_set(ColorPlugin.Commands(["blue", "green"])) + line = "paint " + completions = manual_command_sets_app.complete("", line, len(line), len(line)) + assert completions.to_strings() == ("blue", "green") + + complete_states_expected_self = None diff --git a/tests/test_utils_defining_class.py b/tests/test_utils_defining_class.py index 4f0de6387..fe2cd149b 100644 --- a/tests/test_utils_defining_class.py +++ b/tests/test_utils_defining_class.py @@ -89,3 +89,20 @@ def test_get_defining_class_module_level_lambda() -> None: # A module-level lambda's __qualname__ is "", which isn't an attribute of its module assert cu.get_defining_class(module_level_lambda) is None assert cu.get_defining_class(functools.partial(module_level_lambda)) is None + + +class Outer: + class Inner(ParentClass): + def method(self) -> None: + pass + + +def test_get_defining_class_nested_class() -> None: + assert cu.get_defining_class(Outer.Inner.method) is Outer.Inner + assert cu.get_defining_class(functools.partial(Outer.Inner.method)) is Outer.Inner + assert cu.get_defining_class(Outer.Inner.parent_only_func) is ParentClass + + +def test_get_defining_class_nested_class_in_unknown_module(monkeypatch) -> None: + monkeypatch.setattr(Outer.Inner.method, "__module__", "missing_cmd2_test_module") + assert cu.get_defining_class(Outer.Inner.method) is None From 31ba5d1abfa7b562d4e022d1f8c8462461ecb15c Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:01:16 -0500 Subject: [PATCH 2/8] Keep factory-created callbacks unbound during method lookup Skip qualified-name traversal for local functions so choices providers returned by CommandSet methods receive the application. Cover the nested factory case with a regression test. --- cmd2/utils.py | 6 +++--- tests/test_utils_defining_class.py | 7 +++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/cmd2/utils.py b/cmd2/utils.py index 59dcbc449..d0def5f64 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -1588,10 +1588,10 @@ def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: if meth.__name__ in cls.__dict__: return cls meth = getattr(meth, "__func__", meth) # fallback to __qualname__ parsing - if inspect.isfunction(meth): - # Outer.Inner.method belongs to Outer.Inner. Only the part before a local scope is reachable from the module. + if inspect.isfunction(meth) and ".." not in meth.__qualname__: + # Walk the enclosing classes for a module-reachable method such as Outer.Inner.method. owner: object = inspect.getmodule(meth) - for name in meth.__qualname__.partition(".")[0].split(".")[:-1]: + for name in meth.__qualname__.split(".")[:-1]: if owner is None: break owner = getattr(owner, name, None) diff --git a/tests/test_utils_defining_class.py b/tests/test_utils_defining_class.py index fe2cd149b..1f741e4c4 100644 --- a/tests/test_utils_defining_class.py +++ b/tests/test_utils_defining_class.py @@ -96,6 +96,9 @@ class Inner(ParentClass): def method(self) -> None: pass + def make_choices(self): + return lambda app: app.get_all_commands() + def test_get_defining_class_nested_class() -> None: assert cu.get_defining_class(Outer.Inner.method) is Outer.Inner @@ -103,6 +106,10 @@ def test_get_defining_class_nested_class() -> None: assert cu.get_defining_class(Outer.Inner.parent_only_func) is ParentClass +def test_get_defining_class_factory_callback() -> None: + assert cu.get_defining_class(Outer.Inner().make_choices()) is None + + def test_get_defining_class_nested_class_in_unknown_module(monkeypatch) -> None: monkeypatch.setattr(Outer.Inner.method, "__module__", "missing_cmd2_test_module") assert cu.get_defining_class(Outer.Inner.method) is None From 319f3eabbd7fd9475158bcb533e715ca05a78784 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:27:40 -0500 Subject: [PATCH 3/8] Preserve binding for factory-generated CommandSet methods Check whether the enclosing class stores the exact function returned by a factory. This gives class-assigned choices providers the registered command set while standalone callbacks from the same factory receive the application. --- cmd2/utils.py | 16 ++++++++++++---- tests/test_commandset.py | 13 +++++++++++++ tests/test_utils_defining_class.py | 10 ++++++++-- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/cmd2/utils.py b/cmd2/utils.py index d0def5f64..0e46429f6 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -1588,15 +1588,23 @@ def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: if meth.__name__ in cls.__dict__: return cls meth = getattr(meth, "__func__", meth) # fallback to __qualname__ parsing - if inspect.isfunction(meth) and ".." not in meth.__qualname__: - # Walk the enclosing classes for a module-reachable method such as Outer.Inner.method. + if inspect.isfunction(meth): + # For a local function, the reachable path ends at its enclosing factory. + reachable_name, local_scope, _ = meth.__qualname__.partition("..") owner: object = inspect.getmodule(meth) - for name in meth.__qualname__.split(".")[:-1]: + for name in reachable_name.split(".")[:-1]: if owner is None: break owner = getattr(owner, name, None) if isinstance(owner, type): - return owner + if not local_scope: + return owner + # Two calls to the same factory produce functions with the same qualified name. + # Only the function installed on the class should receive the command set. + for member in vars(owner).values(): + func = member.__func__ if isinstance(member, (staticmethod, classmethod)) else member + if func is meth: + return owner return cast(type, getattr(meth, "__objclass__", None)) # handle special descriptor objects diff --git a/tests/test_commandset.py b/tests/test_commandset.py index 36a3bd41f..414606f8c 100644 --- a/tests/test_commandset.py +++ b/tests/test_commandset.py @@ -763,8 +763,14 @@ def __init__(self, colors: list[str]) -> None: def complete_color(self, text: str, line: str, begidx: int, endidx: int) -> Completions: return self._cmd.basic_complete(text, line, begidx, endidx, self.colors) + @staticmethod + def make_color_choices(): + return lambda cmd_set: Completions.from_values(cmd_set.colors) + + color_choices = make_color_choices() paint_parser = cmd2.Cmd2ArgumentParser() paint_parser.add_argument("color", completer=complete_color) + paint_parser.add_argument("--accent", choices_provider=color_choices) @cmd2.with_argparser(paint_parser) def do_paint(self, ns: argparse.Namespace) -> None: @@ -778,6 +784,13 @@ def test_nested_command_set_completer(manual_command_sets_app) -> None: assert completions.to_strings() == ("blue", "green") +def test_nested_command_set_factory_choices_provider(manual_command_sets_app) -> None: + manual_command_sets_app.register_command_set(ColorPlugin.Commands(["blue", "green"])) + line = "paint blue --accent " + completions = manual_command_sets_app.complete("", line, len(line), len(line)) + assert completions.to_strings() == ("blue", "green") + + complete_states_expected_self = None diff --git a/tests/test_utils_defining_class.py b/tests/test_utils_defining_class.py index 1f741e4c4..db09ac659 100644 --- a/tests/test_utils_defining_class.py +++ b/tests/test_utils_defining_class.py @@ -96,9 +96,13 @@ class Inner(ParentClass): def method(self) -> None: pass - def make_choices(self): + @staticmethod + def make_choices(): return lambda app: app.get_all_commands() + static_choices = staticmethod(make_choices()) + class_choices = classmethod(make_choices()) + def test_get_defining_class_nested_class() -> None: assert cu.get_defining_class(Outer.Inner.method) is Outer.Inner @@ -107,7 +111,9 @@ def test_get_defining_class_nested_class() -> None: def test_get_defining_class_factory_callback() -> None: - assert cu.get_defining_class(Outer.Inner().make_choices()) is None + assert cu.get_defining_class(Outer.Inner.make_choices()) is None + assert cu.get_defining_class(Outer.Inner.static_choices) is Outer.Inner + assert cu.get_defining_class(Outer.Inner.class_choices) is Outer.Inner def test_get_defining_class_nested_class_in_unknown_module(monkeypatch) -> None: From da015240de23dede2a5db1cd120decb14f8a26aa Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:42:18 -0500 Subject: [PATCH 4/8] Resolve factory providers installed on subclasses or as partials Search the factory class hierarchy for the callback and match the underlying function when a parser copies an installed partial. Cover both receiver regressions through tab completion. --- cmd2/utils.py | 40 ++++++++++++++++++++++++------ tests/test_commandset.py | 29 +++++++++++++++++++--- tests/test_utils_defining_class.py | 3 +++ 3 files changed, 60 insertions(+), 12 deletions(-) diff --git a/cmd2/utils.py b/cmd2/utils.py index 0e46429f6..c434b1deb 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -1570,6 +1570,32 @@ def do_echo(self, arglist): setattr(cur_func, constants.COMMAND_ATTR_HELP_CATEGORY, category) +def _factory_method_owner(factory_class: type[Any], func: Callable[..., Any], *, is_partial: bool) -> type[Any] | None: + """Find the class in the factory's hierarchy that installed this particular callback.""" + pending = [factory_class] + visited: set[type[Any]] = set() + owner = None + while pending: + cls = pending.pop() + if cls in visited: + continue + visited.add(cls) + for member in vars(cls).values(): + target = member.__func__ if isinstance(member, (staticmethod, classmethod)) else member + # Parser copies can hold distinct partials around the same function. + while is_partial and isinstance(target, functools.partial): + target = target.func + if target is func: + if cls is factory_class or owner is not None: + # A callback shared by multiple branches can use the factory's receiver type. + return factory_class + owner = cls + break + else: + pending.extend(type.__subclasses__(cls)) + return owner + + def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: """Attempt to resolve the class that defined a method. @@ -1579,8 +1605,9 @@ def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: :param meth: method to inspect :return: class type in which the supplied method was defined. None if it couldn't be resolved. """ - if isinstance(meth, functools.partial): - return get_defining_class(meth.func) + is_partial = isinstance(meth, functools.partial) + while isinstance(meth, functools.partial): + meth = meth.func if inspect.ismethod(meth) or ( inspect.isbuiltin(meth) and hasattr(meth, "__self__") and hasattr(meth.__self__, "__class__") ): @@ -1599,12 +1626,9 @@ def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: if isinstance(owner, type): if not local_scope: return owner - # Two calls to the same factory produce functions with the same qualified name. - # Only the function installed on the class should receive the command set. - for member in vars(owner).values(): - func = member.__func__ if isinstance(member, (staticmethod, classmethod)) else member - if func is meth: - return owner + factory_owner = _factory_method_owner(owner, meth, is_partial=is_partial) + if factory_owner is not None: + return factory_owner return cast(type, getattr(meth, "__objclass__", None)) # handle special descriptor objects diff --git a/tests/test_commandset.py b/tests/test_commandset.py index 414606f8c..9305f6a29 100644 --- a/tests/test_commandset.py +++ b/tests/test_commandset.py @@ -1,6 +1,7 @@ """Test CommandSet""" import argparse +import functools import signal import pytest @@ -765,12 +766,14 @@ def complete_color(self, text: str, line: str, begidx: int, endidx: int) -> Comp @staticmethod def make_color_choices(): - return lambda cmd_set: Completions.from_values(cmd_set.colors) + return lambda cmd_set, limit=None: Completions.from_values(cmd_set.colors[:limit]) color_choices = make_color_choices() + first_color = functools.partial(make_color_choices(), limit=1) paint_parser = cmd2.Cmd2ArgumentParser() paint_parser.add_argument("color", completer=complete_color) paint_parser.add_argument("--accent", choices_provider=color_choices) + paint_parser.add_argument("--first", choices_provider=first_color) @cmd2.with_argparser(paint_parser) def do_paint(self, ns: argparse.Namespace) -> None: @@ -784,11 +787,29 @@ def test_nested_command_set_completer(manual_command_sets_app) -> None: assert completions.to_strings() == ("blue", "green") -def test_nested_command_set_factory_choices_provider(manual_command_sets_app) -> None: +@pytest.mark.parametrize(("option", "expected"), [("--accent", ("blue", "green")), ("--first", ("blue",))]) +def test_nested_command_set_factory_choices_provider(manual_command_sets_app, option, expected) -> None: manual_command_sets_app.register_command_set(ColorPlugin.Commands(["blue", "green"])) - line = "paint blue --accent " + line = f"paint blue {option} " completions = manual_command_sets_app.complete("", line, len(line), len(line)) - assert completions.to_strings() == ("blue", "green") + assert completions.to_strings() == expected + + +class PaletteCommands(ColorPlugin.Commands): + palette_choices = ColorPlugin.Commands.make_color_choices() + palette_parser = cmd2.Cmd2ArgumentParser() + palette_parser.add_argument("color", choices_provider=palette_choices) + + @cmd2.with_argparser(palette_parser) + def do_palette(self, ns: argparse.Namespace) -> None: + self._cmd.poutput(ns.color) + + +def test_subclass_installed_factory_choices_provider(manual_command_sets_app) -> None: + manual_command_sets_app.register_command_set(PaletteCommands(["red", "yellow"])) + line = "palette " + completions = manual_command_sets_app.complete("", line, len(line), len(line)) + assert completions.to_strings() == ("red", "yellow") complete_states_expected_self = None diff --git a/tests/test_utils_defining_class.py b/tests/test_utils_defining_class.py index db09ac659..7a5e1e78b 100644 --- a/tests/test_utils_defining_class.py +++ b/tests/test_utils_defining_class.py @@ -102,6 +102,7 @@ def make_choices(): static_choices = staticmethod(make_choices()) class_choices = classmethod(make_choices()) + partial_choices = functools.partial(make_choices()) def test_get_defining_class_nested_class() -> None: @@ -114,6 +115,8 @@ def test_get_defining_class_factory_callback() -> None: assert cu.get_defining_class(Outer.Inner.make_choices()) is None assert cu.get_defining_class(Outer.Inner.static_choices) is Outer.Inner assert cu.get_defining_class(Outer.Inner.class_choices) is Outer.Inner + assert cu.get_defining_class(Outer.Inner.partial_choices) is Outer.Inner + assert cu.get_defining_class(Outer.Inner.partial_choices.func) is None def test_get_defining_class_nested_class_in_unknown_module(monkeypatch) -> None: From 14bb41966a5951cef9ccdfa90e42d3b6f4fec495 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:04:09 -0500 Subject: [PATCH 5/8] Resolve factory callbacks against their actual CommandSet owners Keep the original partial identity for receiver lookup when argparse copies a parser. Resolve shared providers using the command receiver and registered instances, and visit factory subclasses by identity so unhashable metaclasses work. --- cmd2/argparse_completer.py | 9 ++++- cmd2/argparse_utils.py | 17 +++++++-- cmd2/cmd2.py | 48 +++++++------------------ cmd2/utils.py | 54 ++++++++++++++-------------- tests/test_commandset.py | 58 +++++++++++++++++++++++++++++- tests/test_utils_defining_class.py | 49 +++++++++++++++++++++++++ 6 files changed, 168 insertions(+), 67 deletions(-) diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py index 7644acaf1..a7abd940f 100644 --- a/cmd2/argparse_completer.py +++ b/cmd2/argparse_completer.py @@ -23,6 +23,8 @@ from rich.text import Text from .argparse_utils import ( + _CHOICES_PROVIDER_SOURCE, + _COMPLETER_SOURCE, Cmd2ArgumentParser, build_range_error, ) @@ -719,6 +721,7 @@ def _choices_to_items(self, arg_state: _ArgumentState) -> list[CompletionItem]: def _prepare_callable_params( self, to_call: UnboundChoicesProvider[CmdOrSetT] | UnboundCompleter[CmdOrSetT], + source_attr: str, arg_state: _ArgumentState, text: str, consumed_arg_values: dict[str, list[str]], @@ -729,7 +732,9 @@ def _prepare_callable_params( kwargs: dict[str, Any] = {} # Resolve the 'self' instance for the method - self_arg = self._cmd_app._resolve_func_self(to_call, cmd_set) + source_ref = getattr(arg_state.action, source_attr, None) + original = source_ref() if source_ref is not None else None + self_arg = self._cmd_app._resolve_func_self(original if original is not None else to_call, cmd_set) if self_arg is None: raise CompletionError("Could not find CommandSet instance matching defining type") @@ -765,6 +770,7 @@ def _complete_arg( if completer is not None: args, kwargs = self._prepare_callable_params( completer, + _COMPLETER_SOURCE, arg_state, text, consumed_arg_values, @@ -779,6 +785,7 @@ def _complete_arg( if choices_provider is not None: args, kwargs = self._prepare_callable_params( choices_provider, + _CHOICES_PROVIDER_SOURCE, arg_state, text, consumed_arg_values, diff --git a/cmd2/argparse_utils.py b/cmd2/argparse_utils.py index cee16a398..f9c26b054 100644 --- a/cmd2/argparse_utils.py +++ b/cmd2/argparse_utils.py @@ -226,9 +226,11 @@ def get_choices(self) -> Choices: import argparse import contextlib +import functools import re import sys import threading +import weakref from argparse import ArgumentError from collections.abc import ( Callable, @@ -425,7 +427,7 @@ def _action_set_custom_parameter(self: argparse.Action, value: Any) -> None: _CUSTOM_ACTION_ATTRIBS.add(param_name) -def _validate_completion_callable(self: argparse.Action, value: Any) -> Any: +def _validate_completion_callable(self: argparse.Action, value: Any, *, source_attr: str) -> Any: """Validate choices_provider and completer values for potential conflicts.""" if value is None: return None @@ -438,13 +440,22 @@ def _validate_completion_callable(self: argparse.Action, value: Any) -> Any: "None of the following parameters can be used on an action that takes no arguments:\nchoices_provider, completer" ) raise ValueError(err_msg) + # deepcopy creates a new partial (and copies its bound arguments). Keep the + # original identity for receiver lookup while invoking the parser's own copy. + setattr(self, source_attr, weakref.ref(value) if isinstance(value, functools.partial) else None) return value # Add new attributes to argparse.Action. # See _ActionsContainer_add_argument() for details on these attributes. -register_argparse_argument_parameter("choices_provider", validator=_validate_completion_callable) -register_argparse_argument_parameter("completer", validator=_validate_completion_callable) +_CHOICES_PROVIDER_SOURCE = constants.cmd2_private_attr_name("choices_provider_source") +_COMPLETER_SOURCE = constants.cmd2_private_attr_name("completer_source") +register_argparse_argument_parameter( + "choices_provider", validator=functools.partial(_validate_completion_callable, source_attr=_CHOICES_PROVIDER_SOURCE) +) +register_argparse_argument_parameter( + "completer", validator=functools.partial(_validate_completion_callable, source_attr=_COMPLETER_SOURCE) +) register_argparse_argument_parameter("table_columns") register_argparse_argument_parameter("nargs_range") register_argparse_argument_parameter("suppress_tab_hint") diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 27ad738e6..36ba90289 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -215,6 +215,7 @@ def __init__(self, msg: str = "") -> None: ) from .utils import ( Settable, + _get_defining_classes, get_defining_class, get_types, strip_doc_annotations, @@ -6595,39 +6596,14 @@ def _resolve_func_self( :param cmd_support_func: command support function. This could be a completer or namespace provider :param cmd_self: The `self` associated with the command or subcommand """ - # figure out what class the command support function was defined in - func_class: type[Any] | None = get_defining_class(cmd_support_func) - - # Was there a defining class identified? If so, is it a sub-class of CommandSet? - if func_class is not None and issubclass(func_class, CommandSet): - # Since the support function is provided as an unbound function, we need to locate the instance - # of the CommandSet to pass in as `self` to emulate a bound method call. - # We're searching for candidates that match the support function's defining class type in this order: - # 1. Is the command's CommandSet a sub-class of the support function's class? - # 2. Do any of the registered CommandSets in the Cmd2 application exactly match the type? - # 3. Is there a registered CommandSet that is is the only matching subclass? - - func_self: CmdOrSet | None - - # check if the command's CommandSet is a sub-class of the support function's defining class - if isinstance(cmd_self, func_class): - # Case 1: Command's CommandSet is a sub-class of the support function's CommandSet - func_self = cmd_self - else: - # Search all registered CommandSets - func_self = None - candidate_sets: list[CommandSet[Any]] = [] - for installed_cmd_set in self._installed_command_sets: - if type(installed_cmd_set) == func_class: # noqa: E721 - # Case 2: CommandSet is an exact type match for the function's CommandSet - func_self = installed_cmd_set - break - - # Add candidate for Case 3: - if isinstance(installed_cmd_set, func_class): - candidate_sets.append(installed_cmd_set) - if func_self is None and len(candidate_sets) == 1: - # Case 3: There exists exactly 1 CommandSet that is a sub-class match of the function's CommandSet - func_self = candidate_sets[0] - return func_self - return self + owners = tuple(cls for cls in _get_defining_classes(cmd_support_func) if issubclass(cls, CommandSet)) + if not owners: + return self + if isinstance(cmd_self, owners): + return cmd_self + + # Prefer a registered instance of an installing class over one that inherits the provider. + matches = [cmd_set for cmd_set in self._installed_command_sets if isinstance(cmd_set, owners)] + exact = [cmd_set for cmd_set in matches if any(type(cmd_set) is owner for owner in owners)] + candidates = exact or matches + return candidates[0] if len(candidates) == 1 else None diff --git a/cmd2/utils.py b/cmd2/utils.py index c434b1deb..fd2a5db7a 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -26,7 +26,6 @@ TextIO, TypeVar, Union, - cast, ) from rich.text import Text @@ -1570,30 +1569,23 @@ def do_echo(self, arglist): setattr(cur_func, constants.COMMAND_ATTR_HELP_CATEGORY, category) -def _factory_method_owner(factory_class: type[Any], func: Callable[..., Any], *, is_partial: bool) -> type[Any] | None: - """Find the class in the factory's hierarchy that installed this particular callback.""" +def _factory_method_owners(factory_class: type[Any], callback: Callable[..., Any]) -> tuple[type, ...]: + """Find each class in the factory's hierarchy that installed this callback.""" pending = [factory_class] - visited: set[type[Any]] = set() - owner = None + visited: set[int] = set() + owners: list[type] = [] while pending: cls = pending.pop() - if cls in visited: + if id(cls) in visited: continue - visited.add(cls) + visited.add(id(cls)) for member in vars(cls).values(): target = member.__func__ if isinstance(member, (staticmethod, classmethod)) else member - # Parser copies can hold distinct partials around the same function. - while is_partial and isinstance(target, functools.partial): - target = target.func - if target is func: - if cls is factory_class or owner is not None: - # A callback shared by multiple branches can use the factory's receiver type. - return factory_class - owner = cls + if target is callback: + owners.append(cls) break - else: - pending.extend(type.__subclasses__(cls)) - return owner + pending.extend(type.__subclasses__(cls)) + return tuple(owners) def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: @@ -1603,9 +1595,15 @@ def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: https://stackoverflow.com/a/25959545/1956611 :param meth: method to inspect - :return: class type in which the supplied method was defined. None if it couldn't be resolved. + :return: class type in which the supplied method was defined. None if it couldn't be uniquely resolved. """ - is_partial = isinstance(meth, functools.partial) + owners = _get_defining_classes(meth) + return owners[0] if len(owners) == 1 else None + + +def _get_defining_classes(meth: Callable[..., Any]) -> tuple[type, ...]: + """Resolve method ownership, including factory callbacks installed on several classes.""" + original = meth while isinstance(meth, functools.partial): meth = meth.func if inspect.ismethod(meth) or ( @@ -1613,7 +1611,7 @@ def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: ): for cls in inspect.getmro(meth.__self__.__class__): if meth.__name__ in cls.__dict__: - return cls + return (cls,) meth = getattr(meth, "__func__", meth) # fallback to __qualname__ parsing if inspect.isfunction(meth): # For a local function, the reachable path ends at its enclosing factory. @@ -1625,11 +1623,15 @@ def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: owner = getattr(owner, name, None) if isinstance(owner, type): if not local_scope: - return owner - factory_owner = _factory_method_owner(owner, meth, is_partial=is_partial) - if factory_owner is not None: - return factory_owner - return cast(type, getattr(meth, "__objclass__", None)) # handle special descriptor objects + return (owner,) + owners = _factory_method_owners(owner, original) + if not owners and original is not meth: + # A partial of an installed method inherits that method's owner. + owners = _factory_method_owners(owner, meth) + if owners: + return owners + descriptor_owner = getattr(meth, "__objclass__", None) + return (descriptor_owner,) if descriptor_owner is not None else () class CustomCompletionSettings: diff --git a/tests/test_commandset.py b/tests/test_commandset.py index 9305f6a29..6029fb8a7 100644 --- a/tests/test_commandset.py +++ b/tests/test_commandset.py @@ -766,7 +766,7 @@ def complete_color(self, text: str, line: str, begidx: int, endidx: int) -> Comp @staticmethod def make_color_choices(): - return lambda cmd_set, limit=None: Completions.from_values(cmd_set.colors[:limit]) + return lambda receiver, *, key="colors", limit=None: Completions.from_values(getattr(receiver, key)[:limit]) color_choices = make_color_choices() first_color = functools.partial(make_color_choices(), limit=1) @@ -774,6 +774,7 @@ def make_color_choices(): paint_parser.add_argument("color", completer=complete_color) paint_parser.add_argument("--accent", choices_provider=color_choices) paint_parser.add_argument("--first", choices_provider=first_color) + paint_parser.add_argument("--app", choices_provider=functools.partial(first_color.func, key="app_colors")) @cmd2.with_argparser(paint_parser) def do_paint(self, ns: argparse.Namespace) -> None: @@ -812,6 +813,61 @@ def test_subclass_installed_factory_choices_provider(manual_command_sets_app) -> assert completions.to_strings() == ("red", "yellow") +def test_standalone_partial_of_factory_provider(manual_command_sets_app) -> None: + manual_command_sets_app.app_colors = ["purple"] + manual_command_sets_app.register_command_set(ColorPlugin.Commands(["blue", "green"])) + line = "paint blue --app " + completions = manual_command_sets_app.complete("", line, len(line), len(line)) + assert completions.to_strings() == ("purple",) + + +class SharedChoiceFactory: + @staticmethod + def make_choices(): + return lambda receiver: Completions.from_values(receiver.colors) + + +shared_choices = SharedChoiceFactory.make_choices() + + +class WarmPalette(SharedChoiceFactory, cmd2.CommandSet): + choices = shared_choices + + def __init__(self, colors: list[str]) -> None: + super().__init__() + self.colors = colors + + parser = cmd2.Cmd2ArgumentParser() + parser.add_argument("color", choices_provider=choices) + + @cmd2.with_argparser(parser) + def do_warm(self, ns: argparse.Namespace) -> None: + self._cmd.poutput(ns.color) + + +class CoolPalette(SharedChoiceFactory, cmd2.CommandSet): + choices = shared_choices + + def __init__(self, colors: list[str]) -> None: + super().__init__() + self.colors = colors + + +def test_shared_factory_callback_receivers(manual_command_sets_app) -> None: + app = manual_command_sets_app + warm = WarmPalette(["red"]) + cool = CoolPalette(["blue"]) + app.register_command_set(warm) + line = "warm " + assert app.complete("", line, len(line), len(line)).to_strings() == ("red",) + assert app._resolve_func_self(shared_choices, app) is warm + + app.register_command_set(cool) + assert app._resolve_func_self(shared_choices, warm) is warm + assert app._resolve_func_self(shared_choices, cool) is cool + assert app._resolve_func_self(shared_choices, app) is None + + complete_states_expected_self = None diff --git a/tests/test_utils_defining_class.py b/tests/test_utils_defining_class.py index 7a5e1e78b..b0d72471c 100644 --- a/tests/test_utils_defining_class.py +++ b/tests/test_utils_defining_class.py @@ -117,8 +117,57 @@ def test_get_defining_class_factory_callback() -> None: assert cu.get_defining_class(Outer.Inner.class_choices) is Outer.Inner assert cu.get_defining_class(Outer.Inner.partial_choices) is Outer.Inner assert cu.get_defining_class(Outer.Inner.partial_choices.func) is None + assert cu.get_defining_class(functools.partial(Outer.Inner.partial_choices.func, "other")) is None def test_get_defining_class_nested_class_in_unknown_module(monkeypatch) -> None: monkeypatch.setattr(Outer.Inner.method, "__module__", "missing_cmd2_test_module") assert cu.get_defining_class(Outer.Inner.method) is None + + +def test_factory_lookup_through_unhashable_diamond() -> None: + class UnhashableMeta(type): + __hash__ = None + + class Left(Outer.Inner): + pass + + class Right(Outer.Inner): + pass + + class Diamond(Left, Right, metaclass=UnhashableMeta): + choices = Outer.Inner.make_choices() + + assert cu.get_defining_class(Diamond.choices) is Diamond + assert cu.get_defining_class(Outer.Inner.make_choices()) is None + + +def test_factory_lookup_without_receiver_requires_unique_owner() -> None: + choices = Outer.Inner.make_choices() + + class First(Outer.Inner): + provider = choices + + class Second(Outer.Inner): + provider = choices + + assert cu.get_defining_class(First.provider) is None + assert cu.get_defining_class(Second.provider) is None + + +def test_installed_partial_has_its_own_owner() -> None: + callback = Outer.Inner.make_choices() + + class Raw(Outer.Inner): + choices = callback + + class Wrapped(Outer.Inner): + choices = functools.partial(callback) + + assert cu.get_defining_class(Raw.choices) is Raw + assert cu.get_defining_class(Wrapped.choices) is Wrapped + assert cu.get_defining_class(functools.partial(Raw.choices)) is Raw + + +def test_get_defining_class_descriptor_fallback() -> None: + assert cu.get_defining_class(str.join) is str From 41855c4a4bc9f718a4c96af32fa42e2e38012a44 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:45:53 -0500 Subject: [PATCH 6/8] Resolve shared completion callbacks for app commands and attached subcommands Use the active command receiver before looking for a registered fallback. Keep partial callback identity across parser copies while preserving action pickling and custom completion parameters. --- cmd2/argparse_completer.py | 14 ++++++++-- cmd2/argparse_utils.py | 18 ++++++++++--- cmd2/cmd2.py | 7 ++--- tests/test_argparse_utils.py | 37 +++++++++++++++++++++++++ tests/test_commandset.py | 52 ++++++++++++++++++++++++++++++++++++ 5 files changed, 120 insertions(+), 8 deletions(-) diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py index a7abd940f..a6fe048ba 100644 --- a/cmd2/argparse_completer.py +++ b/cmd2/argparse_completer.py @@ -33,7 +33,10 @@ CompletionItem, Completions, ) -from .constants import INFINITY +from .constants import ( + INFINITY, + PARSER_ATTR_OWNER_ID, +) from .exceptions import CompletionError from .rich_utils import Cmd2SimpleTable from .types import ( @@ -368,6 +371,12 @@ def consume_argument(arg_state: _ArgumentState, arg_token: str) -> None: parent_tokens[action.dest] = [token] parser = self._subcommand_action.choices[token] + # An attached subcommand may belong to a different set or to the app itself. + owner_id = getattr(parser, PARSER_ATTR_OWNER_ID, None) + if owner_id is not None: + cmd_set = next( + (owner for owner in self._cmd_app._installed_command_sets if id(owner) == owner_id), None + ) completer = parser.completer_class(parser, self._cmd_app, parent_tokens=parent_tokens) return completer.complete(text, line, begidx, endidx, tokens[token_index + 1 :], cmd_set=cmd_set) @@ -734,7 +743,8 @@ def _prepare_callable_params( # Resolve the 'self' instance for the method source_ref = getattr(arg_state.action, source_attr, None) original = source_ref() if source_ref is not None else None - self_arg = self._cmd_app._resolve_func_self(original if original is not None else to_call, cmd_set) + receiver = self._cmd_app if cmd_set is None else cmd_set + self_arg = self._cmd_app._resolve_func_self(original if original is not None else to_call, receiver) if self_arg is None: raise CompletionError("Could not find CommandSet instance matching defining type") diff --git a/cmd2/argparse_utils.py b/cmd2/argparse_utils.py index f9c26b054..1aaec6272 100644 --- a/cmd2/argparse_utils.py +++ b/cmd2/argparse_utils.py @@ -427,6 +427,17 @@ def _action_set_custom_parameter(self: argparse.Action, value: Any) -> None: _CUSTOM_ACTION_ATTRIBS.add(param_name) +class _CompletionSource(weakref.ref[functools.partial[Any]]): + """Track a partial's live class identity across parser copies.""" + + def __deepcopy__(self, memo: dict[int, Any]) -> "_CompletionSource": + return self + + def __reduce__(self) -> tuple[type, tuple[()]]: + # Ownership belongs to classes in this process. A deserialized action resolves its own callback. + return type(None), () + + def _validate_completion_callable(self: argparse.Action, value: Any, *, source_attr: str) -> Any: """Validate choices_provider and completer values for potential conflicts.""" if value is None: @@ -442,14 +453,15 @@ def _validate_completion_callable(self: argparse.Action, value: Any, *, source_a raise ValueError(err_msg) # deepcopy creates a new partial (and copies its bound arguments). Keep the # original identity for receiver lookup while invoking the parser's own copy. - setattr(self, source_attr, weakref.ref(value) if isinstance(value, functools.partial) else None) + setattr(self, source_attr, _CompletionSource(value) if isinstance(value, functools.partial) else None) return value # Add new attributes to argparse.Action. # See _ActionsContainer_add_argument() for details on these attributes. -_CHOICES_PROVIDER_SOURCE = constants.cmd2_private_attr_name("choices_provider_source") -_COMPLETER_SOURCE = constants.cmd2_private_attr_name("completer_source") +# Custom parameter names must be Python identifiers, so they cannot collide with these dotted names. +_CHOICES_PROVIDER_SOURCE = constants.cmd2_private_attr_name("choices_provider.source") +_COMPLETER_SOURCE = constants.cmd2_private_attr_name("completer.source") register_argparse_argument_parameter( "choices_provider", validator=functools.partial(_validate_completion_callable, source_attr=_CHOICES_PROVIDER_SOURCE) ) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 36ba90289..3b338f2d7 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -6596,11 +6596,12 @@ def _resolve_func_self( :param cmd_support_func: command support function. This could be a completer or namespace provider :param cmd_self: The `self` associated with the command or subcommand """ - owners = tuple(cls for cls in _get_defining_classes(cmd_support_func) if issubclass(cls, CommandSet)) - if not owners: - return self + owners = _get_defining_classes(cmd_support_func) if isinstance(cmd_self, owners): return cmd_self + owners = tuple(cls for cls in owners if issubclass(cls, CommandSet)) + if not owners: + return self # Prefer a registered instance of an installing class over one that inherits the provider. matches = [cmd_set for cmd_set in self._installed_command_sets if isinstance(cmd_set, owners)] diff --git a/tests/test_argparse_utils.py b/tests/test_argparse_utils.py index 0bed9a979..bfa686c44 100644 --- a/tests/test_argparse_utils.py +++ b/tests/test_argparse_utils.py @@ -1,6 +1,8 @@ """Unit/functional testing for argparse customizations in cmd2""" import argparse +import functools +import pickle import sys import pytest @@ -335,6 +337,41 @@ def test_register_argparse_argument_parameter() -> None: delattr(argparse.Action, attr_name) +def _palette_callback(receiver, *args, color): + return cmd2.Completions.from_values([color]) + + +@pytest.mark.parametrize("parameter", ["completer", "choices_provider"]) +def test_custom_callback_source_parameter(parameter) -> None: + source = f"{parameter}_source" + register_argparse_argument_parameter(source) + try: + parser = Cmd2ArgumentParser() + callback = functools.partial(_palette_callback, color="purple") + action = parser.add_argument("color", **{parameter: callback, source: "custom"}) + + class App(cmd2.Cmd): + @cmd2.with_argparser(parser) + def do_palette(self, ns: argparse.Namespace) -> None: + pass + + app = App(auto_load_commands=False) + line = "palette " + assert app.complete("", line, len(line), len(line)).to_strings() == ("purple",) + assert getattr(action, f"get_{source}")() == "custom" + finally: + argparse_utils._CUSTOM_ACTION_ATTRIBS.remove(source) + delattr(argparse.Action, f"get_{source}") + delattr(argparse.Action, f"set_{source}") + + +def test_pickle_action_with_partial_provider() -> None: + action = argparse.Action(option_strings=[], dest="color") + action.set_choices_provider(functools.partial(_palette_callback, color="purple")) + restored = pickle.loads(pickle.dumps(action)) + assert restored.get_choices_provider()(None).to_strings() == ("purple",) + + def test_subcommand_attachment() -> None: """Test Cmd2ArgumentParser convenience methods for attaching and detaching subcommands.""" diff --git a/tests/test_commandset.py b/tests/test_commandset.py index 6029fb8a7..bd6d3f9db 100644 --- a/tests/test_commandset.py +++ b/tests/test_commandset.py @@ -868,6 +868,58 @@ def test_shared_factory_callback_receivers(manual_command_sets_app) -> None: assert app._resolve_func_self(shared_choices, app) is None +class PaletteApp(SharedChoiceFactory, cmd2.Cmd): + choices = shared_choices + colors = ("purple",) + + @cmd2.with_argparser(WarmPalette.parser) + def do_palette(self, ns: argparse.Namespace) -> None: + self.poutput(ns.color) + + +@pytest.mark.parametrize("sets", [[], [WarmPalette(["red"])]]) +def test_app_owns_shared_choices(sets) -> None: + app = PaletteApp(command_sets=sets, auto_load_commands=False) + line = "palette " + assert app.complete("", line, len(line), len(line)).to_strings() == ("purple",) + + +def test_attached_subcommand_owns_shared_choices() -> None: + class Parent(WarmPalette): + group_parser = cmd2.Cmd2ArgumentParser() + group_parser.add_subparsers() + + @cmd2.with_argparser(group_parser) + def do_group(self, ns: argparse.Namespace) -> None: + pass + + class Child(CoolPalette): + @cmd2.as_subcommand_to("group", "child", WarmPalette.parser) + def child(self, ns: argparse.Namespace) -> None: + pass + + @cmd2.as_subcommand_to("app_group", "child", WarmPalette.parser) + def child_of_app(self, ns: argparse.Namespace) -> None: + pass + + class App(PaletteApp): + @cmd2.with_argparser(Parent.group_parser) + def do_app_group(self, ns: argparse.Namespace) -> None: + pass + + @cmd2.as_subcommand_to("app_group", "app_child", WarmPalette.parser) + def app_child(self, ns: argparse.Namespace) -> None: + pass + + app = App(command_sets=[Parent(["red"]), Child(["blue"])], auto_load_commands=False) + line = "group child " + assert app.complete("", line, len(line), len(line)).to_strings() == ("blue",) + line = "app_group child " + assert app.complete("", line, len(line), len(line)).to_strings() == ("blue",) + line = "app_group app_child " + assert app.complete("", line, len(line), len(line)).to_strings() == ("purple",) + + complete_states_expected_self = None From 8883417f32cffcc5b174735481ea62d3d4a7cf51 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:58:23 -0500 Subject: [PATCH 7/8] Preserve completion receivers for inline and shared providers Track the declaration scope of argparse callbacks to recognize inline parser-factory providers. Match live owners by nominal class identity so application fallbacks and concrete protocol providers work. --- cmd2/argparse_completer.py | 7 ++++- cmd2/argparse_utils.py | 7 +++++ cmd2/cmd2.py | 22 ++++++++----- cmd2/utils.py | 5 ++- tests/test_commandset.py | 64 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 96 insertions(+), 9 deletions(-) diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py index a6fe048ba..0b1dc7ba2 100644 --- a/cmd2/argparse_completer.py +++ b/cmd2/argparse_completer.py @@ -23,6 +23,7 @@ from rich.text import Text from .argparse_utils import ( + _CALLBACK_DECLARATION_SCOPE, _CHOICES_PROVIDER_SOURCE, _COMPLETER_SOURCE, Cmd2ArgumentParser, @@ -744,7 +745,11 @@ def _prepare_callable_params( source_ref = getattr(arg_state.action, source_attr, None) original = source_ref() if source_ref is not None else None receiver = self._cmd_app if cmd_set is None else cmd_set - self_arg = self._cmd_app._resolve_func_self(original if original is not None else to_call, receiver) + self_arg = self._cmd_app._resolve_func_self( + original if original is not None else to_call, + receiver, + declaration_scope=getattr(arg_state.action, _CALLBACK_DECLARATION_SCOPE, None), + ) if self_arg is None: raise CompletionError("Could not find CommandSet instance matching defining type") diff --git a/cmd2/argparse_utils.py b/cmd2/argparse_utils.py index 1aaec6272..6a88fe778 100644 --- a/cmd2/argparse_utils.py +++ b/cmd2/argparse_utils.py @@ -462,6 +462,7 @@ def _validate_completion_callable(self: argparse.Action, value: Any, *, source_a # Custom parameter names must be Python identifiers, so they cannot collide with these dotted names. _CHOICES_PROVIDER_SOURCE = constants.cmd2_private_attr_name("choices_provider.source") _COMPLETER_SOURCE = constants.cmd2_private_attr_name("completer.source") +_CALLBACK_DECLARATION_SCOPE = constants.cmd2_private_attr_name("callback.declaration_scope") register_argparse_argument_parameter( "choices_provider", validator=functools.partial(_validate_completion_callable, source_attr=_CHOICES_PROVIDER_SOURCE) ) @@ -586,6 +587,12 @@ def _ActionsContainer_add_argument( # noqa: N802 # Create the argument using the original add_argument function new_arg = orig_actions_container_add_argument(self, *args, **kwargs) + if choices_provider is not None or completer is not None: + # An inline callback belongs to the parser factory that declares the argument. + # Keep the scope names only, so parser copies and pickles do not retain the calling frame. + caller = sys._getframe(1) + setattr(new_arg, _CALLBACK_DECLARATION_SCOPE, (caller.f_globals.get("__name__"), caller.f_code.co_qualname)) + # Set the cmd2-specific attributes new_arg.set_nargs_range(nargs_range) # type: ignore[attr-defined] # ty: ignore[missing-attribute] new_arg.set_choices_provider(choices_provider) # type: ignore[attr-defined] # ty: ignore[missing-attribute] diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 3b338f2d7..e579e4424 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -6585,6 +6585,8 @@ def _resolve_func_self( self, cmd_support_func: Callable[..., Any], cmd_self: CmdOrSet | None, + *, + declaration_scope: tuple[str, str] | None = None, ) -> object | None: """Attempt to resolve a candidate instance to pass as 'self'. @@ -6595,16 +6597,22 @@ def _resolve_func_self( :param cmd_support_func: command support function. This could be a completer or namespace provider :param cmd_self: The `self` associated with the command or subcommand + :param declaration_scope: module and qualified name of the scope that added the argument """ - owners = _get_defining_classes(cmd_support_func) - if isinstance(cmd_self, owners): + owners = _get_defining_classes(cmd_support_func, declaration_scope=declaration_scope) + owner_ids = {id(owner) for owner in owners} + + def matches_owner(receiver: object) -> bool: + # A provider may be defined on a Protocol that disallows runtime instance checks. + return any(id(base) in owner_ids for base in type(receiver).__mro__) + + if cmd_self is not None and matches_owner(cmd_self): return cmd_self - owners = tuple(cls for cls in owners if issubclass(cls, CommandSet)) - if not owners: + if not any(issubclass(owner, CommandSet) for owner in owners): return self - # Prefer a registered instance of an installing class over one that inherits the provider. - matches = [cmd_set for cmd_set in self._installed_command_sets if isinstance(cmd_set, owners)] - exact = [cmd_set for cmd_set in matches if any(type(cmd_set) is owner for owner in owners)] + # Include the app among live owners and prefer an exact owner over an inheriting instance. + matches = [receiver for receiver in (self, *self._installed_command_sets) if matches_owner(receiver)] + exact = [receiver for receiver in matches if id(type(receiver)) in owner_ids] candidates = exact or matches return candidates[0] if len(candidates) == 1 else None diff --git a/cmd2/utils.py b/cmd2/utils.py index fd2a5db7a..06e00a89a 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -1601,7 +1601,7 @@ def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: return owners[0] if len(owners) == 1 else None -def _get_defining_classes(meth: Callable[..., Any]) -> tuple[type, ...]: +def _get_defining_classes(meth: Callable[..., Any], *, declaration_scope: tuple[str, str] | None = None) -> tuple[type, ...]: """Resolve method ownership, including factory callbacks installed on several classes.""" original = meth while isinstance(meth, functools.partial): @@ -1630,6 +1630,9 @@ def _get_defining_classes(meth: Callable[..., Any]) -> tuple[type, ...]: owners = _factory_method_owners(owner, meth) if owners: return owners + if declaration_scope == (meth.__module__, reachable_name): + # The factory passed its own local function directly to add_argument(). + return (owner,) descriptor_owner = getattr(meth, "__objclass__", None) return (descriptor_owner,) if descriptor_owner is not None else () diff --git a/tests/test_commandset.py b/tests/test_commandset.py index bd6d3f9db..f6d1e79ed 100644 --- a/tests/test_commandset.py +++ b/tests/test_commandset.py @@ -3,6 +3,7 @@ import argparse import functools import signal +from typing import Protocol import pytest @@ -877,6 +878,69 @@ def do_palette(self, ns: argparse.Namespace) -> None: self.poutput(ns.color) +class ParserFactoryPalette(cmd2.CommandSet): + def __init__(self, colors) -> None: + super().__init__() + self.colors = colors + + @staticmethod + def build_parser(): + parser = cmd2.Cmd2ArgumentParser() + parser.add_argument("color", choices_provider=lambda receiver: Completions.from_values(receiver.colors)) + return parser + + @cmd2.with_argparser(build_parser) + def do_factory_palette(self, ns: argparse.Namespace) -> None: + pass + + @cmd2.with_argparser(build_parser()) + def do_prebuilt_palette(self, ns: argparse.Namespace) -> None: + pass + + +@pytest.mark.parametrize("command", ["factory_palette", "prebuilt_palette"]) +def test_inline_parser_factory_provider(command) -> None: + app = PaletteApp(command_sets=[ParserFactoryPalette(["green"])], auto_load_commands=False) + line = f"{command} " + assert app.complete("", line, len(line), len(line)).to_strings() == ("green",) + + +class ProtocolPalette(Protocol): + colors: tuple[str, ...] + + def choices(self) -> Completions: + return Completions.from_values(self.colors) + + +class BorrowedPalette(cmd2.CommandSet): + def __init__(self, colors) -> None: + super().__init__() + self.colors = colors + + parser = cmd2.Cmd2ArgumentParser() + parser.add_argument("--shared", choices_provider=shared_choices) + parser.add_argument("--protocol", choices_provider=ProtocolPalette.choices) + + @cmd2.with_argparser(parser) + def do_borrow(self, ns: argparse.Namespace) -> None: + pass + + +@pytest.mark.parametrize("option", ["--shared", "--protocol"]) +def test_unrelated_command_uses_app_provider(option) -> None: + app = PaletteApp(command_sets=[BorrowedPalette(["green"])], auto_load_commands=False) + line = f"borrow {option} " + assert app.complete("", line, len(line), len(line)).to_strings() == ("purple",) + + +def test_unrelated_command_with_two_live_owners_is_ambiguous() -> None: + app = PaletteApp(command_sets=[BorrowedPalette(["green"]), WarmPalette(["red"])], auto_load_commands=False) + line = "borrow --shared " + completions = app.complete("", line, len(line), len(line)) + assert not completions + assert "Could not find CommandSet instance" in completions.error + + @pytest.mark.parametrize("sets", [[], [WarmPalette(["red"])]]) def test_app_owns_shared_choices(sets) -> None: app = PaletteApp(command_sets=sets, auto_load_commands=False) From 36c8ec624678ada797ca032bce46a251b5ca327d Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:08:57 -0500 Subject: [PATCH 8/8] Preserve factory receivers for completion and namespace providers Recognize local callbacks when they are registered through action setters, parser helpers, or command decorators. Exercise both tab completion and command execution with distinct application and command set state. --- cmd2/annotated.py | 4 +++- cmd2/argparse_completer.py | 3 +-- cmd2/argparse_utils.py | 26 +++++++++++++++++++------- cmd2/cmd2.py | 6 +++--- cmd2/decorators.py | 4 +++- cmd2/utils.py | 6 +++--- tests/test_commandset.py | 35 +++++++++++++++++++++++++++++++++-- 7 files changed, 65 insertions(+), 19 deletions(-) diff --git a/cmd2/annotated.py b/cmd2/annotated.py index 1f9f82dee..3b85891e7 100644 --- a/cmd2/annotated.py +++ b/cmd2/annotated.py @@ -301,6 +301,7 @@ def do_build(self, target: str, common: CommonArgs): ArgparseCommandSpec, Cmd2ArgumentParser, SubcommandSpec, + _registered_in_enclosing_factory, ) from .completion import CompletionItem from .decorators import _parse_positionals @@ -3087,6 +3088,7 @@ def with_annotated( "Configure these behaviors on the base command instead." ) + inline_ns_provider = _registered_in_enclosing_factory(ns_provider) options = _ParserBuildOptions( groups=groups, mutually_exclusive_groups=mutually_exclusive_groups, @@ -3167,7 +3169,7 @@ def cmd_wrapper(*args: Any, **kwargs: Any) -> _CommandReturn: if ns_provider is None: namespace = None else: - provider_self = cmd_app._resolve_func_self(ns_provider, args[0]) + provider_self = cmd_app._resolve_func_self(ns_provider, owner, include_enclosing_class=inline_ns_provider) namespace = ns_provider(provider_self if provider_self is not None else cmd_app) try: diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py index 0b1dc7ba2..95f557a10 100644 --- a/cmd2/argparse_completer.py +++ b/cmd2/argparse_completer.py @@ -23,7 +23,6 @@ from rich.text import Text from .argparse_utils import ( - _CALLBACK_DECLARATION_SCOPE, _CHOICES_PROVIDER_SOURCE, _COMPLETER_SOURCE, Cmd2ArgumentParser, @@ -748,7 +747,7 @@ def _prepare_callable_params( self_arg = self._cmd_app._resolve_func_self( original if original is not None else to_call, receiver, - declaration_scope=getattr(arg_state.action, _CALLBACK_DECLARATION_SCOPE, None), + include_enclosing_class=getattr(arg_state.action, f"{source_attr}.inline", False), ) if self_arg is None: raise CompletionError("Could not find CommandSet instance matching defining type") diff --git a/cmd2/argparse_utils.py b/cmd2/argparse_utils.py index 6a88fe778..b21c87fa4 100644 --- a/cmd2/argparse_utils.py +++ b/cmd2/argparse_utils.py @@ -227,6 +227,7 @@ def get_choices(self) -> Choices: import argparse import contextlib import functools +import inspect import re import sys import threading @@ -438,6 +439,23 @@ def __reduce__(self) -> tuple[type, tuple[()]]: return type(None), () +def _registered_in_enclosing_factory(callback: Callable[..., Any] | None) -> bool: + """Check at registration whether a local callback's enclosing factory is active.""" + while isinstance(callback, functools.partial): + callback = callback.func + if not inspect.isfunction(callback): + return False + factory, local_scope, _ = callback.__qualname__.partition("..") + if local_scope: + # Helpers and public action setters may sit between the factory and registration. + frame = sys._getframe().f_back + while frame is not None: + if frame.f_globals is callback.__globals__ and frame.f_code.co_qualname == factory: + return True + frame = frame.f_back + return False + + def _validate_completion_callable(self: argparse.Action, value: Any, *, source_attr: str) -> Any: """Validate choices_provider and completer values for potential conflicts.""" if value is None: @@ -454,6 +472,7 @@ def _validate_completion_callable(self: argparse.Action, value: Any, *, source_a # deepcopy creates a new partial (and copies its bound arguments). Keep the # original identity for receiver lookup while invoking the parser's own copy. setattr(self, source_attr, _CompletionSource(value) if isinstance(value, functools.partial) else None) + setattr(self, f"{source_attr}.inline", _registered_in_enclosing_factory(value)) return value @@ -462,7 +481,6 @@ def _validate_completion_callable(self: argparse.Action, value: Any, *, source_a # Custom parameter names must be Python identifiers, so they cannot collide with these dotted names. _CHOICES_PROVIDER_SOURCE = constants.cmd2_private_attr_name("choices_provider.source") _COMPLETER_SOURCE = constants.cmd2_private_attr_name("completer.source") -_CALLBACK_DECLARATION_SCOPE = constants.cmd2_private_attr_name("callback.declaration_scope") register_argparse_argument_parameter( "choices_provider", validator=functools.partial(_validate_completion_callable, source_attr=_CHOICES_PROVIDER_SOURCE) ) @@ -587,12 +605,6 @@ def _ActionsContainer_add_argument( # noqa: N802 # Create the argument using the original add_argument function new_arg = orig_actions_container_add_argument(self, *args, **kwargs) - if choices_provider is not None or completer is not None: - # An inline callback belongs to the parser factory that declares the argument. - # Keep the scope names only, so parser copies and pickles do not retain the calling frame. - caller = sys._getframe(1) - setattr(new_arg, _CALLBACK_DECLARATION_SCOPE, (caller.f_globals.get("__name__"), caller.f_code.co_qualname)) - # Set the cmd2-specific attributes new_arg.set_nargs_range(nargs_range) # type: ignore[attr-defined] # ty: ignore[missing-attribute] new_arg.set_choices_provider(choices_provider) # type: ignore[attr-defined] # ty: ignore[missing-attribute] diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index e579e4424..adddf2437 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -6586,7 +6586,7 @@ def _resolve_func_self( cmd_support_func: Callable[..., Any], cmd_self: CmdOrSet | None, *, - declaration_scope: tuple[str, str] | None = None, + include_enclosing_class: bool = False, ) -> object | None: """Attempt to resolve a candidate instance to pass as 'self'. @@ -6597,9 +6597,9 @@ def _resolve_func_self( :param cmd_support_func: command support function. This could be a completer or namespace provider :param cmd_self: The `self` associated with the command or subcommand - :param declaration_scope: module and qualified name of the scope that added the argument + :param include_enclosing_class: whether the enclosing factory registered this callback """ - owners = _get_defining_classes(cmd_support_func, declaration_scope=declaration_scope) + owners = _get_defining_classes(cmd_support_func, include_enclosing_class=include_enclosing_class) owner_ids = {id(owner) for owner in owners} def matches_owner(receiver: object) -> bool: diff --git a/cmd2/decorators.py b/cmd2/decorators.py index b3167e499..ba12ab377 100644 --- a/cmd2/decorators.py +++ b/cmd2/decorators.py @@ -23,6 +23,7 @@ NoParamParserFactory, ParserSource, SubcommandSpec, + _registered_in_enclosing_factory, ) from .command_set import CommandSet from .exceptions import Cmd2ArgparseError @@ -301,6 +302,7 @@ def do_argprint(self, args: argparse.Namespace, unknown_args: list[str]): ``` """ + inline_ns_provider = _registered_in_enclosing_factory(ns_provider) def arg_decorator(func: ArgparseCommandFunc[CmdOrSetT]) -> RawCommandFunc[CmdOrSetT]: """Decorate function that ingests an Argparse Command Function and returns a raw command function. @@ -339,7 +341,7 @@ def cmd_wrapper(*args: Any, **kwargs: Any) -> bool | None: # The namespace provider may or may not be defined in the same class as the command. Since provider # functions are registered with the command argparser before anything is instantiated, we # need to find an instance at runtime that matches the types during declaration - provider_self = cmd_app._resolve_func_self(ns_provider, args[0]) + provider_self = cmd_app._resolve_func_self(ns_provider, args[0], include_enclosing_class=inline_ns_provider) initial_namespace = ns_provider(provider_self if provider_self is not None else cmd_app) try: diff --git a/cmd2/utils.py b/cmd2/utils.py index 06e00a89a..50622633a 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -1601,7 +1601,7 @@ def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: return owners[0] if len(owners) == 1 else None -def _get_defining_classes(meth: Callable[..., Any], *, declaration_scope: tuple[str, str] | None = None) -> tuple[type, ...]: +def _get_defining_classes(meth: Callable[..., Any], *, include_enclosing_class: bool = False) -> tuple[type, ...]: """Resolve method ownership, including factory callbacks installed on several classes.""" original = meth while isinstance(meth, functools.partial): @@ -1630,8 +1630,8 @@ def _get_defining_classes(meth: Callable[..., Any], *, declaration_scope: tuple[ owners = _factory_method_owners(owner, meth) if owners: return owners - if declaration_scope == (meth.__module__, reachable_name): - # The factory passed its own local function directly to add_argument(). + if include_enclosing_class: + # A class's factory registered its own local callback. return (owner,) descriptor_owner = getattr(meth, "__objclass__", None) return (descriptor_owner,) if descriptor_owner is not None else () diff --git a/tests/test_commandset.py b/tests/test_commandset.py index f6d1e79ed..5a6fcf800 100644 --- a/tests/test_commandset.py +++ b/tests/test_commandset.py @@ -878,6 +878,10 @@ def do_palette(self, ns: argparse.Namespace) -> None: self.poutput(ns.color) +def _add_color_option(parser, provider) -> None: + parser.add_argument("--helper", choices_provider=provider) + + class ParserFactoryPalette(cmd2.CommandSet): def __init__(self, colors) -> None: super().__init__() @@ -887,6 +891,9 @@ def __init__(self, colors) -> None: def build_parser(): parser = cmd2.Cmd2ArgumentParser() parser.add_argument("color", choices_provider=lambda receiver: Completions.from_values(receiver.colors)) + parser.add_argument("--setter").set_choices_provider(lambda receiver: Completions.from_values(receiver.colors)) + parser.add_argument("--completer").set_completer(lambda receiver, *args: Completions.from_values(receiver.colors)) + _add_color_option(parser, lambda receiver: Completions.from_values(receiver.colors)) return parser @cmd2.with_argparser(build_parser) @@ -897,14 +904,38 @@ def do_factory_palette(self, ns: argparse.Namespace) -> None: def do_prebuilt_palette(self, ns: argparse.Namespace) -> None: pass + @staticmethod + def command_with_colors(annotated=False): + def namespace(receiver): + return argparse.Namespace(color=receiver.colors[0]) + + if annotated: + return cmd2.with_annotated(ns_provider=namespace) + return cmd2.with_argparser(cmd2.Cmd2ArgumentParser(), ns_provider=namespace) + + @command_with_colors() + def do_namespace_palette(self, ns: argparse.Namespace) -> None: + self._cmd.poutput(ns.color) + + @command_with_colors(annotated=True) + def do_annotated_palette(self, color: str = "default") -> None: + self._cmd.poutput(color) + @pytest.mark.parametrize("command", ["factory_palette", "prebuilt_palette"]) -def test_inline_parser_factory_provider(command) -> None: +@pytest.mark.parametrize("option", ["", "value --setter ", "value --helper ", "value --completer "]) +def test_inline_parser_factory_provider(command, option) -> None: app = PaletteApp(command_sets=[ParserFactoryPalette(["green"])], auto_load_commands=False) - line = f"{command} " + line = f"{command} {option}" assert app.complete("", line, len(line), len(line)).to_strings() == ("green",) +@pytest.mark.parametrize("command", ["namespace_palette", "annotated_palette"]) +def test_inline_namespace_provider(command) -> None: + app = PaletteApp(command_sets=[ParserFactoryPalette(["green"])], auto_load_commands=False) + assert run_cmd(app, command) == (["green"], []) + + class ProtocolPalette(Protocol): colors: tuple[str, ...]