Skip to content

Commit

Permalink
Support Python overriding of Storable::cloneStorable.
Browse files Browse the repository at this point in the history
  • Loading branch information
kfindeisen committed Nov 5, 2019
1 parent b3e50ca commit 57e2b73
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
7 changes: 6 additions & 1 deletion include/lsst/afw/typehandling/python.h
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,12 @@ class StorableHelper : public Base {
public:
using Base::Base;

// Can't wrap clone(); PYBIND11_OVERLOAD chokes on unique_ptr return type
std::shared_ptr<Storable> cloneStorable() const override {
/* __deepcopy__ takes an optional dict, but PYBIND11_OVERLOAD_* doesn't
* allow translation between different argument lists in C++ and Python
*/
PYBIND11_OVERLOAD_NAME(std::shared_ptr<Storable>, Base, "__deepcopy__", cloneStorable, );
}

std::string toString() const override {
PYBIND11_OVERLOAD_NAME(std::string, Base, "__repr__", toString, );
Expand Down
9 changes: 9 additions & 0 deletions tests/testGenericMapLib.cc
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,14 @@ std::shared_ptr<Storable> keepStaticStorable(std::shared_ptr<Storable> storable
return longLived;
}

/**
* Copy a Storable in C++.
*
* @param input The Storable to copy.
* @returns An identical but independent Storable.
*/
std::shared_ptr<Storable> duplicate(std::shared_ptr<Storable> input) { return input->cloneStorable(); }

} // namespace

namespace {
Expand Down Expand Up @@ -333,6 +341,7 @@ PYBIND11_MODULE(testGenericMapLib, mod) {
mod.def("makeCppUpdates", &makeCppUpdates, "testmap"_a);
mod.def("addCppStorable", &addCppStorable, "testmap"_a);
mod.def("keepStaticStorable", &keepStaticStorable, "storable"_a = nullptr);
mod.def("duplicate", &duplicate, "input"_a);

py::class_<CppStorable, PySharedPtr<CppStorable>, Storable, StorableHelper<CppStorable>> cls(
mod, "CppStorable");
Expand Down
7 changes: 7 additions & 0 deletions tests/test_Storable.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,16 @@ def testCopy(self):
self.assertIsNot(deep, self.testbed)
self.assertEqual(deep, self.testbed)

cpp = cppLib.duplicate(self.testbed)
self.assertIsInstance(cpp, Storable)
self.assertIsInstance(cpp, DemoStorable)
self.assertIsNot(cpp, self.testbed)
self.assertEqual(cpp, self.testbed)

self.aList.append(43)
self.assertEqual(shallow, DemoStorable([42, 43]))
self.assertEqual(deep, DemoStorable([42]))
self.assertEqual(cpp, DemoStorable([42]))

def testStr(self):
self.assertEqual(str(self.testbed), "value = [42]")
Expand Down

0 comments on commit 57e2b73

Please sign in to comment.