Python:将类型提示与注释一起使用



在Python中,我们都知道类型提示,它从2015年开始可用:

def greet(name: str) -> str:
return "Hello, " + name

我们也知道函数注释,特别是这里我指的是文本注释,比如:

def greet(name: "The name of the person to greet") -> str:
return "Hello, " + name

但是是否可以将类型提示与文本函数注释一起使用

例如:

def greet(name: str, "The name of the person to greet") -> str:
return "Hello, " + name

最后一个抛出了一个错误。

我似乎在PEP或Python文档中找不到任何关于这是否可能的来源。虽然我没有特别深入地搜索,但我仍然希望能找到潜在答案。

由于注释可以是任何表达式(就Python解释器而言(,因此从技术上讲,您可以使用元组作为注释:

def greet(name: (str, "The name of the person to greet")) -> str:
return "Hello, " + name

它显示在函数的注释dict中,正如您所期望的那样:

>>> greet.__annotations__
{'name': (<class 'str'>, 'The name of the person to greet'), 'return': <class 'str'>}

然而,只有当您拥有知道其含义的工具时,这才是有用的。据我所知,现有的静态类型检查器、linter、文档生成器等都无法识别类型和描述的元组注释。

实际上,我建议只使用类型的注释,因为这绝大多数是标准用法,并使用注释或文档字符串来获取更多信息。

正如Samwise所说,类型检查器不会理解注释是否是类型和描述的元组(或您希望附加的任何其他元数据(。PEP 593–灵活的函数和变量注释通过以下方式准确地解决了这一问题:

from typing import Annotated
@dataclass
class Description:
x: str
def greet(name: Annotated[str, Description("The name of the person to greet")]) -> str:
return "Hello, " + name

我们引入包装类Description的原因是,很明显,编写的字符串是我们使用的描述,因此其他分析注释的库在将str用于自己的元数据时不会混淆。

然后,每次键入。带注释的,您可以在运行时使用typing.get_type_hints(name, include_extras=True)来获取描述。

最新更新