4 ms·
My general rule is, if I have a dict with a fixed set of keys, it should be a dataclass. Problem solved! Then if I need to send or receive it, it's an easy con
by claytonjy 3y ago
My general rule is, if I have a dict with a fixed set of keys, it should be a dataclass. Problem solved!
Then if I need to send or receive it, it's an easy conversion to a Pydantic BaseModel.
- smashed 3y agoAnd the dataclass serves as documentation for the available attributes and type safety.. It's really the way to go, takes a minute or two to define and saves so much headaches in the long run.
- behnamoh 3y agoCan dataclasses be serialized just as easily?
- paulddraper 3y agoYes via pickle. Or for JSON, dataclasses_json
- dharmab 3y agoBe aware that pickle is unsafe (as documented near the top of https://docs.python.org/3/library/pickle.html https://docs.python.org/3/library/pickle.html), so prefer other serialization formats except between trusted processes
- claytonjy 3y agoI can't remember the last time I _wanted_ to pickle something. Parquet and JSON pretty much cover it for me. I guess pickling made more sense before tools like Pydantic were good and popular? If I want all the python-specific nuance on disk, I know I'm in a bad place!
- nurettin 3y agoI use pickle to serialize RPC requests between internal services. Nothing beats it in terms of speed and ease of use.
- jammycrisp 3y agoYep! Both msgspec (https://jcristharif.com/msgspec/supported-types.html#dataclasses https://jcristharif.com/msgspec/supported-types.html#datacla...) and orjson support encoding dataclasses to JSON natively.
- jwestbury 3y agoIn addition to the already-mentioned suggestions, you can also use marshmallow schemas to serialise complex objects, and there's even a package to autogen marshmallow schemas from dataclasses: https://pypi.org/project/marshmallow-dataclass/ https://pypi.org/project/marshmallow-dataclass/
- Fatal1ty 3y ago[dead]
- rivepica 3y ago100%. I don’t understand the obsession with bending dicts into something they are inherently bad at when actual alternatives in dataclasses and Pydantic models right there.