Open bdoms opened 2 weeks ago
If additional options are being considered for msgspec.structs.asdict
: Given that the fields in a struct have a "real" name (name
), but can also have a different name used for encoding/decoding (encode_name
), another useful option would be a flag to choose between using the "real" field names as dict keys (which is what asdict
does currently, so should be the default), or the "encode" names.
Description
Imagine that I have a user being created from a web form, and it's defined like:
Now, I don't need to do much data manipulation before saving this to the database via my ORM. But I do need to hash the password first, and in fact I'm storing both that and the email in a different schema and table just to be safe. Currently I have to do something like:
That's not the end of the world for small numbers of fields, but it can get much worse and very cumbersome to manage if there are lots of fields being split into many different places. And sometimes forgetting a
del
can be catastrophic.Other frameworks like Pydantic solve this by having both
inclulde
andexclude
lists as options: https://docs.pydantic.dev/2.9/api/base_model/#pydantic.BaseModel.model_dumpI think msgspec getting a similar feature would be highly useful:
Note that this may be related to https://github.com/jcrist/msgspec/issues/199 depending on whether or not setting the
private=True
flag being talked about over there would effect the behavior ofasdict()
. Personally, I'd prefer keeping them separate since when I'm callingasdict
it's usually with a completely different intention than encode/decode.