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?
This scenario is exactly what enums are made for.
>>> from enum import Enum
>>> class Material(Enum):
...     gold = 1
...     silver = 2
...     platinum = 3
...
>>> Material.diamond
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\...\enum.py", line 341, in __getattr__
    raise AttributeError(name) from None
AttributeError: diamond
>>> Material.gold
<Material.gold: 1>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With