From db028d685cb78a71b299a98efe762b614a8b26da Mon Sep 17 00:00:00 2001 From: Wenzel Jakob Date: Tue, 13 Oct 2015 23:44:25 +0200 Subject: [PATCH] added module::import statement --- example/example9.cpp | 5 ++++- example/example9.py | 2 ++ example/example9.ref | 1 + include/pybind/pybind.h | 4 ++++ 4 files changed, 11 insertions(+), 1 deletion(-) diff --git a/example/example9.cpp b/example/example9.cpp index 81b6edc09..f64b539a2 100644 --- a/example/example9.cpp +++ b/example/example9.cpp @@ -1,5 +1,6 @@ /* - example/example9.cpp -- nested modules and internal references + example/example9.cpp -- nested modules, importing modules, and + internal references Copyright (c) 2015 Wenzel Jakob @@ -49,4 +50,6 @@ void init_ex9(py::module &m) { .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal) .def_readwrite("a1", &B::a1) // def_readonly uses an internal reference return policy by default .def_readwrite("a2", &B::a2); + + m.attr("OD") = py::module::import("collections").attr("OrderedDict"); } diff --git a/example/example9.py b/example/example9.py index 9a29353c7..2262fcf5c 100755 --- a/example/example9.py +++ b/example/example9.py @@ -9,6 +9,7 @@ print(example.__name__) print(example.submodule.__name__) from example.submodule import * +from example import OD submodule_func() @@ -26,3 +27,4 @@ print(b.a1) print(b.get_a2()) print(b.a2) +print(OD([(1, 'a'), (2, 'b')])) diff --git a/example/example9.ref b/example/example9.ref index c498077d7..9c783135c 100644 --- a/example/example9.ref +++ b/example/example9.ref @@ -16,6 +16,7 @@ A[42] A[42] A[43] A[43] +OrderedDict([(1, 'a'), (2, 'b')]) B destructor A destructor A destructor diff --git a/include/pybind/pybind.h b/include/pybind/pybind.h index 9ca1929f8..86fc60991 100644 --- a/include/pybind/pybind.h +++ b/include/pybind/pybind.h @@ -466,6 +466,10 @@ public: attr(name) = result; return result; } + + static module import(const char *name) { + return module(PyImport_ImportModule(name), false); + } }; NAMESPACE_BEGIN(detail)