python / python/mypy

Type narrowing on TypedDict with match expresion produces an unexpected error

Open
#16,834 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When you try to narrow down the type of a TypedDict by checking with a match expression, it produces an error when it shouldn't. But when you try an equivalent code but instead of using match, using if/else it works as expected.

To Reproduce

from typing import TypedDict, Literal, Union

class EmptyTaskPayload(TypedDict):
    pass

class CheckPendingTaskSystemRebootResponse(TypedDict):
    type: Literal["SYSTEM/REBOOT"]
    payload: EmptyTaskPayload
    
class SystemVersionTaskPayload(TypedDict):
    version: str
    
class CheckPendingTaskSystemVersionResponse(TypedDict):
    type: Literal["SYSTEM/VERSION"]
    payload: SystemVersionTaskPayload

CheckPendingTaskResponse = Union[
    CheckPendingTaskSystemRebootResponse,
    CheckPendingTaskSystemVersionResponse
]

def test_match(pending_task: CheckPendingTaskResponse) -> None:
    match pending_task["type"]:
        case "SYSTEM/REBOOT":
            pass
        case "SYSTEM/VERSION":
            payload = pending_task["payload"]
            version = payload["version"]
#                                      ^ Error produced here
# main.py:28: error: TypedDict "EmptyTaskPayload" has no key "version"  [typeddict-item]

def test_if(pending_task: CheckPendingTaskResponse) -> None:
    if pending_task["type"] == "SYSTEM/REBOOT":
        pass
    elif pending_task["type"] == "SYSTEM/VERSION":
        payload = pending_task["payload"]
        version = payload["version"]

Code with inlay hints
Error given in the local editor
Playground and Gist

Expected Behavior

Expected the code to be absent of errors since it's correct.

Actual Behavior

Produces an error in the index of payload with the key "version" saying that the other type (EmptyTaskPayload) does not have that key. Which is strange as the type system givs payload the correct type (SystemVersionTaskPayload) and in the alternative version with if/else it works.

Your Environment

  • Mypy version used: 1.8.0
  • Python version used: 3.10.12

Contributor guide

Open the contributing guide

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

Run the supplied TypedDict reproduction with the reported mypy version, comparing the match and if/else cases. Trace the match-based type narrowing behavior and add a regression test for the example; done means the match branch narrows payload to SystemVersionTaskPayload without a TypedDict key error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.