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



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

此外,某些抽象类型在typingcollections.abc中有两个版本,以Mapping为例:

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

According to The Zen of Python:

应该有一个——最好只有一个——很明显的方法。

我很困惑哪一个是最好的?

您应该使用set[str]样式的打字。查看PEP 585:

不赞成从键入中导入。由于PEP 563和最小化键入对运行时影响的意图,此弃用将不会生成DeprecationWarnings。相反,当被检查程序的目标版本被标记为Python 3.9或更新版本时,类型检查器可能会警告这种不赞成的用法。

所以从python的typing包中导入这些现在是不赞成的,理想情况下你不应该再使用它们了;但是,如果您需要向后兼容旧版本的python,则可以暂时使用它们。请注意,在5年内,你可能需要去更新你的代码库,因为你将需要python 3.9:

工具,包括类型检查器和检查器,必须适应将标准集合识别为泛型。

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

相关内容

最新更新