blob: 447250ed9e88dbe09cc7d06329e021761103b038 [file] [log] [blame]
Wenzel Jakob28f98aa2015-10-13 02:57:16 +02001.. _basics:
2
3First steps
4###########
5
6This sections demonstrates the basic features of pybind11. Before getting
7started, make sure that development environment is set up to compile the
Dean Moldovanec0d38e2016-08-13 03:09:52 +02008included set of test cases.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +02009
10
11Compiling the test cases
12========================
13
14Linux/MacOS
15-----------
16
17On Linux you'll need to install the **python-dev** or **python3-dev** packages as
18well as **cmake**. On Mac OS, the included python version works out of the box,
19but **cmake** must still be installed.
20
21After installing the prerequisites, run
22
23.. code-block:: bash
24
Dean Moldovanec0d38e2016-08-13 03:09:52 +020025 mkdir build
26 cd build
27 cmake ..
Jason Rhinelander05920e32016-12-19 11:33:02 -050028 make check -j 4
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020029
Dean Moldovanec0d38e2016-08-13 03:09:52 +020030The last line will both compile and run the tests.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020031
32Windows
33-------
34
Dean Moldovanec0d38e2016-08-13 03:09:52 +020035On Windows, only **Visual Studio 2015** and newer are supported since pybind11 relies
36on various C++11 language features that break older versions of Visual Studio.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020037
Dean Moldovanec0d38e2016-08-13 03:09:52 +020038To compile and run the tests:
39
40.. code-block:: batch
41
42 mkdir build
43 cd build
44 cmake ..
Jason Rhinelander05920e32016-12-19 11:33:02 -050045 cmake --build . --config Release --target check
Dean Moldovanec0d38e2016-08-13 03:09:52 +020046
47This will create a Visual Studio project, compile and run the target, all from the
48command line.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020049
50.. Note::
51
Dean Moldovanec0d38e2016-08-13 03:09:52 +020052 If all tests fail, make sure that the Python binary and the testcases are compiled
53 for the same processor type and bitness (i.e. either **i386** or **x86_64**). You
54 can specify **x86_64** as the target architecture for the generated Visual Studio
55 project using ``cmake -A x64 ..``.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020056
57.. seealso::
58
59 Advanced users who are already familiar with Boost.Python may want to skip
Dean Moldovanec0d38e2016-08-13 03:09:52 +020060 the tutorial and look at the test cases in the :file:`tests` directory,
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020061 which exercise all features of pybind11.
62
Dean Moldovan67b52d82016-10-16 19:12:43 +020063Header and namespace conventions
64================================
65
66For brevity, all code examples assume that the following two lines are present:
67
68.. code-block:: cpp
69
70 #include <pybind11/pybind11.h>
71
72 namespace py = pybind11;
73
74Some features may require additional headers, but those will be specified as needed.
75
Ivan Smirnov5cbfda52017-08-30 20:58:43 +010076.. _simple_example:
77
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020078Creating bindings for a simple function
79=======================================
80
81Let's start by creating Python bindings for an extremely simple function, which
82adds two numbers and returns their result:
83
84.. code-block:: cpp
85
86 int add(int i, int j) {
87 return i + j;
88 }
89
90For simplicity [#f1]_, we'll put both this function and the binding code into
91a file named :file:`example.cpp` with the following contents:
92
93.. code-block:: cpp
94
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020095 #include <pybind11/pybind11.h>
Wenzel Jakob93296692015-10-13 23:21:54 +020096
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020097 int add(int i, int j) {
98 return i + j;
99 }
100
Dean Moldovan443ab592017-04-24 01:51:44 +0200101 PYBIND11_MODULE(example, m) {
102 m.doc() = "pybind11 example plugin"; // optional module docstring
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200103
104 m.def("add", &add, "A function which adds two numbers");
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200105 }
106
Dean Moldovan67b52d82016-10-16 19:12:43 +0200107.. [#f1] In practice, implementation and binding code will generally be located
108 in separate files.
109
Dean Moldovan443ab592017-04-24 01:51:44 +0200110The :func:`PYBIND11_MODULE` macro creates a function that will be called when an
111``import`` statement is issued from within Python. The module name (``example``)
Matthew Chan6223b182017-06-08 13:55:30 -0400112is given as the first macro argument (it should not be in quotes). The second
Dean Moldovan443ab592017-04-24 01:51:44 +0200113argument (``m``) defines a variable of type :class:`py::module <module>` which
114is the main interface for creating bindings. The method :func:`module::def`
115generates binding code that exposes the ``add()`` function to Python.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200116
117.. note::
118
119 Notice how little code was needed to expose our function to Python: all
120 details regarding the function's parameters and return value were
121 automatically inferred using template metaprogramming. This overall
122 approach and the used syntax are borrowed from Boost.Python, though the
123 underlying implementation is very different.
124
Ivan Smirnov5cbfda52017-08-30 20:58:43 +0100125pybind11 is a header-only library, hence it is not necessary to link against
126any special libraries and there are no intermediate (magic) translation steps.
127On Linux, the above example can be compiled using the following command:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200128
129.. code-block:: bash
130
Ivan Smirnov5cbfda52017-08-30 20:58:43 +0100131 $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200132
Ivan Smirnov5cbfda52017-08-30 20:58:43 +0100133For more details on the required compiler flags on Linux and MacOS, see
134:ref:`building_manually`. For complete cross-platform compilation instructions,
135refer to the :ref:`compiling` page.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200136
Ivan Smirnov5cbfda52017-08-30 20:58:43 +0100137The `python_example`_ and `cmake_example`_ repositories are also a good place
138to start. They are both complete project examples with cross-platform build
139systems. The only difference between the two is that `python_example`_ uses
140Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake
141(which may be preferable for existing C++ projects).
142
143.. _python_example: https://github.com/pybind/python_example
144.. _cmake_example: https://github.com/pybind/cmake_example
145
146Building the above C++ code will produce a binary module file that can be
147imported to Python. Assuming that the compiled module is located in the
148current directory, the following interactive Python session shows how to
149load and execute the example:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200150
Wenzel Jakob99279f72016-06-03 11:19:29 +0200151.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200152
Wenzel Jakob93296692015-10-13 23:21:54 +0200153 $ python
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200154 Python 2.7.10 (default, Aug 22 2015, 20:33:39)
155 [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
156 Type "help", "copyright", "credits" or "license" for more information.
157 >>> import example
158 >>> example.add(1, 2)
159 3L
Wenzel Jakob93296692015-10-13 23:21:54 +0200160 >>>
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200161
162.. _keyword_args:
163
164Keyword arguments
165=================
166
167With a simple modification code, it is possible to inform Python about the
168names of the arguments ("i" and "j" in this case).
169
170.. code-block:: cpp
171
172 m.def("add", &add, "A function which adds two numbers",
173 py::arg("i"), py::arg("j"));
174
175:class:`arg` is one of several special tag classes which can be used to pass
176metadata into :func:`module::def`. With this modified binding code, we can now
177call the function using keyword arguments, which is a more readable alternative
178particularly for functions taking many parameters:
179
Wenzel Jakob99279f72016-06-03 11:19:29 +0200180.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200181
182 >>> import example
183 >>> example.add(i=1, j=2)
184 3L
185
186The keyword names also appear in the function signatures within the documentation.
187
Wenzel Jakob99279f72016-06-03 11:19:29 +0200188.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200189
190 >>> help(example)
191
192 ....
193
194 FUNCTIONS
195 add(...)
Wenzel Jakob6eb11da2016-01-17 22:36:36 +0100196 Signature : (i: int, j: int) -> int
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200197
198 A function which adds two numbers
199
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200200A shorter notation for named arguments is also available:
201
202.. code-block:: cpp
Wenzel Jakobfe342412016-09-06 13:02:29 +0900203
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200204 // regular notation
205 m.def("add1", &add, py::arg("i"), py::arg("j"));
206 // shorthand
207 using namespace pybind11::literals;
208 m.def("add2", &add, "i"_a, "j"_a);
209
Wenzel Jakobfe342412016-09-06 13:02:29 +0900210The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
211Note that the literal operator must first be made visible with the directive
212``using namespace pybind11::literals``. This does not bring in anything else
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200213from the ``pybind11`` namespace except for literals.
214
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200215.. _default_args:
216
217Default arguments
218=================
219
220Suppose now that the function to be bound has default arguments, e.g.:
221
222.. code-block:: cpp
223
224 int add(int i = 1, int j = 2) {
225 return i + j;
226 }
227
228Unfortunately, pybind11 cannot automatically extract these parameters, since they
229are not part of the function's type information. However, they are simple to specify
230using an extension of :class:`arg`:
231
232.. code-block:: cpp
233
234 m.def("add", &add, "A function which adds two numbers",
235 py::arg("i") = 1, py::arg("j") = 2);
236
237The default values also appear within the documentation.
238
Wenzel Jakob99279f72016-06-03 11:19:29 +0200239.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200240
241 >>> help(example)
242
243 ....
244
245 FUNCTIONS
246 add(...)
Wenzel Jakob6eb11da2016-01-17 22:36:36 +0100247 Signature : (i: int = 1, j: int = 2) -> int
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200248
249 A function which adds two numbers
250
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200251The shorthand notation is also available for default arguments:
252
253.. code-block:: cpp
Wenzel Jakobfe342412016-09-06 13:02:29 +0900254
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200255 // regular notation
256 m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
257 // shorthand
258 m.def("add2", &add, "i"_a=1, "j"_a=2);
259
Dean Moldovan67b52d82016-10-16 19:12:43 +0200260Exporting variables
261===================
262
Jason Rhinelander3f1ff3f2016-12-12 17:42:52 -0500263To expose a value from C++, use the ``attr`` function to register it in a
264module as shown below. Built-in types and general objects (more on that later)
265are automatically converted when assigned as attributes, and can be explicitly
Dean Moldovan67b52d82016-10-16 19:12:43 +0200266converted using the function ``py::cast``.
267
268.. code-block:: cpp
269
Dean Moldovan443ab592017-04-24 01:51:44 +0200270 PYBIND11_MODULE(example, m) {
Jason Rhinelander3f1ff3f2016-12-12 17:42:52 -0500271 m.attr("the_answer") = 42;
272 py::object world = py::cast("World");
273 m.attr("what") = world;
Dean Moldovan67b52d82016-10-16 19:12:43 +0200274 }
275
276These are then accessible from Python:
277
278.. code-block:: pycon
279
280 >>> import example
281 >>> example.the_answer
282 42
283 >>> example.what
284 'World'
285
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200286.. _supported_types:
287
288Supported data types
289====================
290
Dean Moldovan67b52d82016-10-16 19:12:43 +0200291A large number of data types are supported out of the box and can be used
292seamlessly as functions arguments, return values or with ``py::cast`` in general.
293For a full overview, see the :doc:`advanced/cast/index` section.