Skip to content

Shouldn't get_args(Literal[...]) be usable for type narrowing? #1359

@ReggX

Description

@ReggX

Currently, it's possible to use if value in (0, 1, 2, 3) to apply type narrowing for value down to Literal[0, 1, 2, 3].

During runtime, using typing.get_args() on Literal[0, 1, 2, 3] returns (0, 1, 2, 3), so value in get_args(Literal[0, 1, 2, 3]) has the same result as value in (0, 1, 2, 3). Shouldn't type checkers be able to do the same deduction statically?

Here's some simple example code, tested in mypy and pyright, both give builtins.int for the two reveal_type(value) calls.

from typing import Literal
from typing import TypeAlias
from typing import get_args


SUBLIT: TypeAlias = Literal[0, 1, 2]
LIT: TypeAlias = Literal[SUBLIT, 3]

 
def test_function(value: int) -> None:
  reveal_type(value)  # should be and is builtins.int
  if value in get_args(LIT):
    reveal_type(value)  # should be Literal[0, 1, 2, 3], but is builtins.int

print(get_args(LIT))

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions