如何使用超类调用键入Python mixin?

时间:2019-07-11 00:07:02

标签: python python-3.x mypy

我正在尝试在项目中使用FieldMixin from this answer,但是我无法使其通过mypy检查。当前代码:

class DynamicFieldsMixin(Serializer):
    context: Dict[str, Any]

    def get_field_names(
        self, declared_fields: OrderedDict, info: FieldInfo
    ) -> Set[str]:
        field_names: Set[str] = self.context.get(
            "fields",
            super().get_field_names(declared_fields, info)
        )
        return field_names

rest_framework.serializers.Serializer继承似乎很奇怪,我想知道是否有办法避免这种情况,因为它是要混入实际的Serializer类中的。仅删除超类会导致以下错误:

  

错误:超类中未定义“ get_field_names”

mypy配置:

[mypy]
check_untyped_defs = true
disallow_untyped_defs = true
ignore_missing_imports = true
no_implicit_optional = true
warn_redundant_casts = true
warn_return_any = true
warn_unused_ignores = true

1 个答案:

答案 0 :(得分:2)

仅出于类型检查的目的,您可以引入基类:

import typing
from typing import Any, Dict, List, Mapping, TypeVar
from rest_framework.fields import Field
from rest_framework.serializers import ModelSerializer
from rest_framework.utils.model_meta import FieldInfo


if typing.TYPE_CHECKING:
    _Base = ModelSerializer
else:
    _Base = object


class DynamicFieldsMixin(_Base):
    context: Dict[str, Any]

    def get_field_names(self, declared_fields: Mapping[str, Field], info: FieldInfo) -> List[str]:
        field_names = super().get_field_names(declared_fields, info)
        # Revealed type is 'builtins.list[builtins.str]'
        reveal_type(field_names)
        return field_names