Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use repr when Enum has custom __repr__ impl #11879

Merged
merged 4 commits into from
Jan 16, 2024
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
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ Features added
Patch by Bénédikt Tran.

.. _`<search>`: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/search
* #11803: autodoc: Use an overriden ``__repr__()`` function in an enum,
if defined. Patch by Shengyu Zhang.

Bugs fixed
----------
Expand Down
2 changes: 2 additions & 0 deletions sphinx/util/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,8 @@ def object_description(obj: Any, *, _seen: frozenset = frozenset()) -> str:
return 'frozenset({%s})' % ', '.join(object_description(x, _seen=seen)
for x in sorted_values)
elif isinstance(obj, enum.Enum):
if obj.__repr__.__func__ is not enum.Enum.__repr__: # type: ignore[attr-defined]
return repr(obj)
return f'{obj.__class__.__name__}.{obj.name}'
elif isinstance(obj, tuple):
if id(obj) in seen:
Expand Down
11 changes: 11 additions & 0 deletions tests/test_util_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,17 @@ class MyEnum(enum.Enum):
assert inspect.object_description(MyEnum.FOO) == "MyEnum.FOO"


def test_object_description_enum_custom_repr():
class MyEnum(enum.Enum):
FOO = 1
BAR = 2

def __repr__(self):
return self.name

assert inspect.object_description(MyEnum.FOO) == "FOO"


def test_getslots():
class Foo:
pass
Expand Down