Skip to content

Type[Enum] does not properly infer from classmethod when passed to list #14110

Closed

Description

@johnthagen

Bug Report

Type[Enum] does not properly infer when passed to list, and is inferred to Any or str in the case of a (str, Enum) type.

To Reproduce

from enum import Enum, unique

@unique
class Color(Enum):
    Red = "red"
    Green = "green"
    Blue = "blue"

    @classmethod
    def foo(cls) -> None:
        colors = list(cls)
        reveal_type(colors)
        print(colors)


Color.foo()

Expected Behavior

Revealed type: builtins.list[main.Color]

Running the code, shows that at runtime it is a list[Color]:

[<Color.Red: 'red'>, <Color.Green: 'green'>, <Color.Blue: 'blue'>]

Actual Behavior

main.py:12: error: Need type annotation for "colors" (hint: "colors: List[<type>] = ...")  [var-annotated]
main.py:13: note: Revealed type is "builtins.list[Any]"
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 0.991 (compiled: yes)
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): N/A (default settings)
  • Python version used: 3.10.6
  • OS: macOS 12.6, x86_64

Activity

  1. johnthagen commented on Nov 16, 2022

    @johnthagen
    ContributorAuthor

    When a (str, Enum) type is used:

    from enum import Enum, unique
    
    
    @unique
    class Color(str, Enum):
        Red = "red"
        Green = "green"
        Blue = "blue"
    
        @classmethod
        def foo(cls) -> None:
            colors = list(cls)
            reveal_type(colors)
            print(colors)
    
    
    Color.foo()

    The revealed type is list[str] instead of list[Color]:

    main.py:13: note: Revealed type is "builtins.list[builtins.str]"
    Success: no issues found in 1 source file
    

    Even though at runtime, it is a list[Color]:

    [<Color.Red: 'red'>, <Color.Green: 'green'>, <Color.Blue: 'blue'>]
    
  2. changed the title [-]`Type[Enum]` does not properly infer when passed to `list`[/-] [+]`Type[Enum]` does not properly infer from `classmethod` when passed to `list`[/+] on Nov 16, 2022
  3. erictraut commented on Aug 14, 2023

    @erictraut

    This bug appears to have been fixed in mypy 1.1.0. I'm not able to repro it in that version or any subsequent version.

  4. hauntsaninja commented on Aug 14, 2023

    @hauntsaninja
    Collaborator

    Fixed in #14554

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