python / python/mypy

Attempted to reuse member name in Enum definition

Open
#17,234 0 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

I'm trying to follow the dynamic generation of Enum values example as described in the Enum documentation, and I'm getting this from mypy:

example.py:23: error: Attempted to reuse member name "i" in Enum definition "Slot"  [misc]

Now, I am trying to reuse the member name; in contrast to the Enum example, I have multiple loops that generate several sets of Enum values, and I am reusing the same loop variable across all of them (see the example below). mypy doesn't complain if I only have one loop in my Enum.

But considering I've already declared that member to be ignored in _ignore_, I don't see why I should use multiple distinct loop variables for all my loops, if all of them are going to be ignored by Enum plumbing anyway.

Moreover, the loop variable is used in a loop anyway; it will definitely get reassigned multiple values even during the first loop execution. I don't see how having multiple loops makes any difference to having a single loop.

To Reproduce

Run source through mypy:

import enum


class MyEnum(enum.StrEnum):
    _ignore_ = 'MyEnum i'
    MyEnum = vars()

    for i in range(8):
        MyEnum[f'SOMETHING_{i}'] = f'Something{i}'

    for i in range(4):
        MyEnum[f'ANOTHER_{i}'] = f'Another{i}'

Expected Behavior

mypy should not complain about this code.

Actual Behavior

mypy complains about the member being reused at the line of the second loop.

Your Environment

  • Mypy version used: 1.10.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files):
[mypy]
files = src
mypy_path = stubs
strict = True
install_types = True
  • Python version used: 3.11.9

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

Reproduce the diagnostic with the provided example using mypy 1.10.0 and confirm that the second loop triggers the reuse warning while a single loop does not. Trace the Enum-definition analysis that handles ignore and loop variables, then add or update a regression test so the example no longer reports an error.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.