Should operator `|` on `TypedDict` allow for creating intersection-like dicts?
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 1.8k
- フォーク
- 302
- 平均マージ
- 23時間
- マージ済み PR(30日)
- 8
説明
I'm wondering how is the relation between the following PEPs:
- PEP 584 which introduces operator
|for dicts, but doesn't mention how it should behave forTypedDict. - PEP 589 which introduces
TypedDict, but doesn't mention the operator|.
According to PEP 589, multiple inheritance can be used to create a combined (or "intersection like") dict, and operator | provides the corresponding behavior at runtime. Thus it would be nice if the type system could handle the combination properly (similar to how it is possible in TypeScript):
from typing import TypedDict
class HasFoo(TypedDict):
foo: int
class HasBar(TypedDict):
bar: int
class HasFooAndBar(HasFoo, HasBar):
...
def f(a: HasFoo, b: HasBar) -> HasFooAndBar:
return a | b
From a runtime and type-checking perspective this code looks valid, but currently mypy does not accept it (playground):
main.py:15: error: Incompatible return value type (got "HasFoo", expected "HasFooAndBar") [return-value]
main.py:15: error: Unsupported operand types for | ("HasFoo" and "HasBar") [operator]
Pyright seems to have the same behavior.
Apparently operator | can only be used for two instances of the same typed dict, which as far as I can see has limited use cases, because using the operator | on two dicts that already have the same fields is kind of pointless (perhaps it mostly makes sense if the type used total=False).
Possible related discussions and issues I've found:
- https://github.com/python/typing/issues/213 (since this feature for
TypedDictprobably falls into the "intersection type" category as well?) - https://github.com/microsoft/pylance-release/issues/2300
- https://github.com/microsoft/pyright/issues/2951
コントリビューションガイド
このリポジトリのコントリビューションガイドは索引されていません
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず PEP 584 と PEP 589 を比較し、次にリンク先の mypy playground で TypedDict の例を再現します。関連する typing、Pylance、Pyright の議論を確認し、提案されている交差型のような動作について合意があるかどうかを判断します。合意されたセマンティクスと、type checker がそれをサポートするための文書化された道筋があれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- tooling
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 30/100