Skip to content

Mypy cannot infer type of [[], [1]] #2255

Description

@squiddy

mypy 0.4.5, CPython 3.4.4

Running the code with mypy results in an error:

x = [[], [1]]
for b in x:
    reveal_type(b) # error: Revealed type is 'builtins.object*'
    b + [1]  # error: Unsupported left operand type for + ("object")

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.:

error: Need type annotation for variable

I'm also wondering why it infers an object, when it could (should?) be a list instead.

Activity

  1. gvanrossum commented on Oct 14, 2016

    @gvanrossum
    Member

    Thanks for the report. It's not directly related to the for loop, 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 a is builtins.list[builtins.object*].

    You're not getting the error Need type annotation for variable because that is only used for "partial types" (that's a mypy-internal term), and partial types are only inferred for variables directly assigned from None or 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.

  2. rwbarton commented on Oct 15, 2016

    @rwbarton
    Contributor

    The workaround is to add an explicit type signature to x:

    x = [[], [1]] # type: List[List[int]]
    
  3. changed the title [-]Incorrect infered type in for loop[/-] [+]Incorrect inferred type in for loop[/+] on Oct 20, 2016
  4. added this to the milestone on Oct 20, 2016
  5. changed the title [-]Incorrect inferred type in for loop[/-] [+]Mypy cannot infer type of `[[], [1]]`[/+] on Oct 20, 2016
  6. gvanrossum commented on Oct 20, 2016

    @gvanrossum
    Member

    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 :-).

  7. removed this from the milestone on Mar 29, 2017
  8. Alberth289346 commented on May 15, 2020

    @Alberth289346

    Looks like the same issue as #5045

  9. ilevkivskyi commented on Sep 14, 2023

    @ilevkivskyi
    Member

    Duplicate of #230

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions