Type narrowing of indexing a StrEnum created in a function
Nobody has claimed this yet.
- 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"]
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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