Skip to content

serde transparently #466

@uyha

Description

@uyha

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

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions