如何使用超类调用键入 Python mixin? [英] How to type Python mixin with superclass calls?

查看:52
本文介绍了如何使用超类调用键入 Python mixin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的项目中使用 FieldMixin 这个答案,但是我无法让它通过 mypy 检查.当前代码:

I'm trying to use the FieldMixin from this answer in my project, but I'm having trouble getting it to pass mypy checks. The current code:

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 类中.只是删除超类会导致此错误:

Inheriting from rest_framework.serializers.Serializer seems weird, and I wonder if there's a way to avoid that, since it's meant to be mixed into actual Serializer classes. Just removing the superclass results in this error:

错误:get_field_names"在超类中未定义

error: "get_field_names" undefined in superclass

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

推荐答案

你可以只为了类型检查而引入基类:

You can introduce the base class for the sake of type checking only:

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

这篇关于如何使用超类调用键入 Python mixin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