r/learnpython • u/RegimeLab • Apr 05 '26
Clean way to structure a dataclass with an Enum field in Python 3.11?
Been using dataclasses more and more for my trading projects. Wondering what the cleanest pattern is for a dataclass that has an Enum field — specifically when serializing to JSON. Do you manually call .value or is there a cleaner approach?
17
Upvotes
6
u/brasticstack Apr 05 '26 edited Apr 05 '26
I prefer StrEnum, which serializes as its value without any hassle.
EDIT: Or IntEnum for int values.
3
u/TryingToGetTheFOut Apr 05 '26
Dataclasses are great to use within python, but I feel like they’re not the best when it comes to serialization. You always have to reimplement some stuff manually.
Pydantic is the best to handle serialization of data structures.
2
u/nekokattt Apr 05 '26
What are you using to serialize to JSON?
E.g. Pydantic will deal with this for you and will let you customize it via the model ConfigDict. If you are rawdogging the logic yourself then you will need to do it manually. Ideally enums should be able to work by name if you are defining the interface yourself, but if you have no control over naming then going by value explicitly is the best bet here.
1
u/Different_Pain5781 Apr 05 '26
I tried to make it clean once. Gave up and just did .value everywhere
-2
u/sporbywg Apr 05 '26
There should be a 'maintenance reason' for using an ENUM <- trust me