TypedDict 的 Python typehint 子集(部分)

vac*_*456 14 python type-hinting partial python-typing typeddict

在打字稿中,我们有Partial 类型,所以我们可以这样做:

interface Foo {
    x:number
    y:number
}

const foo:Partial<Foo> = {x: 1}
Run Code Online (Sandbox Code Playgroud)

(通过这个我们可以使接口的所有属性都是可选的)

在 Python 中,我们可以使用 来做到这一点total=False,如下所示:

from typing_extensions import TypedDict


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

foo:Foo = {'x':1}
Run Code Online (Sandbox Code Playgroud)

但这种方法不太好,因为这意味着 allFoo必须将所有属性尽可能为 None,并且我们需要进行大量类型转换。在 python 中,是否有一种方法可以声明 TypedDict,然后将其某些实现作为该类型的子集,如下所示:

from typing_extensions import TypedDict


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


foo:Partial[Foo] = {'x': 1}
Run Code Online (Sandbox Code Playgroud)

Yum*_*514 4

从Python3.11开始,我们有了typing.NotRequired. 文档在这里,PEP 在这里

这将变量标记为潜在缺失

喜欢

from typing import TypedDict, NotRequired

class Movie(TypedDict):
    title: str
    year: NotRequired[int]
Run Code Online (Sandbox Code Playgroud)

  • 虽然这朝着正确的方向发展,但为了获得与 TS 相同的效果,我们需要像“Partial[Movie]”这样的东西来返回每个属性都是“NotRequired”的电影版本。 (5认同)