python / python/mypy

Feature request: infer pre-narrowed tagged union as a Union of possible types

Open
#20,970 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

I'm building a tagged union inside of a function, like so:

from typing import Literal, TypedDict

class Foo(TypedDict):
    tag: Literal["foo"]

class Bar(TypedDict):
    tag: Literal["bar"]
    
def test1(tag: Literal["foo", "bar"]) -> Foo | Bar:
    return {"tag": tag}  # error

Because tag hasn't been narrowed to "foo" or "bar" at the return site, it's considered not to be assignable to FooOrBar, even though there are no other possible outcomes. To fix this, I have to return the same value from both branches of an if clause:

def test2(tag: Literal["foo", "bar"]) -> Foo | Bar:
    if tag == "foo":
        return {"tag": tag}  # ok
    else:
        return {"tag": tag}  # ok

At this stage all I care about is knowing that my output value is one of Foo or Bar, and the above construct looks like a code smell (especially with >2 tag values).

MyPy also sees this as an error even when defining the literal value inline if my variable is annotated with multiple possible values:

tag: Literal["foo", "bar"] = "foo"
foo: Foo | Bar = {"tag": tag}  # error

Pitch
In cases where the "tag" value of the tagged union is not narrowed, but can be inferred as consistent with multiple typed dicts in the return type of a function, I'd love to see this be narrowed as a union of those possible typed dicts. Given the "tag" is already scoped to the possible values (if it weren't, the bare "else" wouldn't work) I can't think of any way this would be unsound.

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

No implementation file, test, or entry point is named in the issue. Start by reproducing test1 and test2 in mypy, then investigate the tagged TypedDict and Literal inference paths; done means the shown assignments are accepted without requiring explicit branching.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.