Skip to content

Commit 34d5f3d

Browse files
committed
Fixed error in categorize() which would not handle a bound method in an Iterable.
1 parent 44fd9e8 commit 34d5f3d

2 files changed

Lines changed: 24 additions & 22 deletions

File tree

cmd2/utils.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,7 @@ def categorize(func: Callable[..., Any] | Iterable[Callable[..., Any]], category
694694
The help command output will group the passed function under the
695695
specified category heading
696696
697-
:param func: function or list of functions to categorize
697+
:param func: function or Iterable of functions to categorize
698698
:param category: category to put it in
699699
700700
Example:
@@ -710,13 +710,13 @@ def do_echo(self, arglist):
710710
For an alternative approach to categorizing commands using a decorator, see [cmd2.decorators.with_category][]
711711
712712
"""
713-
if isinstance(func, Iterable):
714-
for item in func:
715-
setattr(item, constants.COMMAND_ATTR_HELP_CATEGORY, category)
716-
elif inspect.ismethod(func):
717-
setattr(func.__func__, constants.COMMAND_ATTR_HELP_CATEGORY, category)
718-
else:
719-
setattr(func, constants.COMMAND_ATTR_HELP_CATEGORY, category)
713+
funcs = func if isinstance(func, Iterable) else (func,)
714+
715+
for cur_func in funcs:
716+
if inspect.ismethod(cur_func):
717+
setattr(cur_func.__func__, constants.COMMAND_ATTR_HELP_CATEGORY, category)
718+
else:
719+
setattr(cur_func, constants.COMMAND_ATTR_HELP_CATEGORY, category)
720720

721721

722722
def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None:

tests/test_utils.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -411,22 +411,24 @@ def func1() -> None:
411411
cu.categorize(func1, category)
412412
assert getattr(func1, attr_name) == category
413413

414-
# Test iterable of functions
415-
def func2() -> None:
416-
pass
414+
# Test single method
415+
class Foo:
416+
def foo_method(self) -> None:
417+
pass
417418

418-
def func3() -> None:
419-
pass
419+
f = Foo()
420+
cu.categorize(f.foo_method, category)
421+
assert getattr(Foo.foo_method, attr_name) == category
420422

421-
cu.categorize([func2, func3], category)
422-
assert getattr(func2, attr_name) == category
423-
assert getattr(func3, attr_name) == category
423+
# Test iterable
424+
def func2() -> None:
425+
pass
424426

425-
# Test bound method
426-
class Foo:
427-
def bar(self) -> None:
427+
class Bar:
428+
def bar_method(self) -> None:
428429
pass
429430

430-
f = Foo()
431-
cu.categorize(f.bar, category)
432-
assert getattr(Foo.bar, attr_name) == category
431+
b = Bar()
432+
cu.categorize([func2, b.bar_method], category)
433+
assert getattr(func2, attr_name) == category
434+
assert getattr(Bar.bar_method, attr_name) == category

0 commit comments

Comments
 (0)