File tree Expand file tree Collapse file tree 3 files changed +24
-1
lines changed Expand file tree Collapse file tree 3 files changed +24
-1
lines changed Original file line number Diff line number Diff line change @@ -1463,7 +1463,10 @@ template <typename Type> class enum_ : public class_<Type> {
1463
1463
enum_& value (char const * name, Type value, const char *doc = nullptr ) {
1464
1464
auto v = pybind11::cast (value, return_value_policy::copy);
1465
1465
this ->attr (name) = v;
1466
- m_entries[pybind11::str (name)] = std::make_pair (v, doc);
1466
+ auto name_converted = pybind11::str (name);
1467
+ if (m_entries.contains (name_converted))
1468
+ throw value_error (" Enum error - element with name: " + std::string (name) + " already exists" );
1469
+ m_entries[name_converted] = std::make_pair (v, doc);
1467
1470
return *this ;
1468
1471
}
1469
1472
Original file line number Diff line number Diff line change @@ -68,4 +68,18 @@ TEST_SUBMODULE(enums, m) {
68
68
m.def (" test_enum_to_int" , [](int ) { });
69
69
m.def (" test_enum_to_uint" , [](uint32_t ) { });
70
70
m.def (" test_enum_to_long_long" , [](long long ) { });
71
+
72
+ // test_duplicate_enum_name
73
+ enum SimpleEnum
74
+ {
75
+ ONE, TWO, THREE
76
+ };
77
+
78
+ m.def (" register_bad_enum" , [m]() {
79
+ py::enum_<SimpleEnum>(m, " SimpleEnum" )
80
+ .value (" ONE" , SimpleEnum::ONE) // NOTE: all value function calls are called with the same first parameter value
81
+ .value (" ONE" , SimpleEnum::TWO)
82
+ .value (" ONE" , SimpleEnum::THREE)
83
+ .export_values ();
84
+ });
71
85
}
Original file line number Diff line number Diff line change @@ -148,3 +148,9 @@ def test_enum_to_int():
148
148
m .test_enum_to_uint (m .ClassWithUnscopedEnum .EMode .EFirstMode )
149
149
m .test_enum_to_long_long (m .Flags .Read )
150
150
m .test_enum_to_long_long (m .ClassWithUnscopedEnum .EMode .EFirstMode )
151
+
152
+
153
+ def test_duplicate_enum_name ():
154
+ with pytest .raises (ValueError ) as excinfo :
155
+ m .register_bad_enum ()
156
+ assert str (excinfo .value ) == "Enum error - element with name: ONE already exists"
You can’t perform that action at this time.
0 commit comments