Skip to content

Commit

Permalink
Add make_namespace function and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Jouke Witteveen committed Feb 1, 2021
1 parent 721834b commit ca210c7
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 1 deletion.
40 changes: 39 additions & 1 deletion docs/advanced/pycpp/object.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,44 @@ Available types include :class:`handle`, :class:`object`, :class:`bool_`,
Be sure to review the :ref:`pytypes_gotchas` before using this heavily in
your C++ API.

.. _instantiating_compound_types:

Instantiating compound Python types from C++
============================================

Dictionaries can be initialized in the :class:`dict` constructor:

.. code-block:: cpp
using namespace pybind11::literals; // to bring in the `_a` literal
auto d = py::dict("spam"_a=py::none(), "eggs"_a=42);
A tuple of python objects can be instantiated using :func:`py::make_tuple`:

.. code-block:: cpp
py::tuple tup = py::make_tuple(42, py::none(), "spam");
Each element is converted to a supported Python type.

A simple namespace can be instantiated using :func:`py::make_namespace`:

.. code-block:: cpp
using namespace pybind11::literals; // to bring in the `_a` literal
py::object ns = py::make_namespace("spam"_a=py::none(), "eggs"_a=42);
Attributes on a namespace can be modified with the :func:`py::delattr`,
:func:`py::getattr`, and :func:`py::setattr` functions. Namespaces can be useful
as stand-ins for class instances.

.. note::

``make_namespace`` is not available in Python 2.

.. versionchanged:: 2.7
``make_namespace`` added.

.. _casting_back_and_forth:

Casting back and forth
Expand All @@ -30,7 +68,7 @@ types to Python, which can be done using :func:`py::cast`:

.. code-block:: cpp
MyClass *cls = ..;
MyClass *cls = ...;
py::object obj = py::cast(cls);
The reverse direction uses the following syntax:
Expand Down
8 changes: 8 additions & 0 deletions include/pybind11/cast.h
Original file line number Diff line number Diff line change
Expand Up @@ -1890,6 +1890,14 @@ template <return_value_policy policy = return_value_policy::automatic_reference,
return result;
}

#if PY_MAJOR_VERSION >= 3
template <typename... Args,
typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>>
object make_namespace(Args&&... args_) {
return reinterpret_steal<object>(_PyNamespace_New(dict(std::forward<Args>(args_)...).ptr()));
}
#endif

/// \ingroup annotations
/// Annotation for arguments
struct arg {
Expand Down
11 changes: 11 additions & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ TEST_SUBMODULE(pytypes, m) {
return dict.contains(val);
});

// test_tuple
m.def("make_tuple", []() { return py::make_tuple(42, py::none(), "spam"); });

// test_namespace
m.def("make_namespace", []() {
auto ns = py::make_namespace("attr"_a=42, "x"_a="foo", "wrong"_a=1);
py::delattr(ns, "wrong");
py::setattr(ns, "right", py::int_(2));
return ns;
});

// test_str
m.def("str_from_string", []() { return py::str(std::string("baz")); });
m.def("str_from_bytes", []() { return py::str(py::bytes("boo", 3)); });
Expand Down
14 changes: 14 additions & 0 deletions tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,20 @@ def test_dict(capture, doc):
assert m.dict_keyword_constructor() == {"x": 1, "y": 2, "z": 3}


def test_tuple():
t = m.make_tuple()
assert t == (42, None, "spam")


@pytest.mark.skipif("env.PY2")
def test_namespace():
ns = m.make_namespace()
assert ns.attr == 42
assert ns.x == "foo"
assert ns.right == 2
assert not hasattr(ns, "wrong")


def test_str(doc):
assert m.str_from_string().encode().decode() == "baz"
assert m.str_from_bytes().encode().decode() == "boo"
Expand Down

0 comments on commit ca210c7

Please sign in to comment.