dataclasses-json icon indicating copy to clipboard operation
dataclasses-json copied to clipboard

`MyClass.schema()` returns `SchemaF[Any]`, providing no type safety, rather than `SchemaF[MyClass]`

Open andersk opened this issue 1 year ago • 0 comments

This should give a mypy error, but doesn’t:

from dataclasses import dataclass
from dataclasses_json import DataClassJsonMixin

@dataclass
class MyClass(DataClassJsonMixin):
    my_field: int

x: str = MyClass.schema().load({"my_field": 0})
print(x.lower())

In reality, of course, x is a MyClass, but mypy doesn’t know that.

That’s because of this incorrect usage of a generic type alias:

https://github.com/lidatong/dataclasses-json/blob/3264a0046e1aa3c0a813335286ebdbc651f58b13/dataclasses_json/mm.py#L223 https://github.com/lidatong/dataclasses-json/blob/3264a0046e1aa3c0a813335286ebdbc651f58b13/dataclasses_json/api.py#L78-L88

A type alias SchemaType = SchemaF[A] needs to be used as SchemaType[A], not SchemaType. The latter is interpreted as SchemaType[Any]. This is flagged by mypy with the disallow_any_generics option—there are many other mypy errors, but here are the ones about SchemaType:

dataclasses_json/mm.py:322: error: Missing type parameters for generic type "SchemaType"
dataclasses_json/mm.py:362: error: Missing type parameters for generic type "SchemaType"
dataclasses_json/api.py:88: error: Missing type parameters for generic type "SchemaType"

It looks like this was broken by 9092e6f91235ed2468a5e0476f4117586c117fba (#96) in the name of Python 3.6 compatibility. If there is a compatibility problem with old Python versions, a better workaround is to quote the annotation to prevent runtime evaluation: -> "SchemaType[A]".

andersk avatar Jul 13 '22 04:07 andersk