Opinions: Dataclasses or Pydantic model base?
Opinions: Dataclasses or Pydantic model base?
Opinions: Dataclasses or Pydantic model base?
Keep it simple, stupid.
I'd use the built-in dataclass (or something even simpler) where possible. Only when I need more functionalities (e.g. validation) would I switch to using Pydantic model.
For validation and/or (de)serialization: pydantic.
Otherwise, dataclasses.
I also like to replace tuples with NamedTuple, but I tend to use tuples a lot in the first place. It’s generally recommended to use dataclasses instead if you don’t specifically need tuple-like behavior.
Oh btw there are three choices, not two.
pydantic underneath (pydantic-base) is written in Rust. fastapi is fast cuz of pydantic. fastapi is extremely popular. Cuz it's right there in the word, fast. No matter how crap the usability is, the word fast will always win.
If fastapi is fast then whatever is not fastapi is slow. And there is no convincing anyone otherwise so lets not even try.
Therefore lets do fast. Cuz we already agreed slow would be bad.
normal dataclasses is not fast and therefore it's bad. If it had a better marketing team this would be a different conversation.
SQLModel combines pydantic and SQLAlchemy.
At first i feel in love with the SQLModel docs. Then realized the eye wateringly beautiful docs are missing vital details, such as how to:
cls.__name__.lower()
#2 is particularly nasty. SQLModel.new implementation consists of multiple metaclasses. So subclasses always inherit that worthless tablename implementation. And SQLAlchemy applies three decorators, so figuring out the right witchcraft to create the Descriptor is near impossible. pydantic doesn't support overriding tablename
Then i came along
After days of, lets be honest, hair loss and bouts of heavy drinking, posted the answer here.
Required familiarity with pydantic, sqlalchemy, and SQLModel.
Depends on what you are trying to accomplish, pydantic is great for encoding/decoding
If you don't need that go with dataclasses
I was going to comment this too