相关疑难解决方法(0)

TypedDict 不允许可选键?

我想使用 pydantic 进行模式验证,并使用 TypedDict 来定义嵌套字典模式的一部分。但是,我意识到Optional如果在 TypedDict 类中指定它则不起作用。

我读到这个类将根据需要呈现所有键,并且使所有键都成为可选的方法是 at total=False。但是,我只希望其中一个键是可选的,其余键是必需的。有没有办法克服这个限制?

from typing import List, Optional
from pydantic import BaseModel
from typing_extensions import TypedDict

class _trending(TypedDict):
    allStores: Optional[bool] = False
    category: str
    date: str
    average: List[int]

class RequestSchema(BaseModel):
    storeId: str
    trending: _trending
Run Code Online (Sandbox Code Playgroud)

编辑

我之前尝试过这个,因为我认为它类似于嵌套列表。

from typing import List, Optional, Dict
from pydantic import BaseModel


class _trending(BaseModel):
    allStores: Optional[bool] = False
    category: str
    date: str
    average: List[int]

class RequestSchema(BaseModel):
    storeId: str
    trending: Dict[_trending]
Run Code Online (Sandbox Code Playgroud)

但遇到一条错误消息,指出 Dict 需要 2 个参数。显然 Dict …

python pydantic typeddict

44
推荐指数
2
解决办法
2万
查看次数

标签 统计

pydantic ×1

python ×1

typeddict ×1