python 3.9 之后输入提示的最佳实践是什么?

ess*_*sse 6 python type-hinting python-3.x

python3.9之后,至少有三种方式使用输入提示。以内置集合set为例:

# way 1
def f(s: set[str]) -> str:
    pass

# way 2
def f(s: typing.Set[str]) -> str:
    pass

# way 3
def f(s: collections.abc.Set[str]) -> str:
    pass

# way 3': or arguable collections.abc.MutableSet vs collections.abc.Set
def f(s: collections.abc.MutableSet[str]) -> str:
    pass
Run Code Online (Sandbox Code Playgroud)

typing此外,对于某些抽象类型,和中有两个版本collections.abcMapping例如:

def f(m: typing.Mapping[str, int]) -> int:
    pass

def f(m: collections.abc.Mapping[str, int]) -> int:
    pass
Run Code Online (Sandbox Code Playgroud)

根据Python 之禅

应该有一种——最好只有一种——明显的方法来做到这一点。

我很困惑哪一个最好?

jos*_*nda 9

您应该使用set[str]打字风格。查看PEP 585

不推荐从输入中导入这些内容。由于 PEP 563 以及尽量减少输入对运行时影响的目的,此弃用不会生成 DeprecationWarnings。相反,当被检查程序的目标版本被标记为 Python 3.9 或更高版本时,类型检查器可能会警告此类已弃用的用法。

因此,从 python 的typing包中导入这些内容现在已被弃用,您最好不再使用它们;但是,如果您需要向后兼容旧版本的 python,您现在可以使用它们。请注意,5 年后您可能需要进入并更新您的代码库,因为您将需要 python 3.9:

必须调整工具(包括类型检查器和 linter)以将标准集合识别为泛型。

在源代码级别,新描述的功能需要 Python 3.9