basics.rst 8.87 KB
Newer Older
1
2
3
4
5
6
7
.. _basics:

First steps
###########

This sections demonstrates the basic features of pybind11. Before getting
started, make sure that development environment is set up to compile the
8
included set of test cases.
9
10
11
12
13


Compiling the test cases
========================

14
Linux/macOS
15
16
17
-----------

On Linux  you'll need to install the **python-dev** or **python3-dev** packages as
18
well as **cmake**. On macOS, the included python version works out of the box,
19
20
21
22
23
24
but **cmake** must still be installed.

After installing the prerequisites, run

.. code-block:: bash

25
26
27
   mkdir build
   cd build
   cmake ..
28
   make check -j 4
29

30
The last line will both compile and run the tests.
31
32
33
34

Windows
-------

35
36
On Windows, only **Visual Studio 2015** and newer are supported since pybind11 relies
on various C++11 language features that break older versions of Visual Studio.
37

38
39
40
41
42
43
44
45
.. Note::

    To use the C++17 in Visual Studio 2017 (MSVC 14.1), pybind11 requires the flag
    ``/permissive-`` to be passed to the compiler `to enforce standard conformance`_. When
    building with Visual Studio 2019, this is not strictly necessary, but still adviced.

..  _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017

46
To compile and run the tests:
47

48
49
50
51
52
.. code-block:: batch

   mkdir build
   cd build
   cmake ..
53
   cmake --build . --config Release --target check
54

55
56
This will create a Visual Studio project, compile and run the target, all from the
command line.
57

58
.. Note::
59

60
61
62
63
    If all tests fail, make sure that the Python binary and the testcases are compiled
    for the same processor type and bitness (i.e. either **i386** or **x86_64**). You
    can specify **x86_64** as the target architecture for the generated Visual Studio
    project using ``cmake -A x64 ..``.
64
65
66
67

.. seealso::

    Advanced users who are already familiar with Boost.Python may want to skip
68
    the tutorial and look at the test cases in the :file:`tests` directory,
69
70
    which exercise all features of pybind11.

Dean Moldovan's avatar
Dean Moldovan committed
71
72
73
74
75
76
77
78
79
80
81
82
83
Header and namespace conventions
================================

For brevity, all code examples assume that the following two lines are present:

.. code-block:: cpp

    #include <pybind11/pybind11.h>

    namespace py = pybind11;

Some features may require additional headers, but those will be specified as needed.

84
85
.. _simple_example:

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
Creating bindings for a simple function
=======================================

Let's start by creating Python bindings for an extremely simple function, which
adds two numbers and returns their result:

.. code-block:: cpp

    int add(int i, int j) {
        return i + j;
    }

