◐ Shell
clean mode source ↗

Issue 46108: Enum repr() incorrect when mixed with non-__new__ data types

Issue46108

Created on 2021-12-17 01:13 by ethan.furman, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (4)
msg408748 - (view) Author: Ethan Furman (ethan.furman) * (Python committer) Date: 2021-12-17 01:13
from dataclasses import dataclass
from enum import Enum

@dataclass
class Foo:
    a: int = 0

class Entries(Foo, Enum):
    ENTRY1 = Foo(1)

repr(Entries.ENTRY1) != '<Entries.ENTRY1: Foo(a=1)>'
msg408756 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-12-17 07:57
I know you know this, but here's a version without dataclasses, in case you want to add a test for this, too.

from enum import Enum

class Foo:
    def __init__(self, a):
        self.a = a
    def __repr__(self):
        return f'Foo(a={self.a!r})'

class Entries(Foo, Enum):
    ENTRY1 = Foo(1)

repr(Entries.ENTRY1) != '<Entries.ENTRY1: Foo(a=1)>'
msg408775 - (view) Author: Ethan Furman (ethan.furman) * (Python committer) Date: 2021-12-17 13:15
Thanks, test added.  I also updated the title.

Code updated to treat any __repr__s as affecting the display of the member value instead of the member itself (i.e. the "<...: %r>" portion).  if a user actually wants to change the member repr they can assign it when creating the Enum:

    class Entries(Foo, Enum):
        ENTRY = 1
        __repr__ = Foo.__repr__

    assert repr(Entries.ENTRY1) == 'Entries(a=1)'
msg410806 - (view) Author: Ethan Furman (ethan.furman) * (Python committer) Date: 2022-01-17 16:59
Fixed in 3.11.
History
Date User Action Args
2022-04-11 14:59:53adminsetgithub: 90266
2022-01-17 16:59:39ethan.furmansetstatus: open -> closed
superseder: Enum: modify __repr__, __str__; update docs
messages: + msg410806

type: behavior
resolution: fixed
stage: resolved

2021-12-17 13:15:01ethan.furmansetmessages: + msg408775
title: Enum repr() incorrect when mixed with dataclasses -> Enum repr() incorrect when mixed with non-__new__ data types
2021-12-17 07:57:00eric.smithsetnosy: + eric.smith
messages: + msg408756
2021-12-17 01:13:16ethan.furmancreate