Open
Description
Bug report
Bug description:
from enum import Enum, StrEnum, auto
class Foo(Enum):
one = auto()
two = auto()
class Bar(StrEnum):
one = auto()
two = auto()
names = ["one", "two"]
print([Foo[name] for name in names])
print(list(map(Foo.__getitem__, names)))
print([Bar[name] for name in names])
print(list(map(Bar.__getitem__, names))) # TypeError: expected 1 argument, got 0
CPython versions tested on:
3.12, 3.13
Operating systems tested on:
macOS
Metadata
Metadata
Assignees
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
tom-pytel commentedon Jan 9, 2025
str
class slots are overridingEnumType
mapping for__getitem__
and others inStrEnum
for certain uses.They work implicitly but not explicitly:
Because
Bar['one']
callsEnumType.__getitem__()
andBar.__getitem__('one')
callsstr.__getitem__()
. This also applies to other magics like__contains__
or__len__
:Quick hack fix, add the following to
StrEnum
to re-override methods overridden bystr
(if this is the desired behavior):Before:
After:
StrEnum
as set ofstr
python/mypy#18380serhiy-storchaka commentedon Jan 13, 2025
Then what
Bar.one[0]
will return?tom-pytel commentedon Jan 13, 2025
It will not act as a
str
with respect to those magics as you point out but rather as anEnumType
(see qualifier above "if this is the desired behavior"). So maybe not the desired behavior and the original code should just be invalid?ethanfurman commentedon Jan 13, 2025
I'll need to get some tests written for the expected behavior of those dunders.
serhiy-storchaka commentedon Jan 13, 2025
We need different, well defined behavior for
Bar['one']
andBar.one[0]
,len(Bar)
andlen(Bar.one)
, etc. An enum class should behave as other enum classes, and an enum instance should behave as other instance of a parent class.As for the dunder methods, we have precedents. For example,
int.__or__
is a method that corresponds to an instance operation, whilestr.__or__
is a method that corresponds to a type operation.So I think we should not change anything in StrEnum, at least not before we change the larger image.