为包含namedtup的列表键入提示

2024-06-26 14:10:10 发布

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

我读的是here,但它是关于namedtuples的类型暗示。在

是否可以为包含namedtupleList创建类型提示?在

例如:

firefoxprofile = namedtuple("Profile", ["Name", "Path", "isRelative", "Default"])

# Will contain a list of tuples that represent the firefox profiles.
ffprofiles = [] # -- how would I write the type hint?
ffprofiles.append(Profile(Name='Jason', Path='Profiles/er5rtak4.Jason', isRelative='1', Default=None))
ffprofiles.append(Profile(Name='Sarah', Path='Profiles/23mvfqcj.Sarah', isRelative='1', Default=None))

我试过了:

^{pr2}$

但这不起作用,当我试图用该语法更新ffprofiles = []行时,我得到一个异常:

TypeError: descriptor 'append' requires a 'list' object but received a 'Profile'

Tags: thepathnamenonedefault类型profileprofiles
1条回答
网友
1楼 · 发布于 2024-06-26 14:10:10

不需要拼出命名元组,只需引用List[]类型中类型的名称:

List[firefoxprofile]

在赋值中使用时,将类型提示放在冒号后面,但在PEP 526 Variable Annotations语法之后的=之前:

^{pr2}$

这会将ffprofiles设置为空列表,并告诉任何类型提示检查程序列表的内容必须是firefoxprofile类型的实例。如果您想在该列表中提供一些初始概要文件,只需将它们包含在列表文本中,之后不需要附加它们。在

您将namedtuple()生成的类赋给了名称firefoxprofile,这样其他代码就可以用来引用它了,而不是使用名称Profile。但是,您可能希望将namedtuple()结果赋给作为第一个参数传入的相同名称,所以Profile = namedtuple('Profile', ...)。在

但是,您可能还希望使用^{} class来定义您的类型化命名元组;您链接到的文章涵盖了这一点,但这里它应用于您的示例:

from typing import Optional, NamedTuple, List

class FirefoxProfile(NamedTuple):
    name: str
    path: str
    is_relative: bool
    default: Optional[str]

ffprofiles: List[FirefoxProfile] = [
    FirefoxProfile('Jason', 'Profiles/er5rtak4.Jason', True, None),
    # ... and more
]

定义一个属于typing.NamedTuple的子类的类与使用namedtuple()函数具有相同的结果,除了语法更加简洁,您可以为字段添加类型,还可以选择添加docstring和其他属性或方法(几乎所有不是类型暗示属性或namedtuple方法的都可以)。在

现在,类型暗示机器将知道更多关于预期的东西。现在不仅清楚列表将包含什么类型的实例,上面还记录了命名元组类支持哪些属性以及每个属性具有什么类型。我做了一些有根据的猜测,这些类型可能是什么。我还在这里使用Python的PEP-8样式约定来命名,因此命名的tuple属性都使用小写的_加下划线(“snake_case”)而不是CamelCase。后者实际上应该只用于类名。在

相关问题 更多 >