Skip to content

Commit b347c6d

Browse files
author
gerrymanoim
authored
Merge pull request #177 from quantopian/sequence-to-object
ENH: Create sequence_to_object
2 parents 9182490 + 451bc0f commit b347c6d

File tree

1 file changed

+19
-24
lines changed

1 file changed

+19
-24
lines changed

include/libpy/to_object.h

Lines changed: 19 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -67,25 +67,28 @@ py::owned_ref<> to_object(T&& ob) {
6767
}
6868

6969
namespace dispatch {
70-
template<typename C>
71-
py::owned_ref<> sequence_to_list(const C& v) {
72-
py::owned_ref out(PyList_New(v.size()));
73-
if (!out) {
74-
return nullptr;
75-
}
7670

77-
std::size_t ix = 0;
78-
for (const auto& elem : v) {
79-
PyObject* ob = py::to_object(elem).escape();
80-
if (!ob) {
71+
template<typename C>
72+
struct sequence_to_object {
73+
static py::owned_ref<> f(const C& v) {
74+
py::owned_ref out(PyList_New(v.size()));
75+
if (!out) {
8176
return nullptr;
8277
}
8378

84-
PyList_SET_ITEM(out.get(), ix++, ob);
85-
}
79+
std::size_t ix = 0;
80+
for (const auto& elem : v) {
81+
PyObject* ob = py::to_object(elem).escape();
82+
if (!ob) {
83+
return nullptr;
84+
}
8685

87-
return out;
88-
}
86+
PyList_SET_ITEM(out.get(), ix++, ob);
87+
}
88+
89+
return out;
90+
}
91+
};
8992

9093
template<std::size_t n>
9194
struct to_object<std::array<char, n>> {
@@ -102,11 +105,7 @@ struct to_object<char> {
102105
};
103106

104107
template<typename T, std::size_t n>
105-
struct to_object<std::array<T, n>> {
106-
static py::owned_ref<> f(const std::array<T, n>& v) {
107-
return sequence_to_list(v);
108-
}
109-
};
108+
struct to_object<std::array<T, n>> : public sequence_to_object<std::array<T, n>> {};
110109

111110
/** Identity conversion for `owned_ref`.
112111
*/
@@ -273,11 +272,7 @@ struct to_object<std::unordered_map<K, V, Hash, KeyEqual>>
273272
: public map_to_object<std::unordered_map<K, V, Hash, KeyEqual>> {};
274273

275274
template<typename T>
276-
struct to_object<std::vector<T>> {
277-
static py::owned_ref<> f(const std::vector<T>& v) {
278-
return sequence_to_list(v);
279-
}
280-
};
275+
struct to_object<std::vector<T>> : public sequence_to_object<std::vector<T>> {};
281276

282277
template<typename S>
283278
struct set_to_object {

0 commit comments

Comments
 (0)