Use `repr() when an enum has a custom __repr__()` (#11879)

Co-authored-by: Adam Turner <9087854+aa-turner@users.noreply.github.com>
This commit is contained in:
Shengyu Zhang 2024-01-17 04:28:22 +08:00 committed by GitHub
parent 9c59a6ea84
commit 1b39b20479
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 15 additions and 0 deletions

View File

@ -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
----------

View File

@ -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:

View File

@ -667,6 +667,17 @@ def test_object_description_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