3 ms·
Out of curiosity, why would I use Dataclass vs a Pydantic Basemodel. If we did not have a PyDantic dependency I could imagine wanting to use Dataclass. But if I
by whinvik 1y ago
Out of curiosity, why would I use Dataclass vs a Pydantic Basemodel. If we did not have a PyDantic dependency I could imagine wanting to use Dataclass. But if I have it, why not use everywhere?
- rsyring 1y agoTo help answer your question, here's a detailed comparison from the attrs project: https://www.attrs.org/en/stable/why.html https://www.attrs.org/en/stable/why.html There's some obvious potential for bias there, but I thought most of the arguments were well reasoned. Edit: found another that I thought was helpful: https://threeofwands.com/why-i-use-attrs-instead-of-pydantic/ https://threeofwands.com/why-i-use-attrs-instead-of-pydantic...
- intalentive 1y agoPerformance hit from data validation at construction time. I like msgspec which is much leaner and faster.
- lysecret 1y agoMain reason is (used to be) performance. But since pydantic 2.0 it’s not an issue anymore I default to use pydantic for everything.
- maleldil 1y agoUnnecessary baggage if you don't need validation or serialisation. My rule of thumb is to use Pydantic if I need serialisation, otherwise I default to dataclasses.
- globular-toast 1y agoThis and not just for the performance reasons. A Pydantic model represents an I/O boundary of a program. This conveys a lot of information to a programmer reading the code. It would be quite misleading to find it's actually only passed around internally and never used for I/O. A bit like using an int type to store a Boolean value. On the other hand if I see a dataclass I can tell what it's purpose is by whether it's frozen or not etc. Always strive for self-documenting code.
- adammarples 1y agoThe Chad answer is to use pydantic.dataclass
- afiodorov 1y agoMy rule of the thumb is that Dataclasses are for compile-time type-checking, pydantic classes are for run time type checking.
- tauroid 1y agoWhy would I use a Pydantic model when `TypeAdapter(MyDataclass)` exists?
- meander_water 1y agoOne explicit difference is that dataclasses don't support validating nested objects. I'd use it for passing flat structures as function args rather than a massive list of individual args.