blob: 2ae8c0c2549dde1943894a71f191ffe16f1c3c8e [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
Dean Moldovan443ab592017-04-24 01:51:44 +020099 PYBIND11_MODULE(example, m) {
100 m.doc() = "pybind11 example plugin"; // optional module docstring
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200101
102 m.def("add", &add, "A function which adds two numbers");
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200103 }
104
Dean Moldovan67b52d82016-10-16 19:12:43 +0200105.. [#f1] In practice, implementation and binding code will generally be located
106 in separate files.
107
Dean Moldovan443ab592017-04-24 01:51:44 +0200108The :func:`PYBIND11_MODULE` macro creates a function that will be called when an
109``import`` statement is issued from within Python. The module name (``example``)
Matthew Chan6223b182017-06-08 13:55:30 -0400110is given as the first macro argument (it should not be in quotes). The second
Dean Moldovan443ab592017-04-24 01:51:44 +0200111argument (``m``) defines a variable of type :class:`py::module <module>` which
112is the main interface for creating bindings. The method :func:`module::def`
113generates binding code that exposes the ``add()`` function to Python.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200114
115.. note::
116
117 Notice how little code was needed to expose our function to Python: all
118 details regarding the function's parameters and return value were
119 automatically inferred using template metaprogramming. This overall
120 approach and the used syntax are borrowed from Boost.Python, though the
121 underlying implementation is very different.
122
123pybind11 is a header-only-library, hence it is not necessary to link against
124any special libraries (other than Python itself). On Windows, use the CMake
125build file discussed in section :ref:`cmake`. On Linux and Mac OS, the above
126example can be compiled using the following command
127
128.. code-block:: bash
129
Wenzel Jakob06f56ee2016-04-28 16:25:24 +0200130 $ 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 +0200131
132In general, it is advisable to include several additional build parameters
133that can considerably reduce the size of the created binary. Refer to section
134:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
135build system.
136
137Assuming that the created file :file:`example.so` (:file:`example.pyd` on Windows)
138is located in the current directory, the following interactive Python session
139shows how to load and execute the example.
140
Wenzel Jakob99279f72016-06-03 11:19:29 +0200141.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200142
Wenzel Jakob93296692015-10-13 23:21:54 +0200143 $ python
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200144 Python 2.7.10 (default, Aug 22 2015, 20:33:39)
145 [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
146 Type "help", "copyright", "credits" or "license" for more information.
147 >>> import example
148 >>> example.add(1, 2)
149 3L
Wenzel Jakob93296692015-10-13 23:21:54 +0200150 >>>
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200151
152.. _keyword_args:
153
154Keyword arguments
155=================
156
157With a simple modification code, it is possible to inform Python about the
158names of the arguments ("i" and "j" in this case).
159
160.. code-block:: cpp
161
162 m.def("add", &add, "A function which adds two numbers",
163 py::arg("i"), py::arg("j"));
164
165:class:`arg` is one of several special tag classes which can be used to pass
166metadata into :func:`module::def`. With this modified binding code, we can now
167call the function using keyword arguments, which is a more readable alternative
168particularly for functions taking many parameters:
169
Wenzel Jakob99279f72016-06-03 11:19:29 +0200170.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200171
172 >>> import example
173 >>> example.add(i=1, j=2)
174 3L
175
176The keyword names also appear in the function signatures within the documentation.
177
Wenzel Jakob99279f72016-06-03 11:19:29 +0200178.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200179
180 >>> help(example)
181
182 ....
183
184 FUNCTIONS
185 add(...)
Wenzel Jakob6eb11da2016-01-17 22:36:36 +0100186 Signature : (i: int, j: int) -> int
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200187
188 A function which adds two numbers
189
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200190A shorter notation for named arguments is also available:
191
192.. code-block:: cpp
Wenzel Jakobfe342412016-09-06 13:02:29 +0900193
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200194 // regular notation
195 m.def("add1", &add, py::arg("i"), py::arg("j"));
196 // shorthand
197 using namespace pybind11::literals;
198 m.def("add2", &add, "i"_a, "j"_a);
199
Wenzel Jakobfe342412016-09-06 13:02:29 +0900200The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
201Note that the literal operator must first be made visible with the directive
202``using namespace pybind11::literals``. This does not bring in anything else
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200203from the ``pybind11`` namespace except for literals.
204
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200205.. _default_args:
206
207Default arguments
208=================
209
210Suppose now that the function to be bound has default arguments, e.g.:
211
212.. code-block:: cpp
213
214 int add(int i = 1, int j = 2) {
215 return i + j;
216 }
217
218Unfortunately, pybind11 cannot automatically extract these parameters, since they
219are not part of the function's type information. However, they are simple to specify
220using an extension of :class:`arg`:
221
222.. code-block:: cpp
223
224 m.def("add", &add, "A function which adds two numbers",
225 py::arg("i") = 1, py::arg("j") = 2);
226
227The default values also appear within the documentation.
228
Wenzel Jakob99279f72016-06-03 11:19:29 +0200229.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200230
231 >>> help(example)
232
233 ....
234
235 FUNCTIONS
236 add(...)
Wenzel Jakob6eb11da2016-01-17 22:36:36 +0100237 Signature : (i: int = 1, j: int = 2) -> int
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200238
239 A function which adds two numbers
240
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200241The shorthand notation is also available for default arguments:
242
243.. code-block:: cpp
Wenzel Jakobfe342412016-09-06 13:02:29 +0900244
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200245 // regular notation
246 m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
247 // shorthand
248 m.def("add2", &add, "i"_a=1, "j"_a=2);
249
Dean Moldovan67b52d82016-10-16 19:12:43 +0200250Exporting variables
251===================
252
Jason Rhinelander3f1ff3f2016-12-12 17:42:52 -0500253To expose a value from C++, use the ``attr`` function to register it in a
254module as shown below. Built-in types and general objects (more on that later)
255are automatically converted when assigned as attributes, and can be explicitly
Dean Moldovan67b52d82016-10-16 19:12:43 +0200256converted using the function ``py::cast``.
257
258.. code-block:: cpp
259
Dean Moldovan443ab592017-04-24 01:51:44 +0200260 PYBIND11_MODULE(example, m) {
Jason Rhinelander3f1ff3f2016-12-12 17:42:52 -0500261 m.attr("the_answer") = 42;
262 py::object world = py::cast("World");
263 m.attr("what") = world;
Dean Moldovan67b52d82016-10-16 19:12:43 +0200264 }
265
266These are then accessible from Python:
267
268.. code-block:: pycon
269
270 >>> import example
271 >>> example.the_answer
272 42
273 >>> example.what
274 'World'
275
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200276.. _supported_types:
277
278Supported data types
279====================
280
Dean Moldovan67b52d82016-10-16 19:12:43 +0200281A large number of data types are supported out of the box and can be used
282seamlessly as functions arguments, return values or with ``py::cast`` in general.
283For a full overview, see the :doc:`advanced/cast/index` section.