python / python/mypy

Support type narrowing literals using `typing.get_args()`

Open
#15,106 3 comments 15 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Feature

When using typing.get_args() to ensure that a given string is of a literal type, I would expect mypy to behave similarly than when isinstance() checks are used.

Pitch
Take the following code:

from typing import Literal, TypeAlias, get_args

ExpectedUserInput: TypeAlias = Literal[
    "these", "strings", "are", "expected", "user", "input"
]


def external_function(input: str) -> str:
    if input not in get_args(ExpectedUserInput):
        raise ValueError("Invalid input.")
    return _internal_function(input)


def _internal_function(input: ExpectedUserInput) -> str:
    return f"User input: {input}"

Mypy does not detect that the string must be of the correct type, since the code path is unreachable for an invalid value and outputs an error, requiring the use of casts even though the value is guaranteed to be of the correct type:

...: error: Argument 1 to "_internal_function" has incompatible type "str"; expected "Literal['these', 'strings', 'are', 'expected', 'user', 'input']"  [arg-type]

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 issue's get_args() and Literal example and investigate how mypy currently performs type narrowing for membership checks. Done means mypy recognizes input as the declared literal type after the invalid-input branch without requiring a cast, while still reporting invalid values appropriately.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
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.