我如何在 python mixins 中打字?

问题描述 投票:0回答:0
  • 我有一个 mixin,它将始终与特定类型的类一起使用,即
    widgets.Input
  • 的子类
  • 我想使用 mixin 覆盖一些方法,我在我的自定义方法中引用
    widgets.Input
    上存在的属性

我如何告诉 python 类型系统这个 mixin 扩展了

widgets.Input
接口而不继承
widgets.Input

奖励: 我可以告诉类型系统这个 mixin 只能与

widgets.Input
的子类一起使用吗?

from django.forms import widgets


class MaskedWidgetMixin:
    def format_value(self, value):
        return ""

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)  # <--- super().get_context does not exist
        context["widget"]["attrs"] = self.build_attrs(self.attrs, attrs, value)  # <--- self.attrs does not exist
        return context

    def build_attrs(self, base_attrs, extra_attrs=None, value: str = ""):
        attrs = super().build_attrs(base_attrs, extra_attrs)  # <--- super().build_attrs does not exist
        if value:
            attrs.update({"placeholder": "* ENCRYPTED *", "required": False})
        return attrs


class EncryptedTextInputWidget(MaskedWidgetMixin, widgets.TextInput):
    pass


class EncryptedTextareaWidget(MaskedWidgetMixin, widgets.Textarea):
    pass

更新

如评论中所建议,我尝试定义一个

Protocol
.
然而,这并不是
Protocol
.
的确切目的 相反,
Protocol
定义了一个由扩展它的类实现的接口。

以下代码会产生这种类型的错误...

Class derives from one or more protocol classes but does not implement all required members
  Member "attrs" is declared in protocol class "InputProtocol"
class InputProtocol(Protocol):
    attrs: dict[str, Any]

    def get_context(self, name, value, attrs) -> dict[str, dict[str, Any]]:
        ...

    def build_attrs(self, base_attrs, extra_attrs=None) -> dict[str, Any]:
        ...


class MaskedWidgetMixin(InputProtocol):
    ...
python django mypy python-typing
© www.soinside.com 2019 - 2024. All rights reserved.