pyserde
pyserde copied to clipboard
serde transparently
After #255, type checking for deserialization is declared at the type level, not at deserialization invocation anymore, this leads to having no way to do type checking at a snippet like this (I actually have problem with msgpack
, but I use JSON since it's more popular):
from serde.json import from_json, to_json
int_json = to_json(1)
string_json = to_json("1")
print(f"{int_json=} {string_json=}")
print(f"{from_json(str, int_json)=} {from_json(int, string_json)=}")
One solution I'd like to propose is to have a transparent
attribute, similar to what the Rust crate serde
has (transparent) which allows creating wrapper around a type without requiring using the target format's container type. So we'd have something like
from serde import serde, Strict
from serde.json import from_json, to_json
@serde(transparent=True, type_check=Strict)
class StrictString:
value: str
int_json = to_json(1)
string_json = to_json("1")
from_json(str, string_json) # returns a normal str
from_json(StrictString, string_json) # returns a StrictString with value being "1"
from_json(StrictString, int_json) # raises SerdeError
Hi @uyha
Thanks for a proposal with good example! Yeah, It's nice to have transparent
feature.
Right now, I am working on a pretty big change https://github.com/yukinarit/pyserde/issues/237 right now (branch). I can take a look at this after that. Or If you're interested in contributing to pyserde, I am happy to assist you.
Awesome!
I think the implementation will be similar to flatten feature. you can find code serializing and serializing flatten here
- Serialize: https://github.com/yukinarit/pyserde/blob/03c0c1f5e1fd744e1cf3ad4dce3ce0e5278ecb20/serde/se.py#L815-L820
- Deserialize: https://github.com/yukinarit/pyserde/blob/03c0c1f5e1fd744e1cf3ad4dce3ce0e5278ecb20/serde/de.py#L819-L827
It's good to know how to see the generated code by
python -m serde.insepct {source} {class}
e.g. To see generated code for flatten example.
python -m serde.inspect examples/flatten.py Foo
sorry, I was using my work account to comment, so I removed that, I'll still keep working on a PR though.