Repository navigation
Mypy cannot infer type of [[], [1]] #2255
Description
Activity
Thanks for the report. It's not directly related to the
forloop, it's just that in this case the item type of the outer list is inferred as the join of (the types of)[]and[1]and for obscure reasons that becomes object instead of list. E.g.a = [[], [1]] reveal_type(a)
shows that the type of
aisbuiltins.list[builtins.object*].You're not getting the error
Need type annotation for variablebecause that is only used for "partial types" (that's a mypy-internal term), and partial types are only inferred for variables directly assigned fromNoneor an empty container. Here we've got something more complicated and it tries to directly infer a type for the outer list, and failing to notice the similarity between an empty list and a list of integers.I think we can fix this though I'm not sure how important it is or how soon it'll happen.
Reacted by Reiner GereckeThe workaround is to add an explicit type signature to
x:x = [[], [1]] # type: List[List[int]]- changed the title
[-]Incorrect infered type in for loop[/-][+]Incorrect inferred type in for loop[/+]on Oct 20, 2016 - changed the title
[-]Incorrect inferred type in for loop[/-][+]Mypy cannot infer type of `[[], [1]]`[/+]on Oct 20, 2016 Since this can be worked around by adding annotations I don't consider this very urgent, and it's hard to fix (see the closed PR :-).
- addedfalse-positivemypy gave an error on correct codemypy gave an error on correct code
on May 18, 2018 Looks like the same issue as #5045
Duplicate of #230
- marked this as a duplicate of Generic function type argument inference problem #230
on Sep 14, 2023
mypy 0.4.5, CPython 3.4.4
Running the code with mypy results in an error:
This might be me misunderstanding the type system, but I would have expected mypy to ask for type annotations if it can't infer the type, e.g.:
I'm also wondering why it infers an object, when it could (should?) be a list instead.