python / python/typing

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

オープン
#1,454 コメント 8 件 リアクション 7 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

topic: feature
主要言語
Python
スター
1.8k
フォーク
302
平均マージ
23時間
マージ済み PR(30日)
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. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、提案されている TypedDict、Required、NotRequired のセマンティクスと issue の例を、継承およびインラインアノテーションを含めて確認します。動作を定義し、関連する typing specification と適合性テストを特定します。完了とは、要求された変換が一貫して仕様化され、検証されていることを意味します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
developer-experience
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。