Should operator `|` on `TypedDict` allow for creating intersection-like dicts?
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 1.8k
- Forks
- 302
- Avg merge
- 23h
- Merged PRs (30d)
- 8
Description
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
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by comparing PEP 584 and PEP 589, then reproduce the TypedDict example in the linked mypy playground. Review the related typing, Pylance, and Pyright discussions to determine whether the proposed intersection-like behavior has consensus. Done would require an agreed semantic and a documented path for type checkers to support it.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100