python / python/mypy

Type narrowing of indexing a StrEnum created in a function

Open
#19,532 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-enum
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Run the supplied Python 3.11–3.12 reproducer, including the linked mypy-play example, and compare indexing of the module-created and function-created StrEnum values. Trace mypy’s type narrowing for the function return and make both [...] expressions type-check without the reported invalid-index error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.