Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python typehint subset(partial) of an TypedDict

In typescript we have Partial type, so we can do this:

interface Foo {
    x:number
    y:number
}

const foo:Partial<Foo> = {x: 1}

(With this we can make all properties of an interface optional)

In Python, we could do this with a total=False, like this:

from typing_extensions import TypedDict


class Foo(TypedDict, total=False):
    x:int
    y:int

foo:Foo = {'x':1}

But this approach is not too good, because this implies that all Foo must have all properties as possible None, and we need to do a lot of typecasting. Is there, in python, a way to declare a TypedDict and then make some implementation of it a subset of this type, like this:

from typing_extensions import TypedDict


class Foo(TypedDict):
    x: int
    y: int


foo:Partial[Foo] = {'x': 1}
like image 766
vacih86456 Avatar asked Nov 30 '25 02:11

vacih86456


1 Answers

From Python3.11, we have typing.NotRequired. The Doc is Here, and PEP is Here.

This marks variable as potentially-missing.

Like

from typing import TypedDict, NotRequired

class Movie(TypedDict):
    title: str
    year: NotRequired[int]
like image 114
nagataaaas Avatar answered Dec 02 '25 15:12

nagataaaas