serde icon indicating copy to clipboard operation
serde copied to clipboard

Integration with mypy

Open radix opened this issue 5 years ago • 1 comments

I'm not sure if the serde field type annotations are compatible with MyPy. For example, with this code:

from serde import Model, fields
class Artist(Model):
    name: fields.Str()

Running mypy on the code gives the following result (in addition to an error about the fact that serde doesn't have a type definition module):

serdetest.py:7: error: Invalid type comment or annotation
serdetest.py:7: note: Suggestion: use fields.Str[...] instead of fields.Str(...)

So, on the surface, it seems that this library is incompatible with MyPy. Is this true, or is there a way to get them to work together?

radix avatar Nov 23 '19 18:11 radix

Hi @radix at the moment typing annotations are not supported. However, there is support for plain types which is supported by MyPy. Any of these types will be automatically converted to serde field objects.

import datetime
import uuid
from serde import Model
class Artist(Model):
    id: uuid.UUID
    name: str
    birthday: datetime.date

See the following for a list of types that are supported like this:

https://github.com/rossmacarthur/serde/blob/ad6d24b632825e7ab3c0505976b7f09219a98c4a/src/serde/fields.py#L1308-L1331

In the future I want to make this library automatically convert typing objects to serde field objects. So that you could do something like:

from serde import Model
from typing import List, Tuple

class Example(Model):
    things: List[Tuple[str, int, str]]

rossmacarthur avatar Nov 24 '19 16:11 rossmacarthur