Blame external/pybind11/docs/basics.rst

Packit 534379
.. _basics:
Packit 534379
Packit 534379
First steps
Packit 534379
###########
Packit 534379
Packit 534379
This sections demonstrates the basic features of pybind11. Before getting
Packit 534379
started, make sure that development environment is set up to compile the
Packit 534379
included set of test cases.
Packit 534379
Packit 534379
Packit 534379
Compiling the test cases
Packit 534379
========================
Packit 534379
Packit 534379
Linux/MacOS
Packit 534379
-----------
Packit 534379
Packit 534379
On Linux  you'll need to install the **python-dev** or **python3-dev** packages as
Packit 534379
well as **cmake**. On Mac OS, the included python version works out of the box,
Packit 534379
but **cmake** must still be installed.
Packit 534379
Packit 534379
After installing the prerequisites, run
Packit 534379
Packit 534379
.. code-block:: bash
Packit 534379
Packit 534379
   mkdir build
Packit 534379
   cd build
Packit 534379
   cmake ..
Packit 534379
   make check -j 4
Packit 534379
Packit 534379
The last line will both compile and run the tests.
Packit 534379
Packit 534379
Windows
Packit 534379
-------
Packit 534379
Packit 534379
On Windows, only **Visual Studio 2015** and newer are supported since pybind11 relies
Packit 534379
on various C++11 language features that break older versions of Visual Studio.
Packit 534379
Packit 534379
To compile and run the tests:
Packit 534379
Packit 534379
.. code-block:: batch
Packit 534379
Packit 534379
   mkdir build
Packit 534379
   cd build
Packit 534379
   cmake ..
Packit 534379
   cmake --build . --config Release --target check
Packit 534379
Packit 534379
This will create a Visual Studio project, compile and run the target, all from the
Packit 534379
command line.
Packit 534379
Packit 534379
.. Note::
Packit 534379
Packit 534379
    If all tests fail, make sure that the Python binary and the testcases are compiled
Packit 534379
    for the same processor type and bitness (i.e. either **i386** or **x86_64**). You
Packit 534379
    can specify **x86_64** as the target architecture for the generated Visual Studio
Packit 534379
    project using ``cmake -A x64 ..``.
Packit 534379
Packit 534379
.. seealso::
Packit 534379
Packit 534379
    Advanced users who are already familiar with Boost.Python may want to skip
Packit 534379
    the tutorial and look at the test cases in the :file:`tests` directory,
Packit 534379
    which exercise all features of pybind11.
Packit 534379
Packit 534379
Header and namespace conventions
Packit 534379
================================
Packit 534379
Packit 534379
For brevity, all code examples assume that the following two lines are present:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    #include <pybind11/pybind11.h>
Packit 534379
Packit 534379
    namespace py = pybind11;
Packit 534379
Packit 534379
Some features may require additional headers, but those will be specified as needed.
Packit 534379
Packit 534379
.. _simple_example:
Packit 534379
Packit 534379
Creating bindings for a simple function
Packit 534379
=======================================
Packit 534379
Packit 534379
Let's start by creating Python bindings for an extremely simple function, which
Packit 534379
adds two numbers and returns their result:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    int add(int i, int j) {
Packit 534379
        return i + j;
Packit 534379
    }
