python / python/mypy

Eager narrowing to `Literal` when possible

Open
#15,434 2 comments 4 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

Feature

I often feel I have to put too much effort into informing mypy that some variables can only hold a finite set of values. It would be helpful if mypy was a bit smarter in the way it infers Literal types.

Pitch

Here are some concrete examples:

from typing import Literal

def letter_v1(number: int) -> Literal["a", "b", "c"]:
    if number == 1:
        letter = "a"
    elif number == 2:
        letter = "b"
    else:
        letter = "c"
    
    # Incompatible return value type (got "str", expected "Literal['a', 'b', 'c']")  [return-value]
    return letter
    
def letter_v2(number: int) -> Literal["a", "b", "c"]:
    letter = "a" if number == 1 else "b" if number == 2 else "c"
    
    # Incompatible return value type (got "str", expected "Literal['a', 'b', 'c']")  [return-value]
    return letter

def letter_v3(number: int) -> Literal["a", "b", "c"]:
    letter = ("a", "b", "c")[number]
    
    # Incompatible return value type (got "str", expected "Literal['a', 'b', 'c']")  [return-value]
    return letter

See also: https://mypy-play.net/?mypy=1.3.0&python=3.11&flags=strict&gist=bab569e05877621b90f081fc7bdb7d05

Ideally, I think I should get away without having to specify the type of letter in any of the concrete examples here. A human reviewing this code would easily conclude that there is no issue here, yet mypy struggles.

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

Reproduce the three letter_v1, letter_v2, and letter_v3 examples using the linked mypy-play case, then trace how mypy infers the local variable types. Determine the intended narrowing behavior and add regression coverage for the examples; done means the annotated functions type-check without explicit types for letter.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.