Python how to iterate over StrEnum without linter (PyCharm inspections) unresolved references

Viewed 415

I have implemented a StrEnum (aka enforcing Enum members to be str) per the instructions within the Python 3.6 enum docs, section 8.13.13.4 Others.

from enum import Enum


class StrEnum(str, Enum):
    """Enum where members are strings."""

I have a subclass of StrEnum where I use a for loop to iterate through it.

class TestStrEnum(StrEnum):
    """Test string enum."""

    A = "Apple"
    B = "Bananas"


for enum_ in TestStrEnum:
    print(f"name = {enum_.name}, value = {enum_.value}.")

This works fine at runtime. However, my linter complains about an unresolved reference when referring to the name and value attributes:

Pycharm unresolved reference on enum

How can I get my linter to not complain?

The problem seems to be that the linter is not properly inspecting within the StrEnum._member_map_. I think the solution may be to override a dunder method within StrEnum, but am not sure which one to use.


Workaround Solution

Here is a workaround I figured out by using the __members__ attribute to access the members in an explicit manner.

for enum_member_name, enum_member in TestStrEnum.__members__.items():
    print(f"name = {enum_member.name}, value = {enum_member.value}.")

My linter is PyCharm 2019.2.6 CE's code inspections.

**EDIT**

Per @user2235698's answer, it seems this is a known issue with PyCharm: PY-36205, raised in May 2019. Since this issue only currently has 6 upvotes (as of April 11th, 2020), I am not sure it will be fixed anytime soon.

If anyone has a good solution that can be used until the issue is resolved, I am still interested.

1 Answers
Related