
On 7/7/22 18:22, Steve Jorgensen wrote:
After some playing around, I figured out a pattern that works without any changes to the implementations of `dataclass` or `Enum`, and I like this because it keeps the 2 kinds of concern separate. Maybe I'll try submitting an MR to add an example like this to the documentation for `Enum`.
In [1]: from dataclasses import dataclass
In [2]: from enum import Enum
In [3]: @dataclass(frozen=True) ...: class CreatureDataMixin: ...: size: str ...: legs: int ...:
In [4]: class Creature(CreatureDataMixin, Enum): ...: BEETLE = ('small', 6) ...: DOG = ('medium', 4) ...:
In [5]: Creature.DOG Out[5]: Creature(size='medium', legs=4)
I'm impressed that you found a way to make it work. Be aware that some of the bug-fixing in 3.11 has changed the resulting repr() -- the above now looks like: <Creature.DOG: CreatureDataMixin(size='medium', legs=4)> It would be possible to have Enum check to see if the data type is a dataclass, and then see if the repr is set to be automatically created:
CreatureDataMixin.__dataclass_params__ _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=True)
I'll have to look into that. It does seem like a lot of extra work, or at least no less work, than just writing an `__init__` in the enum class directly. -- ~Ethan~