Python中合并TypedDict实例出现类型警告,如何优化注解?
解决TypedDict继承后字典合并的类型推断问题
当你用**base_instance解包TypedDict实例时,类型检查器会将其视作普通的dict[str, object](因为TypedDict仅为静态类型注解,运行时本质还是普通字典)。和"b": "another string"合并后,整体类型被推断为dict[str, object | str],而Extend要求所有字段值均为str,因此触发类型不匹配的警告。
以下是几种可行的解决方式:
类型断言(cast)明确类型
通过typing.cast直接告知类型检查器合并后的字典符合Extend类型:from typing import TypedDict, cast class Base(TypedDict): a: str class Extend(Base): b: str base_instance: Base = {"a": "string!"} extend_instance: Extend = cast(Extend, {**base_instance, "b": "another string"})直接构造符合结构的字典
跳过解包操作,按Extend的结构直接构建实例:extend_instance: Extend = {"a": base_instance["a"], "b": "another string"}Python 3.10+:使用TypedDict类构造实例
3.10及以上版本支持直接用TypedDict类创建实例,类型检查器能正确识别类型:extend_instance = Extend(a=base_instance["a"], b="another string")
内容的提问来源于stack exchange,提问作者Nick Reid
相关产品推荐
相关产品推荐

