From 1b39b2047988eaef6c0556b3bbd9f7f218a028a1 Mon Sep 17 00:00:00 2001 From: Shengyu Zhang Date: Wed, 17 Jan 2024 04:28:22 +0800 Subject: [PATCH] Use ``repr()`` when an enum has a custom ``__repr__()`` (#11879) Co-authored-by: Adam Turner <9087854+aa-turner@users.noreply.github.com> --- CHANGES.rst | 2 ++ sphinx/util/inspect.py | 2 ++ tests/test_util_inspect.py | 11 +++++++++++ 3 files changed, 15 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 96625202f..9381798d7 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -21,6 +21,8 @@ Features added Patch by Bénédikt Tran. .. _``: 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 ---------- diff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py index d61d5f064..c0166eb16 100644 --- a/sphinx/util/inspect.py +++ b/sphinx/util/inspect.py @@ -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: diff --git a/tests/test_util_inspect.py b/tests/test_util_inspect.py index 73f96562f..6ae6ac0a9 100644 --- a/tests/test_util_inspect.py +++ b/tests/test_util_inspect.py @@ -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