Skip to content

sum(List[Literal[0,1]]) is inferred as Literal[0,1] while it should be int #8230

@jvdwetering

Description

@jvdwetering

Bug report
Using sum on a set of Literal ints has an inferred type of the same Literals, instead of inferring the correct more general type of int.

To reproduce


Z2 = Literal[0,1]

l: List[Z2] = [0,1,1]
a = sum(l)
reveal_type(a) # "Union[Literal[0], Literal[1]]"

a = a - 1 # error: Incompatible types in assignment (expression has type "int", variable has type "Literal[0, 1]")

Expected behaviour
The type of a should be inferred as int.

Actual behaviour
The type of a is inferred to be Literal[0,1]. This is the case for mypy==0.940 and onwards. On mypy==0.930 the correct typing of int is inferred. Explicitly annotating a with int also fixes the issue.

Your environment
Mypy version: 0.961 (also tried 0.940)
Mypy command line flags: none
Mypy configuration options from mypy.ini (and other config files): no other config
Python version used: 3.9.1
Operating system and version: Windows 10

Crossposted from python/mypy#13055

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions