Skip to content

Commit ccca1c8

Browse files
committed
Set __qualname__ for py3 enums (PY >= 3.3)
1 parent aafaef8 commit ccca1c8

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

include/pybind11/pybind11.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1271,6 +1271,10 @@ class py3_enum {
12711271
kwargs["module"] = scope.attr("__module__");
12721272
else if (hasattr(scope, "__name__"))
12731273
kwargs["module"] = scope.attr("__name__");
1274+
#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
1275+
if (hasattr(scope, "__qualname__"))
1276+
kwargs["qualname"] = scope.attr("__qualname__").cast<std::string>() + "." + name;
1277+
#endif
12741278
}
12751279
update();
12761280
}

tests/test_enum.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ enum class Py3EnumNonUnique {
5454
X = 1
5555
};
5656

57+
class DummyScope {};
58+
5759
std::string test_scoped_enum(ScopedEnum z) {
5860
return "ScopedEnum::" + std::string(z == ScopedEnum::Two ? "Two" : "Three");
5961
}
@@ -77,7 +79,8 @@ test_initializer enums([](py::module &m) {
7779
.export_values();
7880

7981
#if PY_VERSION_HEX >= 0x03000000
80-
py::py3_enum<Py3EnumEmpty>(m, "Py3EnumEmpty");
82+
auto scope = py::class_<DummyScope>(m, "DummyScope");
83+
py::py3_enum<Py3EnumEmpty>(scope, "Py3EnumEmpty");
8184

8285
py::py3_enum<Py3Enum>(m, "Py3Enum")
8386
.value("A", Py3Enum::A)

tests/test_enum.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,10 +120,12 @@ def test_binary_operators():
120120
@pytest.requires_py3
121121
def test_py3_enum():
122122
from pybind11_tests import (
123-
Py3Enum, Py3EnumEmpty, Py3EnumScoped,
123+
Py3Enum, DummyScope, Py3EnumScoped,
124124
make_py3_enum, take_py3_enum, non_unique_py3_enum
125125
)
126126

127+
Py3EnumEmpty = DummyScope.Py3EnumEmpty
128+
127129
from enum import IntEnum
128130

129131
expected = {
@@ -137,6 +139,10 @@ def test_py3_enum():
137139
assert sorted(tp.__members__.items()) == entries
138140
assert tp.__module__ == 'pybind11_tests'
139141

142+
assert Py3Enum.__qualname__ == 'Py3Enum'
143+
assert Py3EnumEmpty.__qualname__ == 'DummyScope.Py3EnumEmpty'
144+
assert Py3EnumScoped.__qualname__ == 'Py3EnumScoped'
145+
140146
assert make_py3_enum(True) is Py3EnumScoped.X
141147
assert make_py3_enum(False) is Py3EnumScoped.Y
142148

0 commit comments

Comments
 (0)