Skip to content

Type narrowing of indexing a StrEnum created in a function #19532

@pchar2

Description

@pchar2

Bug Report

When indexing a StrEnum created in a function, the behaviour is not the same as created in an executed module.

To Reproduce

from enum import StrEnum

def create_str_enum(value: str, names: list[str]) -> StrEnum:
    return StrEnum(value=value, names=names)
    
WithoutBug: StrEnum = StrEnum(value="WithoutBug", names=["foo"])
WithBug: StrEnum = create_str_enum("WithBug", ["foo"])
    
WithoutBug["foo"]
WithBug["foo"]

playground

Expected Behavior

No error.

Actual Behavior

main.py:10: error: Invalid index type "str" for "StrEnum"; expected type "SupportsIndex | slice[Any, Any, Any]" [index]

Your Environment

  • Mypy version used: all version
  • Mypy command-line flags: /
  • Mypy configuration options from mypy.ini (and other config files): /
  • Python version used: 3.11-3.12

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions