Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
jvdwetering opened this issue Jul 2, 2022 · 4 comments · Fixed by #8231
Closed

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

jvdwetering opened this issue Jul 2, 2022 · 4 comments · Fixed by #8231
Labels
stubs: false positive Type checkers report false errors

Comments

@jvdwetering
Copy link

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

@jvdwetering
Copy link
Author

I do realise there are a bunch of other sum/Literal related issues on typeshed right now, but I figured my example is a particularly simple one showing an issue.

@AlexWaygood
Copy link
Member

Thanks! I can also reproduce this using typeshed master.

@AlexWaygood
Copy link
Member

AlexWaygood commented Jul 2, 2022

I do realise there are a bunch of other sum/Literal related issues on typeshed right now, but I figured my example is a particularly simple one showing an issue.

I think this one is also relatively easily fixable :)

@AlexWaygood
Copy link
Member

I do realise there are a bunch of other sum/Literal related issues on typeshed right now, but I figured my example is a particularly simple one showing an issue.

I think this one is also relatively easily fixable :)

#8231

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stubs: false positive Type checkers report false errors
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants