Skip to content

Commit fc4a559

Browse files
authored
Cleanup several aspects of the Python bindings (copy of PR #1696) (#1696)
Signed-off-by: Ken Museth <ken.museth@gmail.com>
1 parent 77f28d1 commit fc4a559

File tree

6 files changed

+462
-215
lines changed

6 files changed

+462
-215
lines changed

openvdb/openvdb/python/pyGrid.h

Lines changed: 19 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ inline bool
6868
sharesWith(const GridType& grid, py::object other)
6969
{
7070
if (py::isinstance<GridType>(other)) {
71-
typename GridType::ConstPtr otherGrid = other.cast<typename GridType::Ptr>();
71+
typename GridType::ConstPtr otherGrid = py::cast<typename GridType::Ptr>(other);
7272
return (&otherGrid->tree() == &grid.tree());
7373
}
7474
return false;
@@ -893,7 +893,7 @@ applyMap(const char* methodName, GridType& grid, py::object funcObj)
893893

894894
// Verify that the result is of type GridType::ValueType.
895895
try {
896-
result.cast<ValueT>();
896+
py::cast<ValueT>(result);
897897
} catch (py::cast_error&) {
898898
std::ostringstream os;
899899
os << "expected callable argument to ";
@@ -904,7 +904,7 @@ applyMap(const char* methodName, GridType& grid, py::object funcObj)
904904
throw py::type_error(os.str());
905905
}
906906

907-
it.setValue(result.cast<ValueT>());
907+
it.setValue(py::cast<ValueT>(result));
908908
}
909909
}
910910

@@ -955,7 +955,7 @@ struct TreeCombineOp
955955
throw py::type_error(os.str());
956956
}
957957

958-
result = resultObj.cast<ValueT>();
958+
result = py::cast<ValueT>(resultObj);
959959
}
960960
py::function op;
961961
};
@@ -1177,15 +1177,15 @@ class IterValueProxy
11771177
py::object getItem(py::object keyObj) const
11781178
{
11791179
if (py::isinstance<std::string>(keyObj)) {
1180-
const std::string key = keyObj.cast<std::string>();
1180+
const std::string key = py::cast<std::string>(keyObj);
11811181
if (key == "value") return py::cast(this->getValue());
11821182
else if (key == "active") return py::cast(this->getActive());
11831183
else if (key == "depth") return py::cast(this->getDepth());
11841184
else if (key == "min") return py::cast(this->getBBoxMin());
11851185
else if (key == "max") return py::cast(this->getBBoxMax());
11861186
else if (key == "count") return py::cast(this->getVoxelCount());
11871187
}
1188-
throw py::key_error(keyObj.attr("__repr__")().cast<std::string>());
1188+
throw py::key_error(py::cast<std::string>(keyObj.attr("__repr__")()));
11891189
return py::object();
11901190
}
11911191

@@ -1195,20 +1195,20 @@ class IterValueProxy
11951195
void setItem(py::object keyObj, py::object valObj)
11961196
{
11971197
if (py::isinstance<std::string>(keyObj)) {
1198-
const std::string key = keyObj.cast<std::string>();
1198+
const std::string key = py::cast<std::string>(keyObj);
11991199
if (key == "value") {
1200-
this->setValue(valObj.cast<ValueT>()); return;
1200+
this->setValue(py::cast<ValueT>(valObj)); return;
12011201
} else if (key == "active") {
1202-
this->setActive(valObj.cast<bool>()); return;
1202+
this->setActive(py::cast<bool>(valObj)); return;
12031203
} else if (this->hasKey(key)) {
12041204
std::ostringstream os;
12051205
os << "can't set attribute '";
1206-
os << keyObj.attr("__repr__")().cast<std::string>();
1206+
os << py::cast<std::string>(keyObj.attr("__repr__")());
12071207
os << "'";
12081208
throw py::attribute_error(os.str());
12091209
}
12101210
}
1211-
throw py::key_error(keyObj.attr("__repr__")().cast<std::string>());
1211+
throw py::key_error(py::cast<std::string>(keyObj.attr("__repr__")()));
12121212
}
12131213

12141214
bool operator==(const IterValueProxy& other) const
@@ -1235,7 +1235,7 @@ class IterValueProxy
12351235
}
12361236
// print ", ".join(valuesAsStrings)
12371237
py::object joined = py::str(", ").attr("join")(valuesAsStrings);
1238-
std::string s = joined.cast<std::string>();
1238+
std::string s = py::cast<std::string>(joined);
12391239
os << "{" << s << "}";
12401240
return os;
12411241
}
@@ -1379,13 +1379,9 @@ struct PickleSuite
13791379
}
13801380

13811381
// Construct a state tuple for the serialized Grid.
1382-
#if PY_MAJOR_VERSION >= 3
13831382
// Convert the byte string to a "bytes" sequence.
13841383
const std::string s = ostr.str();
13851384
py::bytes bytesObj(s);
1386-
#else
1387-
py::str bytesObj(ostr.str());
1388-
#endif
13891385
return py::make_tuple(bytesObj);
13901386
}
13911387

