如何正确地向pythonmixin添加类型注释? 代码设置
我有以下类,我想使用mixin插入一个新功能:如何正确地向pythonmixin添加类型注释? 代码设置,python,mixins,type-hinting,Python,Mixins,Type Hinting,我有以下类,我想使用mixin插入一个新功能: class InputCollection(StringReprMixin, AbstractVariableCollection): def __init__(self, data: Optional[ValidInputCollection]): super().__init__() # rest of the code 这是我使用以下协议实现的Mixin: class StringReprMixin:
class InputCollection(StringReprMixin, AbstractVariableCollection):
def __init__(self, data: Optional[ValidInputCollection]):
super().__init__()
# rest of the code
这是我使用以下协议实现的Mixin:
class StringReprMixin:
def __str__(self: HasEmptyProtocol) -> str:
if self.empty:
return "Empty collection."
else:
return _collection_to_string(self)
HasEmptyProtocol
用于启用mypy检查程序,以确保mixin具有empty
属性。\u collection\u to\u string
函数具有以下签名:
CollectionType = Union[InputCollection, OutputCollection, ExpressionCollection]
def _collection_to_string(collection: CollectionType):
# rest of function code
问题
我不知道如何在调用StringReprMixin
函数中的\u collection\u to\u string
时正确检查mypy,因为mypy检查器认为self是HasEmptyProtocol
的实例,而不是CollectionType
中的任何类
这是静态检查器引发的错误:
“\u集合\u到\u字符串”的参数1具有不兼容的类型“HasEmptyProtocol”;应为“Union[InputCollection,OutputCollection,ExpressionCollection]”
我试过的
我见过一些问题,特别是其中一个似乎有效。然而,对我来说,在Mixin中使用类属性违背了mypy文档所建议的协议子类的目的
什么对我有用
在调用\u collection\u to\u string
之前,我对InputCollection
实例执行了一次操作:
class StringReprMixin:
def __str__(self: HasEmptyProtocol) -> str:
if self.empty:
return "Empty collection."
else:
if TYPE_CHECKING:
self = cast(CollectionType, self)
return __collection_to_string(self)
然而,我不知道这是否是处理带有类型注释的Mixin内部实例引用的正确方法
最后一个问题是:
这是注释这种混合的正确方法吗?