Skip to content

List[Literal[...]] type being narrowed where it shouldn't be #9850

Open

Description

@tusharsadhwani

Bug Report

Adding an if check on a specific index of a List of Literals seems to narrow down its scope, even though the list can be modified and the value at that index can change.

To Reproduce

Run mypy over this piece of code:

foo: List[Literal['a', 'b']] = ['a', 'b', 'a']

if foo[0] == 'a':
    print('a')
    exit()

foo.pop(0)
reveal_type(foo[0])
if foo[0] == 'a':
    pass

Expected Behavior

Revealed type to be Literal['a', 'b'], and the conditional to be valid.

Actual Behavior

t.py:11: note: Revealed type is 'Literal['b']'
t.py:12: error: Non-overlapping equality check (left operand type: "Literal['b']", right operand type: "Literal['a']")

Your Environment

  • Mypy version used: 0.790
  • Mypy command-line flags: --strict
  • Python version used: 3.9.1 64-bit
  • Operating system and version: Fedora 33 x86_64

Activity

  1. tusharsadhwani commented on Dec 30, 2020

    @tusharsadhwani
    ContributorAuthor

    Even doing:

    from typing import List, Literal
    
    foo: List[Literal['a', 'b']] = ['b', 'a']
    
    if foo[0] == 'a':
        exit()
    
    foo[0] = 'a'
    reveal_type(foo[0]) # shows Literal['b']
    reveal_type(foo[1]) # shows Literal['a'] | Literal['b']

    It seems to think that the type of list[index] can't change once narrowed down.

  2. tusharsadhwani commented on Dec 5, 2021

    @tusharsadhwani
    ContributorAuthor

    ^ Reproduces on mypy 0.910 as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions