[BUG]: `py::enum_` class creates a new object when calling `MyEnumType(value)` rather than returns the cached instance
XuehaiPan opened this issue · comments
Xuehai Pan commented
Required prerequisites
- Make sure you've read the documentation. Your issue may be addressed there.
- Search the issue tracker and Discussions to verify that this hasn't already been reported. +1 or comment there if it has.
- Consider asking first in the Gitter chat room or in a Discussion.
What version (or hash if on master) of pybind11 are you using?
2.11.1
Problem description
I'm using enum_value is MyEnum.NAME
in my code to test whether the given value is the expected enum value. It works fine when the EnumType is created using enum.Enum
from the Python side. After I changed the implementation to C++ using py::enum_
, my CI tests failed when using lhs_enum is rhs_enum
(but lhs_enum == rhs_enum
works as expected). It creates a new enum object each time when a bounded function returns an enum object.
Reproducible example code
Python implementation:
import enum
class PyEnum(enum.Enum):
A = 0
B = 1
C = 2
assert PyEnum(0) is PyEnum.A # success
assert PyEnum(0) is PyEnum(0) # success
assert PyEnum(0) == PyEnum.A # success
assert PyEnum(0) == PyEnum(0) # success
C++ implementation:
enum class MyEnum {
A = 0;
B = 1;
C = 2;
};
py::enum_<MyEnum>(mod, "CxxEnum")
.value("A", MyEnum::A)
.value("B", MyEnum::B)
.value("C", MyEnum::C);
# call in Python
from _C import CxxEnum
assert CxxEnum(0) is CxxEnum.A # fail
assert CxxEnum(0) is CxxEnum(0) # fail
assert CxxEnum(0) == CxxEnum.A # success
assert CxxEnum(0) == CxxEnum(0) # success
Is this a regression? Put the last known working version here if it is.
Not a regression