microsoft / microsoft/pyright

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

Open
#11,307 0 comments 2 reactions 0 assignees View on GitHub
enhancement request
Dominant language
Python
Stars
15.6k
Forks
1.8k
Avg merge
12h 13m
Merged PRs (30d)
52

Description

If you have a question about a behavior that you’re seeing in pyright, consider posting to the [Pyright discussion forum](https://github.com/microsoft/pyright/discussions).

**Is your feature request related to a problem? Please describe.**
I'm building a tagged union inside of a function, like so:

```python
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:

```python
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).

Interestingly, pyright doesn't see this as ambiguous in other contexts:

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

**Describe the solution you’d like**
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

Research direction

Start by reproducing the test1 and test2 examples and trace Pyright's inference and assignment handling for Literal values, TypedDicts, and tagged unions. Done means the direct return is accepted when the tag's possible values cover the tagged-union variants, with regression coverage for the shown cases.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.