msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

Separate encoding/decoding options from class-specific options

Open petergaultney opened this issue 6 months ago • 0 comments

Description

I'm used to attrs+cattrs. I define attrs classes as a basic schema, and then I encode (unstructure) and decode (structure) those objects to/from builtin types (or JSON, or whatever) with different sorts of encoders (converters) depending on my use case.

For instance, when encoding an object to send to a database, I may choose to omit the defaults since the database knows about NULL already and can fill those in. Or if I'm communicating with another machine that has the same schema - no need to serialize a bunch of default values. But in other cases, it's important to me to represent all values - maybe in JSON across an API, for instance, where the API has no notion of a default value.

I'd like to be able to reuse a class definition for this, and do something like msgpsec.json.encode(my_obj, omit_defaults=True) - but msgspec requires that this be configured one way or the other on the class.

The class definition would otherwise be identical - I suppose I could copy-paste the class definition, but this gets very awkward to keep in sync, and even more so if there are methods on the class.

I feel like somebody must have suggested this before I have, but I didn't find any issue titles that seemed like the same request.

petergaultney avatar May 23 '25 02:05 petergaultney