正确向后移植通用集合

发布于 2025-01-15 05:13:20 字数 759 浏览 4 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

罪#恶を代价 2025-01-22 05:13:20

似乎有些 linter 例如 mypy 不喜欢上面的代码。特别是,mypy 抱怨即使 collections.abc.Sequencetyping.Sequence 不同,也使用了重复的基类。看来正确的解决方法是为较低版本实际子类 typing.Sequence

import collections.abc
import sys

if sys.version_info < (3, 9):
    from typing import Sequence
else:
    from collections.abc import Sequence


class MySequence(Sequence[T]):
    ...


# For `isinstance` checks at runtime.
if sys.version_info < (3, 9):
    collections.abc.Sequence.register(MySequence)

It seems some linters such as mypy do not like the above code. In particular, mypy complains that duplicate base classes are used even though collections.abc.Sequence is not the same as typing.Sequence. It seems the correct fix is to actually subclass typing.Sequence for lower versions.

import collections.abc
import sys

if sys.version_info < (3, 9):
    from typing import Sequence
else:
    from collections.abc import Sequence


class MySequence(Sequence[T]):
    ...


# For `isinstance` checks at runtime.
if sys.version_info < (3, 9):
    collections.abc.Sequence.register(MySequence)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文