python / python/mypy

Narrowing types to `Literal` using `in` syntax

Open
#12,535 6 comments 33 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-literal-types topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Take this example code:

x = "a"
reveal_type(x)
assert x in ("a", "b", "c")
reveal_type(x)

y = 20
reveal_type(y)
assert y == 10 or y == 20 or y == 50
reveal_type(y)

The current output of this is:

$ mypy x.py 
x.py:2: note: Revealed type is "builtins.str"
x.py:4: note: Revealed type is "builtins.str"
x.py:7: note: Revealed type is "builtins.int"
x.py:9: note: Revealed type is "builtins.int"

If mypy were to support type narrowing using chained or statements and in statements, the output would look like:

$ mypy x.py 
x.py:4: note: Revealed type is "builtins.str"
x.py:6: note: Revealed type is "Union[Literal['a'], Literal['b'], Literal['c']]"
x.py:9: note: Revealed type is "builtins.int"
x.py:11: note: Revealed type is "Union[Literal[10], Literal[20], Literal[50]]"

I think doing simple narrowing here would be relatively easy and very useful.

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 x.py examples in the issue and run mypy to confirm the current revealed types. Investigate mypy's existing type-narrowing behavior for chained or conditions and in expressions; done means the examples reveal the requested Literal unions for both string and integer 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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.