mirror of
https://github.com/python/cpython.git
synced 2025-08-04 00:48:58 +00:00
gh-94943: [Enum] improve repr() when inheriting from a dataclass (GH-99740)
Co-authored-by: C.A.M. Gerlach <CAM.Gerlach@Gerlach.CAM>
This commit is contained in:
parent
5da5aa4c3e
commit
679efbb080
5 changed files with 102 additions and 4 deletions
|
@ -2717,17 +2717,67 @@ class TestSpecial(unittest.TestCase):
|
|||
|
||||
def test_repr_with_dataclass(self):
|
||||
"ensure dataclass-mixin has correct repr()"
|
||||
from dataclasses import dataclass
|
||||
@dataclass
|
||||
#
|
||||
# check overridden dataclass __repr__ is used
|
||||
#
|
||||
from dataclasses import dataclass, field
|
||||
@dataclass(repr=False)
|
||||
class Foo:
|
||||
__qualname__ = 'Foo'
|
||||
a: int
|
||||
def __repr__(self):
|
||||
return 'ha hah!'
|
||||
class Entries(Foo, Enum):
|
||||
ENTRY1 = 1
|
||||
self.assertTrue(isinstance(Entries.ENTRY1, Foo))
|
||||
self.assertTrue(Entries._member_type_ is Foo, Entries._member_type_)
|
||||
self.assertTrue(Entries.ENTRY1.value == Foo(1), Entries.ENTRY1.value)
|
||||
self.assertEqual(repr(Entries.ENTRY1), '<Entries.ENTRY1: Foo(a=1)>')
|
||||
self.assertEqual(repr(Entries.ENTRY1), '<Entries.ENTRY1: ha hah!>')
|
||||
#
|
||||
# check auto-generated dataclass __repr__ is not used
|
||||
#
|
||||
@dataclass
|
||||
class CreatureDataMixin:
|
||||
__qualname__ = 'CreatureDataMixin'
|
||||
size: str
|
||||
legs: int
|
||||
tail: bool = field(repr=False, default=True)
|
||||
class Creature(CreatureDataMixin, Enum):
|
||||
__qualname__ = 'Creature'
|
||||
BEETLE = ('small', 6)
|
||||
DOG = ('medium', 4)
|
||||
self.assertEqual(repr(Creature.DOG), "<Creature.DOG: size='medium', legs=4>")
|
||||
#
|
||||
# check inherited repr used
|
||||
#
|
||||
class Huh:
|
||||
def __repr__(self):
|
||||
return 'inherited'
|
||||
@dataclass(repr=False)
|
||||
class CreatureDataMixin(Huh):
|
||||
__qualname__ = 'CreatureDataMixin'
|
||||
size: str
|
||||
legs: int
|
||||
tail: bool = field(repr=False, default=True)
|
||||
class Creature(CreatureDataMixin, Enum):
|
||||
__qualname__ = 'Creature'
|
||||
BEETLE = ('small', 6)
|
||||
DOG = ('medium', 4)
|
||||
self.assertEqual(repr(Creature.DOG), "<Creature.DOG: inherited>")
|
||||
#
|
||||
# check default object.__repr__ used if nothing provided
|
||||
#
|
||||
@dataclass(repr=False)
|
||||
class CreatureDataMixin:
|
||||
__qualname__ = 'CreatureDataMixin'
|
||||
size: str
|
||||
legs: int
|
||||
tail: bool = field(repr=False, default=True)
|
||||
class Creature(CreatureDataMixin, Enum):
|
||||
__qualname__ = 'Creature'
|
||||
BEETLE = ('small', 6)
|
||||
DOG = ('medium', 4)
|
||||
self.assertRegex(repr(Creature.DOG), "<Creature.DOG: .*CreatureDataMixin object at .*>")
|
||||
|
||||
def test_repr_with_init_data_type_mixin(self):
|
||||
# non-data_type is a mixin that doesn't define __new__
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue