Skip to content

Better error message for assignments incompatible due to invariance #4186

Closed

Description

@silviogutierrez

There seems to be a problem with enums when inferred and used inside lists. This happens with both mypy 0.540 and mypy 0.520.

Code:

class Magic(Enum):
    ISSUER = 1
    ISSUER_EXCHANGE = 2
    ASSIGNEE = 3
    ALL = 3

boo = [c for c in Magic if c not in [Magic.ISSUER]]
boo_explicit: List[Enum] = [c for c in Magic if c not in [Magic.ISSUER]]
spam1: Dict[str, List[Enum]] = {'abc': boo} # Fails with: Dict entry 0 has incompatible type "str": "List[Magic]"; expected "str": "List[Enum]"
spam2: Dict[str, List[Enum]] = {'abc': boo_explicit} # works when typed explicitly
spam3: Dict[str, List[Enum]] = {'abc': [Magic.ISSUER]} # works when done inline
spam4: Dict[str, List[Enum]] = {'abc': [c for c in Magic if c not in [Magic.ISSUER]]} # works when done inline, even with a list comp.
spam5: Dict[str, Enum] = {'abc': Magic.ISSUER} # works Works for single enums.

Let me know what other info you need, or any other steps I should take.

Thanks for all the work on such an awesome project.

Activity

  1. JelleZijlstra commented on Nov 1, 2017

    @JelleZijlstra
    Member

    This is not related to enums and I don't think it's a bug; it's because of invariance. Because the List type is invariant, List[B] is not allowed for List[A] when B is a subclass of A. As your examples, show mypy uses special logic to infer List[A] instead of List[B] in some cases.

  2. ilevkivskyi commented on Nov 1, 2017

    @ilevkivskyi
    Member

    This is not a bug, List is invariant. It is however strange that you didn't get a note explaining this. Also the bug is that you don't get an error on the comprehension line, see #3210

    I am keeping this open so that we can give a better error message, for some reasons it does not work with enums.

  3. ilevkivskyi commented on Nov 1, 2017

    @ilevkivskyi
    Member

    OK, the problem is that we give the better error message only for incompatible arguments, not in assignments. This is therefore easy to fix.

  4. changed the title [-]Problems with enums when inferred[/-] [+]Better error message for assignamnets incompatible due to invariance[/+] on Nov 1, 2017
  5. changed the title [-]Better error message for assignamnets incompatible due to invariance[/-] [+]Better error message for assignments incompatible due to invariance[/+] on Apr 4, 2018
  6. felipythondev commented on May 7, 2019

    @felipythondev
    Contributor

    I taking a look at this.

  7. added a commit that references this issue on May 9, 2019
    1ea1122
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