python / python/typing

Allow use of `Required` and `NotRequired` to make an existing typed dict total or optional

未关闭
#1,454 8 条评论 7 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

topic: feature
主要语言
Python
星标
1.8k
派生
302
平均合并
23 小时
30 天内合并 PR
8

描述

I think the ability of indicating that a typed dict requires all keys or that all are optional would be very useful.

For example to allow defining default values for a particular dict or to return a dict that has been completely assigned from a function

A simple example

class A(TypedDict):
    a: int
    b: int

ADefault = {'a': 1, 'b': 42}

def optionalA(v: NotRequired[A]) -> A:
    return ADefault | v

optionalA({'a': 11}) # ok since all keys of NotRequired[A] are optional

class X(TypedDict, total=False):
    x: str
    y: str

XDefault: X = {"x": "xv", "y": "yv"}

def withXDefault(v: X) -> Required[X]:
    return XDefault | v

withXDefault({"x": "foo"})["y"]  # ok since all keys of Required[X] are required

This idea is inspired by the analogous types in typescript Required and Partial that are in general very convenient.

I think it makes sense having the same behaviour of the typescript counterparts:

  • NotRequired[X] is a no op, since X is defined as total=False. Same for Required[A].
  • Required/NotRequired would include all keys of the typed dict and all its superclasses. This differs from how total works. Example:
    class TD1(TypedDict):
        a: int
    
    class TD2(TypedDict, total=False):
        b: int
    
    TDR = Required[TD2]  # b becomes required
    TDNR = NotRequired[TD2]  # a becomes not required
    
  • Required/NotRequired used inline in the TypedDict are not taken into consideration, so the end result is the same independently of how the typed dict is defined

贡献指南

这个仓库没有索引到贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先审查提议的 TypedDict、Required 和 NotRequired 语义以及 issue 中的示例,包括继承和内联注释。定义行为并确定相关的 typing specification 和一致性测试;完成的标准是所请求的转换已得到一致的规范说明和验证。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
developer-experience
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。