Skip to content

Per-field serializers and deserializers

Open
Overdue by 3 year(s)
Due by March 1, 2022
Last updated Nov 28, 2021
0% complete

Setting a tentative due date, as I'm not sure how much effort this will take.

Essentially, I want to enable the usage of per-field serializer and deserializer functions. In theory, this means that user-defined transform functions can be specified for each dataclass field, for fine-grained control over how that field value is de-serialized to a Python type, and how it is serialized to a JSON string or a dict object.

For example, the below syntax (mostly pseudocode) is the simplest usage of what I had in mind:

@dataclass
class Example:
    my_date_field: datetime = field(metadata={
       'deserializer': lambda o: datetime.strptime("my-date-time-format"),
       'serializer': lambda o: o.strftime("my-target-date-string-format"),
    })

Though, I also had another idea, which is to create custom functions like Serializer and Deserializer, and let the user specify them as an extra in the Annotated[T, extra...] form, as shown below:

from typing_extensions import Annotated


@dataclass
class Example:
    my_date_field: Annotated[
        datetime, Serializer(
            lambda o: o.strftime("my-target-date-string-format"))
    ]

List view

    There are no open issues in this milestone

    Add issues to milestones to help organize your work for a particular release or project. Find and add issues with no milestones in this repo.