Blame external/pybind11/docs/advanced/pycpp/object.rst

Packit 534379
Python types
Packit 534379
############
Packit 534379
Packit 534379
Available wrappers
Packit 534379
==================
Packit 534379
Packit 534379
All major Python types are available as thin C++ wrapper classes. These
Packit 534379
can also be used as function parameters -- see :ref:`python_objects_as_args`.
Packit 534379
Packit 534379
Available types include :class:`handle`, :class:`object`, :class:`bool_`,
Packit 534379
:class:`int_`, :class:`float_`, :class:`str`, :class:`bytes`, :class:`tuple`,
Packit 534379
:class:`list`, :class:`dict`, :class:`slice`, :class:`none`, :class:`capsule`,
Packit 534379
:class:`iterable`, :class:`iterator`, :class:`function`, :class:`buffer`,
Packit 534379
:class:`array`, and :class:`array_t`.
Packit 534379
Packit 534379
Casting back and forth
Packit 534379
======================
Packit 534379
Packit 534379
In this kind of mixed code, it is often necessary to convert arbitrary C++
Packit 534379
types to Python, which can be done using :func:`py::cast`:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    MyClass *cls = ..;
Packit 534379
    py::object obj = py::cast(cls);
Packit 534379
Packit 534379
The reverse direction uses the following syntax:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::object obj = ...;
Packit 534379
    MyClass *cls = obj.cast<MyClass *>();
Packit 534379
Packit 534379
When conversion fails, both directions throw the exception :class:`cast_error`.
Packit 534379
Packit 534379
.. _python_libs:
Packit 534379
Packit 534379
Accessing Python libraries from C++
Packit 534379
===================================
Packit 534379
Packit 534379
It is also possible to import objects defined in the Python standard
Packit 534379
library or available in the current Python environment (``sys.path``) and work
Packit 534379
with these in C++.
Packit 534379
Packit 534379
This example obtains a reference to the Python ``Decimal`` class.
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    // Equivalent to "from decimal import Decimal"
Packit 534379
    py::object Decimal = py::module::import("decimal").attr("Decimal");
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    // Try to import scipy
Packit 534379
    py::object scipy = py::module::import("scipy");
Packit 534379
    return scipy.attr("__version__");
Packit 534379
Packit 534379
.. _calling_python_functions:
Packit 534379
Packit 534379
Calling Python functions
Packit 534379
========================
Packit 534379
Packit 534379
It is also possible to call Python classes, functions and methods 
Packit 534379
via ``operator()``.
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    // Construct a Python object of class Decimal
Packit 534379
    py::object pi = Decimal("3.14159");
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    // Use Python to make our directories
Packit 534379
    py::object os = py::module::import("os");
Packit 534379
    py::object makedirs = os.attr("makedirs");
Packit 534379
    makedirs("/tmp/path/to/somewhere");
Packit 534379
Packit 534379
One can convert the result obtained from Python to a pure C++ version 
Packit 534379
if a ``py::class_`` or type conversion is defined.
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::function f = <...>;
Packit 534379
    py::object result_py = f(1234, "hello", some_instance);
Packit 534379
    MyClass &result = result_py.cast<MyClass>();
Packit 534379
Packit 534379
.. _calling_python_methods:
Packit 534379
Packit 534379
Calling Python methods
Packit 534379
========================
Packit 534379
Packit 534379
To call an object's method, one can again use ``.attr`` to obtain access to the
Packit 534379
Python method.
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    // Calculate e^π in decimal
Packit 534379
    py::object exp_pi = pi.attr("exp")();
Packit 534379
    py::print(py::str(exp_pi));
Packit 534379
Packit 534379
In the example above ``pi.attr("exp")`` is a *bound method*: it will always call
Packit 534379
the method for that same instance of the class. Alternately one can create an 
Packit 534379
*unbound method* via the Python class (instead of instance) and pass the ``self`` 
Packit 534379
object explicitly, followed by other arguments.
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::object decimal_exp = Decimal.attr("exp");
Packit 534379
Packit 534379
    // Compute the e^n for n=0..4
Packit 534379
    for (int n = 0; n < 5; n++) {
Packit 534379
        py::print(decimal_exp(Decimal(n));
Packit 534379
    }
Packit 534379
Packit 534379
Keyword arguments
Packit 534379
=================
Packit 534379
Packit 534379
Keyword arguments are also supported. In Python, there is the usual call syntax:
Packit 534379
Packit 534379
.. code-block:: python
Packit 534379
Packit 534379
    def f(number, say, to):
Packit 534379
        ...  # function code
Packit 534379
Packit 534379
    f(1234, say="hello", to=some_instance)  # keyword call in Python
Packit 534379
Packit 534379
In C++, the same call can be made using:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    using namespace pybind11::literals; // to bring in the `_a` literal
Packit 534379
    f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
Packit 534379
Packit 534379
Unpacking arguments
Packit 534379
===================
Packit 534379
Packit 534379
Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with
Packit 534379
other arguments:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    // * unpacking
Packit 534379
    py::tuple args = py::make_tuple(1234, "hello", some_instance);
Packit 534379
    f(*args);
Packit 534379
Packit 534379
    // ** unpacking
Packit 534379
    py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance);
Packit 534379
    f(**kwargs);
Packit 534379
Packit 534379
    // mixed keywords, * and ** unpacking
Packit 534379
    py::tuple args = py::make_tuple(1234);
Packit 534379
    py::dict kwargs = py::dict("to"_a=some_instance);
Packit 534379
    f(*args, "say"_a="hello", **kwargs);
Packit 534379
Packit 534379
Generalized unpacking according to PEP448_ is also supported:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::dict kwargs1 = py::dict("number"_a=1234);
Packit 534379
    py::dict kwargs2 = py::dict("to"_a=some_instance);
Packit 534379
    f(**kwargs1, "say"_a="hello", **kwargs2);
Packit 534379
Packit 534379
.. seealso::
Packit 534379
Packit 534379
    The file :file:`tests/test_pytypes.cpp` contains a complete
Packit 534379
    example that demonstrates passing native Python types in more detail. The
Packit 534379
    file :file:`tests/test_callbacks.cpp` presents a few examples of calling
Packit 534379
    Python functions from C++, including keywords arguments and unpacking.
Packit 534379
Packit 534379
.. _PEP448: https://www.python.org/dev/peps/pep-0448/