python / python/mypy

Indexing a Type Alias of an Enum yields false error

Open
#7,568 7 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-2-low topic-enum topic-metaclasses
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Minimum [not-]working product:

Ah, good old Enums:

from enum import Enum
class EnumClass(Enum):
    one = 1

EnumAlias = EnumClass
EnumAlias['one']
test.py:6: error: Type application targets a non-generic function or class
test.py:6: error: Name 'one' is not defined

I'm fairly certain this is not an intentional design choice. Just to be sure, according to documentation:

A type alias does not create a new type. It’s just a shorthand notation for another type – it’s equivalent to the target type except for generic aliases.

Now, Enums actually can't be generic, so I certainly expect the alias to be equivalent. So I think this code should pass (regardless of its usefulness... who wants to alias an Enum anyways?).

Possible Causes

I'm no expert, but I think this is happening because the semantic analyzer deems any IndexExpr a TypeApplication if it has a TypeAlias as a base. Once it's marked as analyzed, it doesn't reach the stage of the expression checker where the Enum type would be recognized and the indexing processed as valid. Whatever the root of the problem, I think there's only one spot where the expression checker actually looks at is_enum to handle Enum indexing, so the alias isn't making it there one way or another.

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

Start by tracing how the semantic analyzer classifies the IndexExpr as a TypeApplication when its base is a TypeAlias, then follow the expression checker path that handles is_enum. Verify the EnumAlias['one'] example no longer produces either reported error, and add regression coverage for this case.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.