I want a field in a Python dataclass to only have certain possible values.
For instance, I want a Jewel dataclass, whose field material can only accept values "gold", "silver", and "platinum".
I came up with this solution:
@dataclass
class Jewel:
kind: str
material: str
def __post_init__(self):
ok_materials = ["gold", "silver", "platinum"]
if self.material not in ok_materials:
raise ValueError(f"Only available materials: {ok_materials}.")
So, Jewel("earrings", "silver") would be ok, whereas Jewel("earrings", "plastic") would raise a ValueError.
Is there a better or more pythonic way to achieve this? Maybe something that relies on features from dataclasses module?