serde icon indicating copy to clipboard operation
serde copied to clipboard

Support typing module

Open rossmacarthur opened this issue 5 years ago • 2 comments

From #119

rossmacarthur avatar Feb 08 '20 10:02 rossmacarthur

Supporting the typing module for assigning fields has now made it impossible to practically type hint your models, meaning that you can't really get any sort of autocomplete.

Is there another way?

vyrzdev avatar Dec 01 '20 12:12 vyrzdev

Not right now unfortunately. Basically what I really want to do is to make specifying field types using type annotations a first class thing like pydantic does. However, I still want to preserve the ability to add extra validation etc and have custom fields. So I think this is going to entail multiple things:

  • Converting or using type annotations as fields. I tried something like this on an old branch here.
  • Type annotating the serde package. We might be able to get away with just type annotating the public API.
  • Depending on the chosen API we might have to build a mypy plugin to recognize serde fields as particular types.

Examples

Basic

from datetime import date
from serde import Model, fields
from typing import Optional

class Artist(Model):
    name: str

class Album(Model):
    title: str
    release_date: Optional[date]
    artist: Artist

# this following behaves the same as before
album = Album(
    title='Dangerously in Love',
    release_date=date(2003, 6, 23),
    artist=Artist(name='Beyoncé')
)
album.to_dict()
album.to_json()

# not sure what these would be but likely a still serde field instance
assert isinstance(Album.__fields__.title, fields.Str)

With extra validation

from serde import Model, field, validators

class Example(Model):
    field: str = field(validators=[validators.LengthMin(1)])
               # ^ would need a mypy plugin for this

rossmacarthur avatar Dec 02 '20 08:12 rossmacarthur