@@ -1397,25 +1393,16 @@ struct PickleSuite
13971393
std::string serialized;
13981394
if (!badState) {
13991395
// Extract the sequence containing the serialized Grid.
1400-
#if PY_MAJOR_VERSION >= 3
14011396
if (py::isinstance<py::bytes>(state[0]))
1402-
serialized = state[0].cast<py::bytes>();
1403-
#else
1404-
if (py::isinstance<std::string>(state[0]))
1405-
serialized = state[0].cast<std::string>();
1406-
#endif
1397+
serialized = py::cast<py::bytes>(state[0]);
14071398
else
14081399
badState = true;
14091400
}
14101401

14111402
if (badState) {
14121403
std::ostringstream os;
1413-
#if PY_MAJOR_VERSION >= 3
14141404
os << "expected (dict, bytes) tuple in call to __setstate__; found ";
1415-
#else
1416-
os << "expected (dict, str) tuple in call to __setstate__; found ";
1417-
#endif
1418-
os << state.attr("__repr__")().cast<std::string>();
1405+
os << py::cast<std::string>(state.attr("__repr__")());
14191406
throw py::value_error(os.str());
14201407
}
14211408

@@ -1457,14 +1444,15 @@ exportGrid(py::module_ m)
14571444
using ValueAllIterT = typename GridType::ValueAllIter;
14581445

14591446
const std::string pyGridTypeName = Traits::name();
1460-
const std::string defaultCtorDescr = "Initialize with a background value of "
1461-
+ pyutil::str(pyGrid::getZeroValue<GridType>()) + ".";
1447+
std::stringstream docstream;
1448+
docstream << "Initialize with a background value of " << pyGrid::getZeroValue<GridType>() << ".";
1449+
std::string docstring = docstream.str();
14621450

14631451
// Define the Grid wrapper class and make it the current scope.
14641452
py::class_<GridType, GridPtr, GridBase>(m,
14651453
/*classname=*/pyGridTypeName.c_str(),
14661454
/*docstring=*/(Traits::descr()).c_str())
1467-
.def(py::init<>(), defaultCtorDescr.c_str())
1455+
.def(py::init<>(), docstring.c_str())
14681456
.def(py::init<const ValueT&>(), py::arg("background"),
14691457
"Initialize with the given background value.")
14701458

@@ -1711,7 +1699,7 @@ exportGrid(py::module_ m)
17111699
IterWrap<GridType, ValueAllIterT>::wrap(m);
17121700

17131701
// Add the Python type object for this grid type to the module-level list.
1714-
m.attr("GridTypes").cast<py::list>().append(m.attr(pyGridTypeName.c_str()));
1702+
py::cast<py::list>(m.attr("GridTypes")).append(m.attr(pyGridTypeName.c_str()));
17151703
}
17161704

17171705
} // namespace pyGrid

openvdb/openvdb/python/pyGridBase.cc

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -100,12 +100,8 @@ exportGridBase(py::module_ m)
100100

101101

102102
auto getMetadataKeys = [](GridBase::ConstPtr grid) {
103-
#if PY_MAJOR_VERSION >= 3
104103
// Return an iterator over the "keys" view of a dict.
105104
return py::make_key_iterator(static_cast<const MetaMap&>(*grid).beginMeta(), static_cast<const MetaMap&>(*grid).endMeta());
106-
#else
107-
return py::dict(py::cast(static_cast<const MetaMap&>(*grid))).iterkeys();
108-
#endif
109105
};
110106

111107

@@ -118,7 +114,7 @@ exportGridBase(py::module_ m)
118114
MetaMap metamap;
119115
metamap.insertMeta(name, *metadata);
120116
// todo: Add/refactor out type_casters for each TypedMetadata from MetaMap's type_caster
121-
return py::dict(py::cast(metamap))[py::str(name)].cast<py::object>();
117+
return py::cast<py::object>(py::dict(py::cast(metamap))[py::str(name)]);
122118
};
123119

124120

@@ -135,7 +131,7 @@ exportGridBase(py::module_ m)
135131
// todo: Add/refactor out type_casters for each TypedMetadata from MetaMap's type_caster
136132
py::dict dictObj;
137133
dictObj[py::str(name)] = value;
138-
MetaMap metamap = dictObj.cast<MetaMap>();
134+
MetaMap metamap = py::cast<MetaMap>(dictObj);
139135

