TypedDict does not allow optional keys?

Viewed 4291

I wanted to have a schema validation using pydantic, and also TypedDict to define the part of a nested dict schema. However, I realised that the Optional does not work if it is specified within the TypedDict class.

I read that this class will render all the keys within as required, and a way to make ALL of them as optional was to at total=False. However, I only wanted one of the keys to be optional and the rest required. Is there a way to overcome this limitation?

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

EDIT

I tried this previously as I thought it is similar to a nested list.

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]

but faced an error msg saying that Dict requires 2 parameters. Apparently Dict works differently and I can't define it as a class like I hope to be?

1 Answers

According to PEP 655, what you need is NotRequired

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

notice that you shouldn't use Optional in TypedDict, and only use (Not)Required

if you want to use TypedDict with Pydantic, you could refer this article

Related