blhsing
(Ben Hsing)
15
Good example, allthough to be fair, this can be implemented without a metaclass since we now have __init_subclass__
:
from enum import Enum
from dataclasses import dataclass
from typing import dataclass_transform, Literal
@dataclass_transform()
class SlotDataclass:
def __init_subclass__(cls):
cls.__slots__ = tuple(vars(cls).get('__annotations__', {}))
dataclass(cls)
class Card(SlotDataclass):
value_: Literal[2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']
suite: Literal['heart', 'diamond', 'club', 'spade']
class PlayingCards(Card, Enum):
TWO_OF_HEART = 2, 'heart'
THREE_OF_SPADES = 3, 'spade'
so that:
print(list(PlayingCards))
outputs:
[PlayingCards(value_=2, suite='heart'), PlayingCards(value_=3, suite='spade')]
Demo here
Note that Enum
members already have a value
attribute so the value of a Card
has to be named something else.