正确向后移植通用集合
在 Python 3.9 中,现在可以将 collections.abc
与泛型一起使用,这意味着这样的代码是可能的:
import collections.abc
from typing import TypeVar
T = TypeVar("T")
class MySequence(collections.abc.Sequence[T]):
...
但是,在 Python 3.8 中,这是不可能的。相反,必须使用泛型的typing
模块。我想知道解决这个问题的正确方法是什么。现在我正在做以下事情:
import sys
from typing import TypeVar
T = TypeVar("T")
if sys.version_info < (3, 9):
import collections.abc, typing
class ABC_Sequence(collections.abc.Sequence, typing.Sequence[T]):
pass
else:
from collections.abc import Sequence as ABC_Sequence
class MySequence(ABC_Sequence[T]):
...
这是正确的方法吗?
In Python 3.9 it is now possible to use collections.abc
with generics, meaning code such as this is possible:
import collections.abc
from typing import TypeVar
T = TypeVar("T")
class MySequence(collections.abc.Sequence[T]):
...
In Python 3.8, however, this is not possible. Instead, one must use the typing
module for generics. I'm wondering what the proper way to go about this is. Right now I'm doing the following:
import sys
from typing import TypeVar
T = TypeVar("T")
if sys.version_info < (3, 9):
import collections.abc, typing
class ABC_Sequence(collections.abc.Sequence, typing.Sequence[T]):
pass
else:
from collections.abc import Sequence as ABC_Sequence
class MySequence(ABC_Sequence[T]):
...
Is this the proper way to go about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
似乎有些 linter 例如
mypy
不喜欢上面的代码。特别是,mypy
抱怨即使collections.abc.Sequence
与typing.Sequence
不同,也使用了重复的基类。看来正确的解决方法是为较低版本实际子类typing.Sequence
。It seems some linters such as
mypy
do not like the above code. In particular,mypy
complains that duplicate base classes are used even thoughcollections.abc.Sequence
is not the same astyping.Sequence
. It seems the correct fix is to actually subclasstyping.Sequence
for lower versions.