On 7/6/22 17:01, Steve Jorgensen wrote:

> Perhaps, this has already been addressed in a newer release (?) but in Python 
3.9, making
> `@dataclass` work with `Enum` is a bit awkward.
>
> Currently, it order to make it work, I have to:
> 1. Pass `init=False` to `@dataclass` and hand-write the `__init__` method
> 2. Pass `repr=False` to `@dataclass` and use `Enum`'s representation or write 
a custom __repr__
>
> Example:
> In [72]: @dataclass(frozen=True, init=False, repr=False)
>      ...: class Creature(Enum):
>      ...:     legs: int
>      ...:     size: str
>      ...:     Beetle = (6, 'small')
>      ...:     Dog = (4, 'medium')
>      ...:     def __init__(self, legs, size):
>      ...:         self.legs = legs
>      ...:         self.size = size
>      ...:
>
> In [73]: Creature.Dog
> Out[73]: <Creature.Dog: (4, 'medium')>

So why use dataclass then?

class Creature(Enum):
    Beetle = (6, 'small')
    Dog = (4, 'medium')
    def __init__(self, legs, size):
        self.legs = legs
        self.size = size

and

>>> list(Creature)
[<Creature.Beetle: (6, 'small')>, <Creature.Dog: (4, 'medium')>]

>>> Creature.Beetle.size
'small'

>>> Creature.Beetle.legs
6

It looks like dataclass was just making you do a bunch of extra work.

--
~Ethan~
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/X5UCN42LFGSGISWD62SUP2BU4WDRGWDM/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to