[Python-ideas] Re: Make dataclass aware that it might be used with Enum

2022-07-07 Thread Steve Jorgensen
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)
___
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/G2VALQ4RIVFKIOKVW4XZAHZMLSZWL2XS/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Make dataclass aware that it might be used with Enum

2022-07-07 Thread Steve Jorgensen
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]: 

Actually, maybe these are fundamentally incompatible? `@dataclass` is a 
decorator, so it acts on the class after it was already defined, but `Enum` 
acts before that when `@dataclass` cannot have not generated the `__init__` 
yet. Right?
___
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/T775WMOLR6TNOXDAU37ZA2FKQB3SMJT6/
Code of Conduct: http://python.org/psf/codeofconduct/