justanr / marshmallow-annotations

Allows declaring marshmallow schema through type annotations
MIT License
48 stars 12 forks source link

A way to build from classes using annotations to declare instance members #1

Closed justanr closed 6 years ago

justanr commented 6 years ago

Originally filed by @Diaoul on marshmallow-code/marshmallow#773

@deckar01 thought it might be a better fit for this project

justanr commented 6 years ago

Thoughts. Given the following class:

from typing import List, Optional

class SomeEntity:
    ids: List[int]
    frob: Optional[str]  # actually Union[str, None] under the hood

generate the following schema fields:

from marshmallow import fields

{
    'ids': fields.List(fields.Integer()),
    'frob': fields.String(missing=None, required=False)
}

But how could we handle something like:

class SomeOtherThing:
    entity: SomeEntity

My initial thought is some sort of registry that maps python types to Marshmallow fields:

registry = {
    int: fields.Integer,
    List: fields.List
}

And introduce some sort of abstraction between an entity and it's schema:

class SchemaFor(Generic[T]):
    def __init__(self, schema):
        self.schema = schema

    def __call__(self, **kwargs):
        # hook into marshmallow registry to get the schema
        return schema(**kwargs)

Pros:


def register_annotation_field(type, field):
    ...

register_annotation_field(Enum, marshmallow_enum.EnumField)

Cons:

other thoughts: How does marshmallow-sqlalchemy handle this?