Skip to content
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions docs/advanced/pycpp/object.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ 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.

.. _casting_back_and_forth:

Casting back and forth
======================

Expand Down Expand Up @@ -62,6 +64,7 @@ This example obtains a reference to the Python ``Decimal`` class.
py::object scipy = py::module::import("scipy");
return scipy.attr("__version__");


.. _calling_python_functions:

Calling Python functions
Expand Down Expand Up @@ -176,6 +179,47 @@ Generalized unpacking according to PEP448_ is also supported:

.. _PEP448: https://www.python.org/dev/peps/pep-0448/

.. _implicit_casting:

Implicit casting
================

When using this C++ interface for Python types or calling Python functions,
and objects of type :class:`object` are returned, it is possible to
specialize to a subtype like :class:`dict`. The same holds for the proxy objects
returned by ``operator[]`` or ``obj.attr()``.
Casting to subtypes improves code readability and allows values to be used in
C++ functions that require a specific subtype rather than a generic :class:`object`.

.. code-block:: cpp

#include <pybind11/numpy.h>
using namespace pybind11::literals;

py::module os = py::module::import("os");
py::module path = py::module::import("os.path"); // like 'import os.path as path'
py::module np = py::module::import("numpy"); // like 'import numpy as np'

py::str curdir_abs = path.attr("abspath")(path.attr("curdir"));
py::print(py::str("Current directory: ") + curdir_abs);
py::dict environ = os.attr("environ");
py::print(environ["HOME"]);
py::array_t<float> arr = np.attr("ones")(3, "dtype"_a="float32");
py::print(py::repr(arr + py::int_(1)));

These implicit conversions are available for subclasses of :class:`object`; there
is no need to call ``obj.cast()`` explicitly as for custom classes, see
:ref:`casting_back_and_forth`.

.. note::
If a trivial conversion via move constructor is not possible, both implicit and
explicit casting (calling ``obj.cast()``) will attempt a "rich" conversion.
For instance, ``py::list env = os.attr("environ");`` will succeed and is
equivalent to the Python code ``env = list(os.environ)`` that produces a
list of the dict keys.

.. TODO: Adapt text once PR #2349 has landed
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great, thanks! :-)


Handling exceptions
===================

Expand Down