小编Mar*_*ost的帖子

用户定义的泛型类型和collections.abc

我有一个Python包,它基于collections.abc(Mapping,Sequence等)提供的ABC定义了各种集合.我想利用Python 3.5中引入的类型提示功能,但我怀疑最好的方法是什么.

让我们以其中一个类为例; 到现在为止,我有类似这样的东西:

from collections.abc import Mapping

class MyMapping(Mapping):
    ...
Run Code Online (Sandbox Code Playgroud)

要将其转换为泛型类型,文档建议执行以下操作:

from typing import TypeVar, Hashable, Mapping

K = TypeVar("K", bound=Hashable)
V = TypeVar("V")

class MyMapping(Mapping[K, V]):
    ...
Run Code Online (Sandbox Code Playgroud)

但这会带来两个问题:

  • 该类丢失了collections.abc.Mapping中的所有mixin方法.我可以自己处理这个实现它们,但这首先会破坏使用ABCs的部分目的.

  • isinstance(MyMapping(), collections.abc.Mapping)返回False.此外,尝试调用collections.abc.Mapping.register(MyMapping)解决此问题会引发RuntimeError("拒绝创建继承循环").

我解决这些问题的第一个尝试是回到扩展collections.abc.Mapping:

from typing import TypeVar, Hashable
from collections.abc import Mapping

K = TypeVar("K", bound=Hashable)
V = TypeVar("V")

class MyMapping(Mapping[K, V]):
    ...
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为collections.abc.Mapping不是泛型类型,并且不支持订阅运算符.所以我尝试了这个:

from typing import TypeVar, Hashable, Mapping …
Run Code Online (Sandbox Code Playgroud)

python generics type-hinting python-3.x

11
推荐指数
1
解决办法
798
查看次数

标签 统计

generics ×1

python ×1

python-3.x ×1

type-hinting ×1