Packit 534379
Packit 534379
For simplicity [#f1]_, we'll put both this function and the binding code into
Packit 534379
a file named :file:`example.cpp` with the following contents:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    #include <pybind11/pybind11.h>
Packit 534379
Packit 534379
    int add(int i, int j) {
Packit 534379
        return i + j;
Packit 534379
    }
Packit 534379
Packit 534379
    PYBIND11_MODULE(example, m) {
Packit 534379
        m.doc() = "pybind11 example plugin"; // optional module docstring
Packit 534379
Packit 534379
        m.def("add", &add, "A function which adds two numbers");
Packit 534379
    }
Packit 534379
Packit 534379
.. [#f1] In practice, implementation and binding code will generally be located
Packit 534379
         in separate files.
Packit 534379
Packit 534379
The :func:`PYBIND11_MODULE` macro creates a function that will be called when an
Packit 534379
``import`` statement is issued from within Python. The module name (``example``)
Packit 534379
is given as the first macro argument (it should not be in quotes). The second
Packit 534379
argument (``m``) defines a variable of type :class:`py::module <module>` which
Packit 534379
is the main interface for creating bindings. The method :func:`module::def`
Packit 534379
generates binding code that exposes the ``add()`` function to Python.
Packit 534379
Packit 534379
.. note::
Packit 534379
Packit 534379
    Notice how little code was needed to expose our function to Python: all
Packit 534379
    details regarding the function's parameters and return value were
Packit 534379
    automatically inferred using template metaprogramming. This overall
Packit 534379
    approach and the used syntax are borrowed from Boost.Python, though the
Packit 534379
    underlying implementation is very different.
Packit 534379
Packit 534379
pybind11 is a header-only library, hence it is not necessary to link against
Packit 534379
any special libraries and there are no intermediate (magic) translation steps.
Packit 534379
On Linux, the above example can be compiled using the following command:
Packit 534379
Packit 534379
.. code-block:: bash
Packit 534379
Packit 534379
    $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
Packit 534379
Packit 534379
For more details on the required compiler flags on Linux and MacOS, see
Packit 534379
:ref:`building_manually`. For complete cross-platform compilation instructions,
Packit 534379
refer to the :ref:`compiling` page.
Packit 534379
Packit 534379
The `python_example`_ and `cmake_example`_ repositories are also a good place
Packit 534379
to start. They are both complete project examples with cross-platform build
Packit 534379
systems. The only difference between the two is that `python_example`_ uses
Packit 534379
Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake
Packit 534379
(which may be preferable for existing C++ projects).
Packit 534379
Packit 534379
.. _python_example: https://github.com/pybind/python_example
Packit 534379
.. _cmake_example: https://github.com/pybind/cmake_example
Packit 534379
Packit 534379
Building the above C++ code will produce a binary module file that can be
Packit 534379
imported to Python. Assuming that the compiled module is located in the
Packit 534379
current directory, the following interactive Python session shows how to
Packit 534379
load and execute the example:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    $ python
Packit 534379
    Python 2.7.10 (default, Aug 22 2015, 20:33:39)
Packit 534379
    [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
Packit 534379
    Type "help", "copyright", "credits" or "license" for more information.
Packit 534379
    >>> import example
Packit 534379
    >>> example.add(1, 2)
Packit 534379
    3L
Packit 534379
    >>>
Packit 534379
Packit 534379
.. _keyword_args:
Packit 534379
Packit 534379
Keyword arguments
Packit 534379
=================
Packit 534379
Packit 534379
With a simple modification code, it is possible to inform Python about the
Packit 534379
names of the arguments ("i" and "j" in this case).
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    m.def("add", &add, "A function which adds two numbers",
Packit 534379
          py::arg("i"), py::arg("j"));
Packit 534379
Packit 534379
:class:`arg` is one of several special tag classes which can be used to pass
Packit 534379
metadata into :func:`module::def`. With this modified binding code, we can now
Packit 534379
call the function using keyword arguments, which is a more readable alternative
Packit 534379
particularly for functions taking many parameters:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> import example
Packit 534379
    >>> example.add(i=1, j=2)
Packit 534379
    3L
Packit 534379
Packit 534379
The keyword names also appear in the function signatures within the documentation.
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> help(example)
Packit 534379
Packit 534379
    ....
Packit 534379
Packit 534379
    FUNCTIONS
Packit 534379
        add(...)
Packit 534379
            Signature : (i: int, j: int) -> int
Packit 534379
Packit 534379
            A function which adds two numbers
Packit 534379
Packit 534379
A shorter notation for named arguments is also available:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    // regular notation
Packit 534379
    m.def("add1", &add, py::arg("i"), py::arg("j"));
Packit 534379
    // shorthand
Packit 534379
    using namespace pybind11::literals;
Packit 534379
    m.def("add2", &add, "i"_a, "j"_a);
Packit 534379
Packit 534379
The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
Packit 534379
Note that the literal operator must first be made visible with the directive
Packit 534379
``using namespace pybind11::literals``. This does not bring in anything else
Packit 534379
from the ``pybind11`` namespace except for literals.
Packit 534379
Packit 534379
.. _default_args:
Packit 534379
Packit 534379
Default arguments
Packit 534379
=================
Packit 534379
Packit 534379
Suppose now that the function to be bound has default arguments, e.g.:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    int add(int i = 1, int j = 2) {
Packit 534379
        return i + j;
Packit 534379
    }
Packit 534379
Packit 534379
Unfortunately, pybind11 cannot automatically extract these parameters, since they
Packit 534379
are not part of the function's type information. However, they are simple to specify
Packit 534379
using an extension of :class:`arg`:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    m.def("add", &add, "A function which adds two numbers",
Packit 534379
          py::arg("i") = 1, py::arg("j") = 2);
Packit 534379
Packit 534379
The default values also appear within the documentation.
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> help(example)
Packit 534379
Packit 534379
    ....
Packit 534379
Packit 534379
    FUNCTIONS
Packit 534379
        add(...)
Packit 534379
            Signature : (i: int = 1, j: int = 2) -> int
Packit 534379
Packit 534379
            A function which adds two numbers
Packit 534379
Packit 534379
The shorthand notation is also available for default arguments:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    // regular notation
Packit 534379
    m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
Packit 534379
    // shorthand
Packit 534379
    m.def("add2", &add, "i"_a=1, "j"_a=2);
Packit 534379
Packit 534379
Exporting variables
Packit 534379
===================
Packit 534379
Packit 534379
To expose a value from C++, use the ``attr`` function to register it in a
Packit 534379
module as shown below. Built-in types and general objects (more on that later)
Packit 534379
are automatically converted when assigned as attributes, and can be explicitly
Packit 534379
converted using the function ``py::cast``.
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    PYBIND11_MODULE(example, m) {
Packit 534379
        m.attr("the_answer") = 42;
Packit 534379
        py::object world = py::cast("World");
Packit 534379
        m.attr("what") = world;
Packit 534379
    }
Packit 534379
Packit 534379
These are then accessible from Python:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> import example
Packit 534379
    >>> example.the_answer
Packit 534379
    42
Packit 534379
    >>> example.what
Packit 534379
    'World'
Packit 534379
Packit 534379
.. _supported_types:
Packit 534379
Packit 534379
Supported data types
Packit 534379
====================
Packit 534379
Packit 534379
A large number of data types are supported out of the box and can be used
Packit 534379
seamlessly as functions arguments, return values or with ``py::cast`` in general.
Packit 534379
For a full overview, see the :doc:`advanced/cast/index` section.