Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serialization/Deserialization enable custom validator method #1840

Open
munemolx opened this issue Jan 4, 2024 · 0 comments
Open

Serialization/Deserialization enable custom validator method #1840

munemolx opened this issue Jan 4, 2024 · 0 comments

Comments

@munemolx
Copy link

munemolx commented Jan 4, 2024

in default function, you expect that always we will need to validate the data o instance of type t.
but we might have cases where we also need to have more than type instance type validation, for example, in my case I want to serialize all dataclasses.dataclass to a dict using dataclasses.asdict.
So recommend adding the following enhancements to the register_type method .

def register_type(
    t: type[T],
    marker: str,
    encoder: Callable[[T], EncodedT],
    decoder: Callable[[EncodedT], T],
    validator: Optional[Callable[[T], bool]] = None
):
    """Add support for serializing/deserializing native python type."""
    _encoders[t] = (marker, encoder, validator)
    _decoders[marker] = decoder

  def default(self, o):
        reducer = getattr(o, "__json__", None)
        if reducer is not None:
            return reducer()

        if isinstance(o, textual_types):
            return str(o)

        for t, (marker, encoder, validator) in _encoders.items():
            if validator and validator(o):
                return _as(marker, encoder(o))
            if isinstance(o, t):
                return _as(marker, encoder(o))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant