我正在try 创建几个函数,这些函数将返回不同类型的TypeDict的值.它们中的大多数字段将是相同的,所以我想生成在所有情况下都具有相同功能的基本词典.然而,我被正确地输入这句话难住了.
我的 idea 是创建基本类型Parent
并从它继承,只添加NotRequired
个字段.
from typing_extensions import NotRequired, TypedDict
class Parent(TypedDict):
parent_field: str
class Child(Parent):
child_field: NotRequired[bool | None]
def create_parent() -> Parent:
return {"parent_field": "example"}
child: Child = create_parent()
# Error:
# Expression of type "Parent" cannot be assigned to declared type "Child"
# "child_field" is missing from "Type[Parent]"
但是,此操作失败,因为缺少字段child_field
,即使其类型为NotRequired
.它为什么会失败,如何规避这个问题?
编辑:我正在使用Pylance(如此简单)进行打字判断.
mypy
(playground)给出类似的错误消息:
赋值中的类型不兼容(表达式的类型为"Parent",变量的类型为"Child")[Assignment]