Skip to content

Commit 68a0b2d

Browse files
Add anyset & frozenset, enable copying (cast) to std::set (#3901)
* Add frozenset, and allow it cast to std::set For the reverse direction, std::set still casts to set. This is in concordance with the behavior for sequence containers, where e.g. tuple casts to std::vector but std::vector casts to list. Extracted from #3886. * Rename set_base to any_set to match Python C API since this will be part of pybind11 public API * PR: static_cast, anyset * Add tests for frozenset and rename anyset methods * Remove frozenset default ctor, add tests Making frozenset non-default constructible means that we need to adjust pyobject_caster to not require that its value is default constructible, by initializing value to a nil handle. This also allows writing C++ functions taking anyset, and is arguably a performance improvement, since there is no need to allocate an object that will just be replaced by load. Add some more tests, including anyset::empty, anyset::size, set::add and set::clear. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Add rationale to `pyobject_caster` default ctor * Remove ineffectual protected: access control Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 9a16e55 commit 68a0b2d

File tree

6 files changed

+89
-23
lines changed

6 files changed

+89
-23
lines changed

include/pybind11/cast.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -908,6 +908,14 @@ struct handle_type_name<kwargs> {
908908

909909
template <typename type>
910910
struct pyobject_caster {
911+
template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
912+
pyobject_caster() : value() {}
913+
914+
// `type` may not be default constructible (e.g. frozenset, anyset). Initializing `value`
915+
// to a nil handle is safe since it will only be accessed if `load` succeeds.
916+
template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
917+
pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
918+
911919
template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
912920
bool load(handle src, bool /* convert */) {
913921
value = src;

include/pybind11/pytypes.h

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1784,25 +1784,35 @@ class kwargs : public dict {
17841784
PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check)
17851785
};
17861786

1787-
class set : public object {
1787+
class anyset : public object {
17881788
public:
1789-
PYBIND11_OBJECT_CVT(set, object, PySet_Check, PySet_New)
1790-
set() : object(PySet_New(nullptr), stolen_t{}) {
1789+
PYBIND11_OBJECT(anyset, object, PyAnySet_Check)
1790+
size_t size() const { return static_cast<size_t>(PySet_Size(m_ptr)); }
1791+
bool empty() const { return size() == 0; }
1792+
template <typename T>
1793+
bool contains(T &&val) const {
1794+
return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1;
1795+
}
1796+
};
1797+
1798+
class set : public anyset {
1799+
public:
1800+
PYBIND11_OBJECT_CVT(set, anyset, PySet_Check, PySet_New)
1801+
set() : anyset(PySet_New(nullptr), stolen_t{}) {
17911802
if (!m_ptr) {
17921803
pybind11_fail("Could not allocate set object!");
17931804
}
17941805
}
1795-
size_t size() const { return (size_t) PySet_Size(m_ptr); }
1796-
bool empty() const { return size() == 0; }
17971806
template <typename T>
17981807
bool add(T &&val) /* py-non-const */ {
17991808
return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
18001809
}
18011810
void clear() /* py-non-const */ { PySet_Clear(m_ptr); }
1802-
template <typename T>
1803-
bool contains(T &&val) const {
1804-
return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1;
1805-
}
1811+
};
1812+
1813+
class frozenset : public anyset {
1814+
public:
1815+
PYBIND11_OBJECT_CVT(frozenset, anyset, PyFrozenSet_Check, PyFrozenSet_New)
18061816
};
18071817

18081818
class function : public object {

include/pybind11/stl.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,10 +55,10 @@ struct set_caster {
5555
using key_conv = make_caster<Key>;
5656

5757
bool load(handle src, bool convert) {
58-
if (!isinstance<pybind11::set>(src)) {
58+
if (!isinstance<anyset>(src)) {
5959
return false;
6060
}
61-
auto s = reinterpret_borrow<pybind11::set>(src);
61+
auto s = reinterpret_borrow<anyset>(src);
6262
value.clear();
6363
for (auto entry : s) {
6464
key_conv conv;

tests/test_pytypes.cpp

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -75,22 +75,34 @@ TEST_SUBMODULE(pytypes, m) {
7575
m.def("get_none", [] { return py::none(); });
7676
m.def("print_none", [](const py::none &none) { py::print("none: {}"_s.format(none)); });
7777

78-
// test_set
78+
// test_set, test_frozenset
7979
m.def("get_set", []() {
8080
py::set set;
8181
set.add(py::str("key1"));
8282
set.add("key2");
8383
set.add(std::string("key3"));
8484
return set;
8585
});
86-
m.def("print_set", [](const py::set &set) {
86+
m.def("get_frozenset", []() {
87+
py::set set;
88+
set.add(py::str("key1"));
89+
set.add("key2");
90+
set.add(std::string("key3"));
91+
return py::frozenset(set);
92+
});
93+
m.def("print_anyset", [](const py::anyset &set) {
8794
for (auto item : set) {
8895
py::print("key:", item);
8996
}
9097
});
91-
m.def("set_contains",
92-
[](const py::set &set, const py::object &key) { return set.contains(key); });
93-
m.def("set_contains", [](const py::set &set, const char *key) { return set.contains(key); });
98+
m.def("anyset_size", [](const py::anyset &set) { return set.size(); });
99+
m.def("anyset_empty", [](const py::anyset &set) { return set.empty(); });
100+
m.def("anyset_contains",
101+
[](const py::anyset &set, const py::object &key) { return set.contains(key); });
102+
m.def("anyset_contains",
103+
[](const py::anyset &set, const char *key) { return set.contains(key); });
104+
m.def("set_add", [](py::set &set, const py::object &key) { set.add(key); });
105+
m.def("set_clear", [](py::set &set) { set.clear(); });
94106

95107
// test_dict
96108
m.def("get_dict", []() { return py::dict("key"_a = "value"); });
@@ -310,6 +322,7 @@ TEST_SUBMODULE(pytypes, m) {
310322
"list"_a = py::list(d["list"]),
311323
"dict"_a = py::dict(d["dict"]),
312324
"set"_a = py::set(d["set"]),
325+
"frozenset"_a = py::frozenset(d["frozenset"]),
313326
"memoryview"_a = py::memoryview(d["memoryview"]));
314327
});
315328

@@ -325,6 +338,7 @@ TEST_SUBMODULE(pytypes, m) {
325338
"list"_a = d["list"].cast<py::list>(),
326339
"dict"_a = d["dict"].cast<py::dict>(),
327340
"set"_a = d["set"].cast<py::set>(),
341+
"frozenset"_a = d["frozenset"].cast<py::frozenset>(),
328342
"memoryview"_a = d["memoryview"].cast<py::memoryview>());
329343
});
330344

tests/test_pytypes.py

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,12 @@ def test_none(capture, doc):
6666

6767
def test_set(capture, doc):
6868
s = m.get_set()
69+
assert isinstance(s, set)
6970
assert s == {"key1", "key2", "key3"}
7071

72+
s.add("key4")
7173
with capture:
72-
s.add("key4")
73-
m.print_set(s)
74+
m.print_anyset(s)
7475
assert (
7576
capture.unordered
7677
== """
@@ -81,12 +82,43 @@ def test_set(capture, doc):
8182
"""
8283
)
8384

84-
assert not m.set_contains(set(), 42)
85-
assert m.set_contains({42}, 42)
86-
assert m.set_contains({"foo"}, "foo")
85+
m.set_add(s, "key5")
86+
assert m.anyset_size(s) == 5
8787

88-
assert doc(m.get_list) == "get_list() -> list"
89-
assert doc(m.print_list) == "print_list(arg0: list) -> None"
88+
m.set_clear(s)
89+
assert m.anyset_empty(s)
90+
91+
assert not m.anyset_contains(set(), 42)
92+
assert m.anyset_contains({42}, 42)
93+
assert m.anyset_contains({"foo"}, "foo")
94+
95+
assert doc(m.get_set) == "get_set() -> set"
96+
assert doc(m.print_anyset) == "print_anyset(arg0: anyset) -> None"
97+
98+
99+
def test_frozenset(capture, doc):
100+
s = m.get_frozenset()
101+
assert isinstance(s, frozenset)
102+
assert s == frozenset({"key1", "key2", "key3"})
103+
104+
with capture:
105+
m.print_anyset(s)
106+
assert (
107+
capture.unordered
108+
== """
109+
key: key1
110+
key: key2
111+
key: key3
112+
"""
113+
)
114+
assert m.anyset_size(s) == 3
115+
assert not m.anyset_empty(s)
116+
117+
assert not m.anyset_contains(frozenset(), 42)
118+
assert m.anyset_contains(frozenset({42}), 42)
119+
assert m.anyset_contains(frozenset({"foo"}), "foo")
120+
121+
assert doc(m.get_frozenset) == "get_frozenset() -> frozenset"
90122

91123

92124
def test_dict(capture, doc):
@@ -302,6 +334,7 @@ def test_constructors():
302334
list: range(3),
303335
dict: [("two", 2), ("one", 1), ("three", 3)],
304336
set: [4, 4, 5, 6, 6, 6],
337+
frozenset: [4, 4, 5, 6, 6, 6],
305338
memoryview: b"abc",
306339
}
307340
inputs = {k.__name__: v for k, v in data.items()}

tests/test_stl.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ def test_set(doc):
7373
assert s == {"key1", "key2"}
7474
s.add("key3")
7575
assert m.load_set(s)
76+
assert m.load_set(frozenset(s))
7677

7778
assert doc(m.cast_set) == "cast_set() -> Set[str]"
7879
assert doc(m.load_set) == "load_set(arg0: Set[str]) -> bool"

0 commit comments

Comments
 (0)