Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG]: py::enum_ class creates a new object when calling MyEnumType(value) rather than returns the cached instance #5092

Open
2 of 3 tasks
XuehaiPan opened this issue Apr 7, 2024 · 0 comments
Labels
triage New bug, unverified

Comments

@XuehaiPan
Copy link
Contributor

XuehaiPan commented Apr 7, 2024

Required prerequisites

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

@XuehaiPan XuehaiPan added the triage New bug, unverified label Apr 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
triage New bug, unverified
Projects
None yet
Development

No branches or pull requests

1 participant