如何正确地对字符串列表进行注释/键入提示

2024-05-23 19:54:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图弄清楚如何正确地对字符串列表进行函数注释或键入提示。例如,如果我有这样一个函数:

def send_email(self, from_address: str, to_addresses: list[str]):
    pass

to_addresses应该是字符串列表。但是,当我尝试使用该注释时,我的Python 3.4.3解释器中出现以下错误:

TypeError: 'type' object is not subscriptable

我肯定是list[str]导致了问题,因为如果我将其更改为str,错误就会消失,但这并不能正确反映我对参数的意图


Tags: to函数字符串fromselfsend列表键入
3条回答

此语法现在在Python 3.9+中有效:

In type annotations you can now use built-in collection types such as list and dict as generic types instead of importing the corresponding capitalized types (e.g. List or Dict) from typing.

但是,在3.9之前,您需要使用导入的Listin Python 3.7+来添加

from __future__ import annotations

在文件顶部,允许使用list[int](例如)

Python3.4没有为其函数注释指定格式,它只提供了一种机制,允许您使用任何表达式作为注释。如何解释注释取决于您和您使用的库

Python 3.5标准化了函数注释用于类型暗示的方式,如PEP 484中所述。要注释字符串列表,可以使用List[str],其中List是从typing模块导入的。如果函数接受任何类似列表的序列,也可以使用Sequence[str],或者对任何iterable使用Iterable[str]

从Python 3.9开始,您可以使用list[str]作为类型注释,而不需要导入任何内容

在Python3.9+中,list(带有小写的l)可以用于类型注释,并且代码应该按原样工作。在较早版本的Python上,您需要导入^{}并使用它

from typing import List

to_addresses: List[str]

请注意大写字母L

你可能想考虑一些更具体的事情。为什么from_addressstr,而to_addresseslist[str]?也许是

import typing
Address = typing.NewType("Address")

会有帮助的

相关问题 更多 >