blob: 33c60049df64e1c0ef84e93a4beed0d5e8717782 [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
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020076Creating bindings for a simple function
77=======================================
78
79Let's start by creating Python bindings for an extremely simple function, which
80adds two numbers and returns their result:
81
82.. code-block:: cpp
83
84 int add(int i, int j) {
85 return i + j;
86 }
87
88For simplicity [#f1]_, we'll put both this function and the binding code into
89a file named :file:`example.cpp` with the following contents:
90
91.. code-block:: cpp
92
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020093 #include <pybind11/pybind11.h>
Wenzel Jakob93296692015-10-13 23:21:54 +020094
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020095 int add(int i, int j) {
96 return i + j;
97 }
98
Wenzel Jakob10e62e12015-10-15 22:46:07 +020099 namespace py = pybind11;
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200100
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200101 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200102 py::module m("example", "pybind11 example plugin");
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200103
104 m.def("add", &add, "A function which adds two numbers");
105
106 return m.ptr();
107 }
108
Dean Moldovan67b52d82016-10-16 19:12:43 +0200109.. [#f1] In practice, implementation and binding code will generally be located
110 in separate files.
111
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200112The :func:`PYBIND11_PLUGIN` macro creates a function that will be called when an
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200113``import`` statement is issued from within Python. The next line creates a
114module named ``example`` (with the supplied docstring). The method
115:func:`module::def` generates binding code that exposes the
116``add()`` function to Python. The last line returns the internal Python object
117associated with ``m`` to the Python interpreter.
118
119.. note::
120
121 Notice how little code was needed to expose our function to Python: all
122 details regarding the function's parameters and return value were
123 automatically inferred using template metaprogramming. This overall
124 approach and the used syntax are borrowed from Boost.Python, though the
125 underlying implementation is very different.
126
127pybind11 is a header-only-library, hence it is not necessary to link against
128any special libraries (other than Python itself). On Windows, use the CMake
129build file discussed in section :ref:`cmake`. On Linux and Mac OS, the above
130example can be compiled using the following command
131
132.. code-block:: bash
133
Wenzel Jakob06f56ee2016-04-28 16:25:24 +0200134 $ c++ -O3 -shared -std=c++11 -I <path-to-pybind11>/include `python-config --cflags --ldflags` example.cpp -o example.so
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200135
136In general, it is advisable to include several additional build parameters
137that can considerably reduce the size of the created binary. Refer to section
138:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
139build system.
140
141Assuming that the created file :file:`example.so` (:file:`example.pyd` on Windows)
142is located in the current directory, the following interactive Python session
143shows how to load and execute the example.
144
Wenzel Jakob99279f72016-06-03 11:19:29 +0200145.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200146
Wenzel Jakob93296692015-10-13 23:21:54 +0200147 $ python
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200148 Python 2.7.10 (default, Aug 22 2015, 20:33:39)
149 [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
150 Type "help", "copyright", "credits" or "license" for more information.
151 >>> import example
152 >>> example.add(1, 2)
153 3L
Wenzel Jakob93296692015-10-13 23:21:54 +0200154 >>>
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200155
156.. _keyword_args:
157
158Keyword arguments
159=================
160
161With a simple modification code, it is possible to inform Python about the
162names of the arguments ("i" and "j" in this case).
163
164.. code-block:: cpp
165
166 m.def("add", &add, "A function which adds two numbers",
167 py::arg("i"), py::arg("j"));
168
169:class:`arg` is one of several special tag classes which can be used to pass
170metadata into :func:`module::def`. With this modified binding code, we can now
171call the function using keyword arguments, which is a more readable alternative
172particularly for functions taking many parameters:
173
Wenzel Jakob99279f72016-06-03 11:19:29 +0200174.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200175
176 >>> import example
177 >>> example.add(i=1, j=2)
178 3L
179
180The keyword names also appear in the function signatures within the documentation.
181
Wenzel Jakob99279f72016-06-03 11:19:29 +0200182.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200183
184 >>> help(example)
185
186 ....
187
188 FUNCTIONS
189 add(...)
Wenzel Jakob6eb11da2016-01-17 22:36:36 +0100190 Signature : (i: int, j: int) -> int
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200191
192 A function which adds two numbers
193
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200194A shorter notation for named arguments is also available:
195
196.. code-block:: cpp
Wenzel Jakobfe342412016-09-06 13:02:29 +0900197
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200198 // regular notation
199 m.def("add1", &add, py::arg("i"), py::arg("j"));
200 // shorthand
201 using namespace pybind11::literals;
202 m.def("add2", &add, "i"_a, "j"_a);
203
Wenzel Jakobfe342412016-09-06 13:02:29 +0900204The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
205Note that the literal operator must first be made visible with the directive
206``using namespace pybind11::literals``. This does not bring in anything else
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200207from the ``pybind11`` namespace except for literals.
208
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200209.. _default_args:
210
211Default arguments
212=================
213
214Suppose now that the function to be bound has default arguments, e.g.:
215
216.. code-block:: cpp
217
218 int add(int i = 1, int j = 2) {
219 return i + j;
220 }
221
222Unfortunately, pybind11 cannot automatically extract these parameters, since they
223are not part of the function's type information. However, they are simple to specify
224using an extension of :class:`arg`:
225
226.. code-block:: cpp
227
228 m.def("add", &add, "A function which adds two numbers",
229 py::arg("i") = 1, py::arg("j") = 2);
230
231The default values also appear within the documentation.
232
Wenzel Jakob99279f72016-06-03 11:19:29 +0200233.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200234
235 >>> help(example)
236
237 ....
238
239 FUNCTIONS
240 add(...)
Wenzel Jakob6eb11da2016-01-17 22:36:36 +0100241 Signature : (i: int = 1, j: int = 2) -> int
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200242
243 A function which adds two numbers
244
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200245The shorthand notation is also available for default arguments:
246
247.. code-block:: cpp
Wenzel Jakobfe342412016-09-06 13:02:29 +0900248
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200249 // regular notation
250 m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
251 // shorthand
252 m.def("add2", &add, "i"_a=1, "j"_a=2);
253
Dean Moldovan67b52d82016-10-16 19:12:43 +0200254Exporting variables
255===================
256
Jason Rhinelander3f1ff3f2016-12-12 17:42:52 -0500257To expose a value from C++, use the ``attr`` function to register it in a
258module as shown below. Built-in types and general objects (more on that later)
259are automatically converted when assigned as attributes, and can be explicitly
Dean Moldovan67b52d82016-10-16 19:12:43 +0200260converted using the function ``py::cast``.
261
262.. code-block:: cpp
263
264 PYBIND11_PLUGIN(example) {
265 py::module m("example", "pybind11 example plugin");
Jason Rhinelander3f1ff3f2016-12-12 17:42:52 -0500266 m.attr("the_answer") = 42;
267 py::object world = py::cast("World");
268 m.attr("what") = world;
Dean Moldovan67b52d82016-10-16 19:12:43 +0200269 return m.ptr();
270 }
271
272These are then accessible from Python:
273
274.. code-block:: pycon
275
276 >>> import example
277 >>> example.the_answer
278 42
279 >>> example.what
280 'World'
281
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200282.. _supported_types:
283
284Supported data types
285====================
286
Dean Moldovan67b52d82016-10-16 19:12:43 +0200287A large number of data types are supported out of the box and can be used
288seamlessly as functions arguments, return values or with ``py::cast`` in general.
289For a full overview, see the :doc:`advanced/cast/index` section.