如何为TypedDict列表中的每个字典添加键(Python 3.9)
解决方案
方案1:显式使用Child构造器(推荐)
直接在列表推导式里通过Child(**base, extended='sameval')的方式构建每个元素,类型检查器会直接识别出结果是Child类型,无需额外类型转换:
from typing import TypedDict class Base(TypedDict): key: str class Child(Base): extended: str base_list: list[Base] = [{'key': 'value'}, {'key': 'value2'}] # 显式构造Child实例,类型检查直接通过 child_list: list[Child] = [Child(**base, extended='sameval') for base in base_list]
方案2:封装转换逻辑到辅助函数
如果需要复用转换逻辑,可以写一个带精确类型注解的辅助函数,让类型检查器自动推导返回类型:
def convert_base_to_child(base: Base) -> Child: # 两种写法都可以,类型检查均通过 return Child(**base, extended='sameval') # 或者 return {**base, 'extended': 'sameval'} child_list: list[Child] = [convert_base_to_child(base) for base in base_list]
为什么之前的方法不生效?
dict(base, extended='ex')的问题:这个写法返回的是普通dict[str, object]类型,类型检查器无法将其关联到Child这个TypedDict,因此会报类型不匹配错误。- 列表不变性限制:直接将
list[Base]赋值给list[Child]不合法,因为Python的列表类型是**不变(invariant)**的——即使Child继承自Base,list[Base]和list[Child]也被视为完全不兼容的类型,因为Base缺少Child必须的extended字段。
内容的提问来源于stack exchange,提问作者linter-purgatory
相关产品推荐
相关产品推荐

