Python / Django-Mypy:表达式的类型为“ Type [ModelInstance]”,变量的类型为“ ModelInstance”

时间:2019-10-25 10:24:43

标签: python django mypy

我正在开发一个为前端提供GraphQL api的Django应用。我正在使用mypy进行类型检查,并且在运行mypy时遇到了我不理解的错误

运行时出现以下错误:

api/schema.py:50: error: Incompatible types in assignment (expression has type "Type[Academy]", variable has type "Academy")
api/schema.py:57: error: Incompatible types in assignment (expression has type "Type[School]", variable has type "School")
api/schema.py:64: error: Incompatible types in assignment (expression has type "Type[AcademyGroup]", variable has type "AcademyGroup")

这是mypy正在检查的代码

class AcademyType(DjangoObjectType):
    class Meta:
        model: Academy = Academy
        filter_fields: List[str] = ['name', 'domain', 'slug']
        interfaces: Tuple = (relay.Node,)


class SchoolType(DjangoObjectType):
    class Meta:
        model: School = School
        filter_fields: List[str] = ['name', 'academy']
        interfaces: Tuple = (relay.Node,)


class AcademyGroupType(DjangoObjectType):
    class Meta:
        model: AcademyGroup = AcademyGroup
        filter_fields: List[str] = ['name', 'academy']
        interfaces: Tuple = (relay.Node,)

因此不断失败的行是model: AcademyGroup = AcademyGroup上的变体,但这只是在我的代码中不断出现的“ Django模型为类型”定义(似乎并没有产生错误)

因此,我不确定自己在做什么错,因此我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

您的model属性的类型不是类本身,而是Type。确实,如果您说model = Academy,则model的类型为type(model) == type(Academy) == Type,实际上,Academy not Academy < em> object ,它是对类的引用,此类的类型是Type的(子类)。您还可以使用Type[…] [python-doc]来指定类型的(base-)类,因此Type[C]表示它是CC的子类的类型:

因此,您应该将其注释为:

from typing import Type

class AcademyType(DjangoObjectType):
    class Meta:
        model: Type[Academy] = Academy
        filter_fields: List[str] = ['name', 'domain', 'slug']
        interfaces: Tuple = (relay.Node,)


class SchoolType(DjangoObjectType):
    class Meta:
        model: Type[School] = School
        filter_fields: List[str] = ['name', 'academy']
        interfaces: Tuple = (relay.Node,)


class AcademyGroupType(DjangoObjectType):
    class Meta:
        model: Type[AcademyGroup] = AcademyGroup
        filter_fields: List[str] = ['name', 'academy']
        interfaces: Tuple = (relay.Node,)