blob: 71440c9c66e2f22efd565f8d5bbf528016cb3b08 [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
Henry Schreinerfd61f502020-09-16 17:13:41 -040014Linux/macOS
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020015-----------
16
17On Linux you'll need to install the **python-dev** or **python3-dev** packages as
Henry Schreinerfd61f502020-09-16 17:13:41 -040018well as **cmake**. On macOS, the included python version works out of the box,
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020019but **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
Yannick Jadoul43f390a2020-08-24 20:31:20 +020038.. Note::
39
40 To use the C++17 in Visual Studio 2017 (MSVC 14.1), pybind11 requires the flag
41 ``/permissive-`` to be passed to the compiler `to enforce standard conformance`_. When
42 building with Visual Studio 2019, this is not strictly necessary, but still adviced.
43
44.. _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017
45
Dean Moldovanec0d38e2016-08-13 03:09:52 +020046To compile and run the tests:
47
48.. code-block:: batch
49
50 mkdir build
51 cd build
52 cmake ..
Jason Rhinelander05920e32016-12-19 11:33:02 -050053 cmake --build . --config Release --target check
Dean Moldovanec0d38e2016-08-13 03:09:52 +020054
55This will create a Visual Studio project, compile and run the target, all from the
56command line.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020057
58.. Note::
59
Dean Moldovanec0d38e2016-08-13 03:09:52 +020060 If all tests fail, make sure that the Python binary and the testcases are compiled
61 for the same processor type and bitness (i.e. either **i386** or **x86_64**). You
62 can specify **x86_64** as the target architecture for the generated Visual Studio
63 project using ``cmake -A x64 ..``.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020064
65.. seealso::
66
67 Advanced users who are already familiar with Boost.Python may want to skip
Dean Moldovanec0d38e2016-08-13 03:09:52 +020068 the tutorial and look at the test cases in the :file:`tests` directory,
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020069 which exercise all features of pybind11.
70
Dean Moldovan67b52d82016-10-16 19:12:43 +020071Header and namespace conventions
72================================
73
74For brevity, all code examples assume that the following two lines are present:
75
76.. code-block:: cpp
77
78 #include <pybind11/pybind11.h>
79
80 namespace py = pybind11;
81
82Some features may require additional headers, but those will be specified as needed.
83
Ivan Smirnov5cbfda52017-08-30 20:58:43 +010084.. _simple_example:
85
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020086Creating bindings for a simple function
87=======================================
88
89Let's start by creating Python bindings for an extremely simple function, which
90adds two numbers and returns their result:
91
92.. code-block:: cpp
93
94 int add(int i, int j) {
95 return i + j;
96 }
97
98For simplicity [#f1]_, we'll put both this function and the binding code into
99a file named :file:`example.cpp` with the following contents:
100
101.. code-block:: cpp
102
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200103 #include <pybind11/pybind11.h>
Wenzel Jakob93296692015-10-13 23:21:54 +0200104
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200105 int add(int i, int j) {
106 return i + j;
107 }
108
Dean Moldovan443ab592017-04-24 01:51:44 +0200109 PYBIND11_MODULE(example, m) {
110 m.doc() = "pybind11 example plugin"; // optional module docstring
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200111
112 m.def("add", &add, "A function which adds two numbers");
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200113 }
114
Dean Moldovan67b52d82016-10-16 19:12:43 +0200115.. [#f1] In practice, implementation and binding code will generally be located
116 in separate files.
117
Dean Moldovan443ab592017-04-24 01:51:44 +0200118The :func:`PYBIND11_MODULE` macro creates a function that will be called when an
119``import`` statement is issued from within Python. The module name (``example``)
Matthew Chan6223b182017-06-08 13:55:30 -0400120is given as the first macro argument (it should not be in quotes). The second
Dean Moldovan443ab592017-04-24 01:51:44 +0200121argument (``m``) defines a variable of type :class:`py::module <module>` which
122is the main interface for creating bindings. The method :func:`module::def`
123generates binding code that exposes the ``add()`` function to Python.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200124
125.. note::
126
127 Notice how little code was needed to expose our function to Python: all
128 details regarding the function's parameters and return value were
129 automatically inferred using template metaprogramming. This overall
130 approach and the used syntax are borrowed from Boost.Python, though the
131 underlying implementation is very different.
132
Ivan Smirnov5cbfda52017-08-30 20:58:43 +0100133pybind11 is a header-only library, hence it is not necessary to link against
134any special libraries and there are no intermediate (magic) translation steps.
135On Linux, the above example can be compiled using the following command:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200136
137.. code-block:: bash
138
Ivan Smirnov5cbfda52017-08-30 20:58:43 +0100139 $ 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 +0200140
Henry Schreinerfd61f502020-09-16 17:13:41 -0400141For more details on the required compiler flags on Linux and macOS, see
Ivan Smirnov5cbfda52017-08-30 20:58:43 +0100142:ref:`building_manually`. For complete cross-platform compilation instructions,
143refer to the :ref:`compiling` page.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200144
Ivan Smirnov5cbfda52017-08-30 20:58:43 +0100145The `python_example`_ and `cmake_example`_ repositories are also a good place
146to start. They are both complete project examples with cross-platform build
147systems. The only difference between the two is that `python_example`_ uses
148Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake
149(which may be preferable for existing C++ projects).
150
151.. _python_example: https://github.com/pybind/python_example
152.. _cmake_example: https://github.com/pybind/cmake_example
153
154Building the above C++ code will produce a binary module file that can be
155imported to Python. Assuming that the compiled module is located in the
156current directory, the following interactive Python session shows how to
157load and execute the example:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200158
Wenzel Jakob99279f72016-06-03 11:19:29 +0200159.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200160
Wenzel Jakob93296692015-10-13 23:21:54 +0200161 $ python
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200162 Python 2.7.10 (default, Aug 22 2015, 20:33:39)
163 [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
164 Type "help", "copyright", "credits" or "license" for more information.
165 >>> import example
166 >>> example.add(1, 2)
167 3L
Wenzel Jakob93296692015-10-13 23:21:54 +0200168 >>>
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200169
170.. _keyword_args:
171
172Keyword arguments
173=================
174
Erick Matsenb32b7622019-11-13 23:53:30 -0800175With a simple code modification, it is possible to inform Python about the
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200176names of the arguments ("i" and "j" in this case).
177
178.. code-block:: cpp
179
180 m.def("add", &add, "A function which adds two numbers",
181 py::arg("i"), py::arg("j"));
182
183:class:`arg` is one of several special tag classes which can be used to pass
184metadata into :func:`module::def`. With this modified binding code, we can now
185call the function using keyword arguments, which is a more readable alternative
186particularly for functions taking many parameters:
187
Wenzel Jakob99279f72016-06-03 11:19:29 +0200188.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200189
190 >>> import example
191 >>> example.add(i=1, j=2)
192 3L
193
194The keyword names also appear in the function signatures within the documentation.
195
Wenzel Jakob99279f72016-06-03 11:19:29 +0200196.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200197
198 >>> help(example)
199
200 ....
201
202 FUNCTIONS
203 add(...)
Wenzel Jakob6eb11da2016-01-17 22:36:36 +0100204 Signature : (i: int, j: int) -> int
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200205
206 A function which adds two numbers
207
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200208A shorter notation for named arguments is also available:
209
210.. code-block:: cpp
Wenzel Jakobfe342412016-09-06 13:02:29 +0900211
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200212 // regular notation
213 m.def("add1", &add, py::arg("i"), py::arg("j"));
214 // shorthand
215 using namespace pybind11::literals;
216 m.def("add2", &add, "i"_a, "j"_a);
217
Wenzel Jakobfe342412016-09-06 13:02:29 +0900218The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
219Note that the literal operator must first be made visible with the directive
220``using namespace pybind11::literals``. This does not bring in anything else
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200221from the ``pybind11`` namespace except for literals.
222
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200223.. _default_args:
224
225Default arguments
226=================
227
228Suppose now that the function to be bound has default arguments, e.g.:
229
230.. code-block:: cpp
231
232 int add(int i = 1, int j = 2) {
233 return i + j;
234 }
235
236Unfortunately, pybind11 cannot automatically extract these parameters, since they
237are not part of the function's type information. However, they are simple to specify
238using an extension of :class:`arg`:
239
240.. code-block:: cpp
241
242 m.def("add", &add, "A function which adds two numbers",
243 py::arg("i") = 1, py::arg("j") = 2);
244
245The default values also appear within the documentation.
246
Wenzel Jakob99279f72016-06-03 11:19:29 +0200247.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200248
249 >>> help(example)
250
251 ....
252
253 FUNCTIONS
254 add(...)
Wenzel Jakob6eb11da2016-01-17 22:36:36 +0100255 Signature : (i: int = 1, j: int = 2) -> int
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200256
257 A function which adds two numbers
258
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200259The shorthand notation is also available for default arguments:
260
261.. code-block:: cpp
Wenzel Jakobfe342412016-09-06 13:02:29 +0900262
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200263 // regular notation
264 m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
265 // shorthand
266 m.def("add2", &add, "i"_a=1, "j"_a=2);
267
Dean Moldovan67b52d82016-10-16 19:12:43 +0200268Exporting variables
269===================
270
Jason Rhinelander3f1ff3f2016-12-12 17:42:52 -0500271To expose a value from C++, use the ``attr`` function to register it in a
272module as shown below. Built-in types and general objects (more on that later)
273are automatically converted when assigned as attributes, and can be explicitly
Dean Moldovan67b52d82016-10-16 19:12:43 +0200274converted using the function ``py::cast``.
275
276.. code-block:: cpp
277
Dean Moldovan443ab592017-04-24 01:51:44 +0200278 PYBIND11_MODULE(example, m) {
Jason Rhinelander3f1ff3f2016-12-12 17:42:52 -0500279 m.attr("the_answer") = 42;
280 py::object world = py::cast("World");
281 m.attr("what") = world;
Dean Moldovan67b52d82016-10-16 19:12:43 +0200282 }
283
284These are then accessible from Python:
285
286.. code-block:: pycon
287
288 >>> import example
289 >>> example.the_answer
290 42
291 >>> example.what
292 'World'
293
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200294.. _supported_types:
295
296Supported data types
297====================
298
Dean Moldovan67b52d82016-10-16 19:12:43 +0200299A large number of data types are supported out of the box and can be used
300seamlessly as functions arguments, return values or with ``py::cast`` in general.
301For a full overview, see the :doc:`advanced/cast/index` section.