我正在开发一个为前端提供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模型为类型'定义(似乎并没有产生错误)
因此,我不太确定自己在这里做错了什么,因此将不胜感激。
model
属性的类型不是类本身,而是Type
。确实,如果您说model = Academy
,则model
的类型是type(model) == type(Academy) == Type
,的确,Academy
是not和Academy
object,它是对类的引用,此类的类型是Type
的(子类)。您还可以使用Type[…]
[python-doc]指定类型的(base-)类,因此Type[…]
表示它是Type[C]
的类型,或者是C
的子类:
因此,您应将其注释为:
C