python / python/mypy

Strange behavior using Tagged Union

Open
#10,659 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-typed-dict
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When using tagged unions, mypy infers correctly with with instance["tag"],
but fails with instance.get("tag")

To Reproduce

  1. Write the following code into tagged_union.py:
from typing import Literal, TypedDict, Union


class TaggedTypeA(TypedDict):
    tag: Literal["A"]
    is_a: bool


class TaggedTypeB(TypedDict):
    tag: Literal["B"]


TaggedUnion = Union[TaggedTypeA, TaggedTypeB]

instance_a: TaggedUnion = {"tag": "A", "is_a": True}

if instance_a["tag"] == "A":
    print(f"Am I type a? {instance_a['is_a']}")

if instance_a.get("tag") == "A":
    print(f"Am I type a this time? {instance_a['is_a']}")

  1. Run mypy tagged_union.py
  2. Get only one error

tagged_union.py:21: error: TypedDict "TaggedTypeB" has no key "is_a"

Error occurs in second if statement

Expected Behavior

I can see that mypy correctly infers the type of instance_a when I use instance_a["tag"] == "A" (the first if expression).

Therefore, I would expect the same behavior when using instance_a.get("tag") == "A" (the second if clause).

Actual Behavior
mypy correctly infers the type of instance_a when I use instance_a["tag"] == "A" (the first if expression).

mypy fails to infer the type when I use instance_a.get("tag") == "A".

In fact, mypy doesn't only not infer the correct type, it infers the opposite type TaggedTypeB which does not make sense at all

Your Environment

  • Mypy version used: 0.902
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.8.10
  • Operating system and version: Ubuntu 21.04

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

Start with the tagged_union.py reproduction and run mypy tagged_union.py to compare narrowing for bracket access and get(). Trace the type-narrowing path responsible for TypedDict unions, then add or update a regression test showing that both forms narrow to TaggedTypeA and pass the relevant mypy test suite.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.