Skip to content

enum: Add Enum.value property #2739

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

Merged
merged 3 commits into from
Dec 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions include/pybind11/pybind11.h
Original file line number Diff line number Diff line change
Expand Up @@ -1731,6 +1731,7 @@ template <typename Type> class enum_ : public class_<Type> {
m_base.init(is_arithmetic, is_convertible);

def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
def_property_readonly("value", [](Type value) { return (Scalar) value; });
def("__int__", [](Type value) { return (Scalar) value; });
#if PY_MAJOR_VERSION < 3
def("__long__", [](Type value) { return (Scalar) value; });
Expand Down
23 changes: 16 additions & 7 deletions tests/test_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,24 @@ def test_unscoped_enum():

# name property
assert m.UnscopedEnum.EOne.name == "EOne"
assert m.UnscopedEnum.EOne.value == 1
assert m.UnscopedEnum.ETwo.name == "ETwo"
assert m.EOne.name == "EOne"
# name readonly
assert m.UnscopedEnum.ETwo.value == 2
assert m.EOne is m.UnscopedEnum.EOne
# name, value readonly
with pytest.raises(AttributeError):
m.UnscopedEnum.EOne.name = ""
# name returns a copy
foo = m.UnscopedEnum.EOne.name
foo = "bar"
with pytest.raises(AttributeError):
m.UnscopedEnum.EOne.value = 10
# name, value returns a copy
# TODO: Neither the name nor value tests actually check against aliasing.
# Use a mutable type that has reference semantics.
nonaliased_name = m.UnscopedEnum.EOne.name
nonaliased_name = "bar" # noqa: F841
assert m.UnscopedEnum.EOne.name == "EOne"
nonaliased_value = m.UnscopedEnum.EOne.value
nonaliased_value = 10 # noqa: F841
assert m.UnscopedEnum.EOne.value == 1

# __members__ property
assert m.UnscopedEnum.__members__ == {
Expand All @@ -33,8 +42,8 @@ def test_unscoped_enum():
with pytest.raises(AttributeError):
m.UnscopedEnum.__members__ = {}
# __members__ returns a copy
foo = m.UnscopedEnum.__members__
foo["bar"] = "baz"
nonaliased_members = m.UnscopedEnum.__members__
nonaliased_members["bar"] = "baz"
assert m.UnscopedEnum.__members__ == {
"EOne": m.UnscopedEnum.EOne,
"ETwo": m.UnscopedEnum.ETwo,
Expand Down