140136
if (Metadata::Ptr metadata = metamap[name]) {
141137
grid->removeMeta(name);

openvdb/openvdb/python/pyOpenVDBModule.cc

Lines changed: 0 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -371,78 +371,6 @@ PYBIND11_MODULE(PY_OPENVDB_MODULE_NAME, m)
371371

372372
#undef PYOPENVDB_TRANSLATE_EXCEPTION
373373

374-
// Basic bindings for these Vec types are required to support them as
375-
// default arguments to functions.
376-
py::class_<openvdb::Coord>(m, "Coord")
377-
.def(py::init<>())
378-
.def(py::init<openvdb::Coord::Int32>())
379-
.def(py::init<openvdb::Coord::Int32, openvdb::Coord::Int32, openvdb::Coord::Int32>())
380-
.def(py::self == py::self)
381-
.def(py::self != py::self);
382-
383-
py::class_<openvdb::Vec2i>(m, "Vec2i")
384-
.def(py::init<>())
385-
.def(py::init<int32_t>())
386-
.def(py::init<int32_t, int32_t>())
387-
.def(py::self == py::self)
388-
.def(py::self != py::self);
389-
390-
py::class_<openvdb::Vec2f>(m, "Vec2f")
391-
.def(py::init<>())
392-
.def(py::init<float>())
393-
.def(py::init<float, float>())
394-
.def(py::self == py::self)
395-
.def(py::self != py::self);
396-
397-
py::class_<openvdb::Vec2d>(m, "Vec2d")
398-
.def(py::init<>())
399-
.def(py::init<double>())
400-
.def(py::init<double, double>())
401-
.def(py::self == py::self)
402-
.def(py::self != py::self);
403-
404-
py::class_<openvdb::Vec3i>(m, "Vec3i")
405-
.def(py::init<>())
406-
.def(py::init<int32_t>())
407-
.def(py::init<int32_t, int32_t, int32_t>())
408-
.def(py::self == py::self)
409-
.def(py::self != py::self);
410-
411-
py::class_<openvdb::Vec3f>(m, "Vec3f")
412-
.def(py::init<>())
413-
.def(py::init<float>())
414-
.def(py::init<float, float, float>())
415-
.def(py::self == py::self)
416-
.def(py::self != py::self);
417-
418-
py::class_<openvdb::Vec3d>(m, "Vec3d")
419-
.def(py::init<>())
420-
.def(py::init<double>())
421-
.def(py::init<double, double, double>())
422-
.def(py::self == py::self)
423-
.def(py::self != py::self);
424-
425-
py::class_<openvdb::Vec4i>(m, "Vec4i")
426-
.def(py::init<>())
427-
.def(py::init<int32_t>())
428-
.def(py::init<int32_t, int32_t, int32_t, int32_t>())
429-
.def(py::self == py::self)
430-
.def(py::self != py::self);
431-
432-
py::class_<openvdb::Vec4f>(m, "Vec4f")
433-
.def(py::init<>())
434-
.def(py::init<float>())
435-
.def(py::init<float, float, float, float>())
436-
.def(py::self == py::self)
437-
.def(py::self != py::self);
438-
439-
py::class_<openvdb::Vec4d>(m, "Vec4d")
440-
.def(py::init<>())
441-
.def(py::init<double>())
442-
.def(py::init<double, double, double, double>())
443-
.def(py::self == py::self)
444-
.def(py::self != py::self);
445-
446374
py::class_<openvdb::PointDataIndex32>(m, "PointDataIndex32")
447375
.def(py::init<openvdb::Index32>(), py::arg("i") = openvdb::Index32(0));
448376

openvdb/openvdb/python/pyTransform.cc

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -99,12 +99,8 @@ struct PickleSuite
9999

100100
// Construct a state tuple comprising the version numbers of
101101
// the serialization format and the serialized Transform.
102-
#if PY_MAJOR_VERSION >= 3
103102
// Convert the byte string to a "bytes" sequence.
104103
py::bytes bytesObj(ostr.str());
105-
#else
106-
py::str bytesObj(ostr.str());
107-
#endif
108104
return py::make_tuple(
109105
uint32_t(OPENVDB_LIBRARY_MAJOR_VERSION),
110106
uint32_t(OPENVDB_LIBRARY_MINOR_VERSION),
@@ -125,7 +121,7 @@ struct PickleSuite
125121
uint32_t version[3] = { 0, 0, 0 };
126122
for (int i = 0; i < 3 && !badState; ++i) {
127123
if (py::isinstance<py::int_>(state[idx[i]]))
128-
version[i] = state[idx[i]].cast<uint32_t>();
124+
version[i] = py::cast<uint32_t>(state[idx[i]]);
129125
else badState = true;
130126
}
131127
libVersion.first = version[0];
@@ -137,24 +133,15 @@ struct PickleSuite
137133
if (!badState) {
138134
// Extract the sequence containing the serialized Transform.
139135
py::object bytesObj = state[int(STATE_XFORM)];
140-
#if PY_MAJOR_VERSION >= 3
141136
if (py::isinstance<py::bytes>(bytesObj))
142-
serialized = bytesObj.cast<py::bytes>();
143-
#else
144-
if (py::isinstance<std::string>(bytesObj))
145-
serialized = bytesObj.cast<std::string>();
146-
#endif
137+
serialized = py::cast<py::bytes>(bytesObj);
147138
else badState = true;
148139
}
149140

150141
if (badState) {
151142
std::ostringstream os;
152-
#if PY_MAJOR_VERSION >= 3
153143
os << "expected (int, int, int, bytes) tuple in call to __setstate__; found ";
154-
#else
155-
os << "expected (int, int, int, str) tuple in call to __setstate__; found ";
156-
#endif
157-
os << state.attr("__repr__")().cast<std::string>();
144+
os << py::cast<std::string>(state.attr("__repr__")());
158145
throw py::value_error(os.str());
159146
}
160147

0 commit comments

Comments
 (0)