python / python/typing

Should operator `|` on `TypedDict` allow for creating intersection-like dicts?

Open
#1,445 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
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 for TypedDict.
  • 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:

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.