For simplicity [#f1]_, we'll put both this function and the binding code into
a file named :file:`example.cpp` with the following contents:

.. code-block:: cpp

103
    #include <pybind11/pybind11.h>
Wenzel Jakob's avatar
Wenzel Jakob committed
104

105
106
107
108
    int add(int i, int j) {
        return i + j;
    }

109
110
    PYBIND11_MODULE(example, m) {
        m.doc() = "pybind11 example plugin"; // optional module docstring
111
112
113
114

        m.def("add", &add, "A function which adds two numbers");
    }

Dean Moldovan's avatar
Dean Moldovan committed
115
116
117
.. [#f1] In practice, implementation and binding code will generally be located
         in separate files.

118
119
The :func:`PYBIND11_MODULE` macro creates a function that will be called when an
``import`` statement is issued from within Python. The module name (``example``)
Matthew Chan's avatar
Matthew Chan committed
120
is given as the first macro argument (it should not be in quotes). The second
121
122
argument (``m``) defines a variable of type :class:`py::module_ <module>` which
is the main interface for creating bindings. The method :func:`module_::def`
123
generates binding code that exposes the ``add()`` function to Python.
124
125
126
127
128
129
130
131
132

.. note::

    Notice how little code was needed to expose our function to Python: all
    details regarding the function's parameters and return value were
    automatically inferred using template metaprogramming. This overall
    approach and the used syntax are borrowed from Boost.Python, though the
    underlying implementation is very different.

133
134
135
pybind11 is a header-only library, hence it is not necessary to link against
any special libraries and there are no intermediate (magic) translation steps.
On Linux, the above example can be compiled using the following command:
136
137
138

.. code-block:: bash

139
140
    $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`

141
For more details on the required compiler flags on Linux and macOS, see
142
143
144
145
146
147
148
149
:ref:`building_manually`. For complete cross-platform compilation instructions,
refer to the :ref:`compiling` page.

The `python_example`_ and `cmake_example`_ repositories are also a good place
to start. They are both complete project examples with cross-platform build
systems. The only difference between the two is that `python_example`_ uses
Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake
(which may be preferable for existing C++ projects).
150

151
152
.. _python_example: https://github.com/pybind/python_example
.. _cmake_example: https://github.com/pybind/cmake_example
153

154
155
156
157
Building the above C++ code will produce a binary module file that can be
imported to Python. Assuming that the compiled module is located in the
current directory, the following interactive Python session shows how to
load and execute the example:
158

159
.. code-block:: pycon
160

Wenzel Jakob's avatar
Wenzel Jakob committed
161
    $ python
162
163
164
165
166
167
    Python 2.7.10 (default, Aug 22 2015, 20:33:39)
    [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import example
    >>> example.add(1, 2)
    3L
Wenzel Jakob's avatar
Wenzel Jakob committed
168
    >>>
169
170
171
172
173
174

.. _keyword_args:

Keyword arguments
=================

175
With a simple code modification, it is possible to inform Python about the
176
177
178
179
180
181
182
183
names of the arguments ("i" and "j" in this case).

.. code-block:: cpp

    m.def("add", &add, "A function which adds two numbers",
          py::arg("i"), py::arg("j"));

:class:`arg` is one of several special tag classes which can be used to pass
184
metadata into :func:`module_::def`. With this modified binding code, we can now
185
186
187
call the function using keyword arguments, which is a more readable alternative
particularly for functions taking many parameters:

188
.. code-block:: pycon
189
190
191
192
193
194
195

    >>> import example
    >>> example.add(i=1, j=2)
    3L

The keyword names also appear in the function signatures within the documentation.

196
.. code-block:: pycon
197
198
199
200
201
202
203

    >>> help(example)

    ....

    FUNCTIONS
        add(...)
204
            Signature : (i: int, j: int) -> int
205
206
207

            A function which adds two numbers

208
209
210
A shorter notation for named arguments is also available:

.. code-block:: cpp
Wenzel Jakob's avatar
Wenzel Jakob committed
211

212
213
214
215
216
217
    // regular notation
    m.def("add1", &add, py::arg("i"), py::arg("j"));
    // shorthand
    using namespace pybind11::literals;
    m.def("add2", &add, "i"_a, "j"_a);

Wenzel Jakob's avatar
Wenzel Jakob committed
218
219
220
The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
Note that the literal operator must first be made visible with the directive
``using namespace pybind11::literals``. This does not bring in anything else
221
222
from the ``pybind11`` namespace except for literals.

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
.. _default_args:

Default arguments
=================

Suppose now that the function to be bound has default arguments, e.g.:

.. code-block:: cpp

    int add(int i = 1, int j = 2) {
        return i + j;
    }

Unfortunately, pybind11 cannot automatically extract these parameters, since they
are not part of the function's type information. However, they are simple to specify
using an extension of :class:`arg`:

.. code-block:: cpp

    m.def("add", &add, "A function which adds two numbers",
          py::arg("i") = 1, py::arg("j") = 2);

The default values also appear within the documentation.

247
.. code-block:: pycon
248
249
250
251
252
253
254

    >>> help(example)

    ....

    FUNCTIONS
        add(...)
255
            Signature : (i: int = 1, j: int = 2) -> int
256
257
258

            A function which adds two numbers

259
260
261
The shorthand notation is also available for default arguments:

.. code-block:: cpp
Wenzel Jakob's avatar
Wenzel Jakob committed
262

263
264
265
266
267
    // regular notation
    m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
    // shorthand
    m.def("add2", &add, "i"_a=1, "j"_a=2);

Dean Moldovan's avatar
Dean Moldovan committed
268
269
270
Exporting variables
===================

271
272
273
To expose a value from C++, use the ``attr`` function to register it in a
module as shown below. Built-in types and general objects (more on that later)
are automatically converted when assigned as attributes, and can be explicitly
Dean Moldovan's avatar
Dean Moldovan committed
274
275
276
277
converted using the function ``py::cast``.

.. code-block:: cpp

278
    PYBIND11_MODULE(example, m) {
279
280
281
        m.attr("the_answer") = 42;
        py::object world = py::cast("World");
        m.attr("what") = world;
Dean Moldovan's avatar
Dean Moldovan committed
282
283
284
285
286
287
288
289
290
291
292
293
    }

These are then accessible from Python:

.. code-block:: pycon

    >>> import example
    >>> example.the_answer
    42
    >>> example.what
    'World'

294
295
296
297
298
.. _supported_types:

Supported data types
====================

Dean Moldovan's avatar
Dean Moldovan committed
299
300
301
A large number of data types are supported out of the box and can be used
seamlessly as functions arguments, return values or with ``py::cast`` in general.
For a full overview, see the :doc:`advanced/cast/index` section.