Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions cmd2/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1589,9 +1589,10 @@ 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):
cls = getattr(inspect.getmodule(meth), meth.__qualname__.split(".<locals>", 1)[0].rsplit(".", 1)[0])
if isinstance(cls, type):
return cls
# The name isn't necessarily in the module, as with a module-level lambda whose __qualname__ is "<lambda>"
owner = getattr(inspect.getmodule(meth), meth.__qualname__.split(".<locals>", 1)[0].rsplit(".", 1)[0], None)
Comment thread
tleonhardt marked this conversation as resolved.
Resolved
if isinstance(owner, type):
return owner
return cast(type, getattr(meth, "__objclass__", None)) # handle special descriptor objects


Expand Down
9 changes: 9 additions & 0 deletions tests/test_utils_defining_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,12 @@ def test_get_defining_class() -> None:
nested_partial_bound = functools.partial(partial_bound, 2)
assert cu.get_defining_class(partial_bound) is ParentClass
assert cu.get_defining_class(nested_partial_bound) is ParentClass


module_level_lambda = lambda cmd: ["alpha", "beta"] # noqa: E731


def test_get_defining_class_module_level_lambda() -> None:
# A module-level lambda's __qualname__ is "<lambda>", 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
Loading