basics.rst revision 11986:c12e4625ab56
1.. _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
8included set of test cases.
9
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
25   mkdir build
26   cd build
27   cmake ..
28   make pytest -j 4
29
30The last line will both compile and run the tests.
31
32Windows
33-------
34
35On 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.
37
38To compile and run the tests:
39
40.. code-block:: batch
41
42   mkdir build
43   cd build
44   cmake ..
45   cmake --build . --config Release --target pytest
46
47This will create a Visual Studio project, compile and run the target, all from the
48command line.
49
50.. Note::
51
52    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 ..``.
56
57.. seealso::
58
59    Advanced users who are already familiar with Boost.Python may want to skip
60    the tutorial and look at the test cases in the :file:`tests` directory,
61    which exercise all features of pybind11.
62
63Header 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
76Creating 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
93    #include <pybind11/pybind11.h>
94
95    int add(int i, int j) {
96        return i + j;
97    }
98
99    namespace py = pybind11;
100
101    PYBIND11_PLUGIN(example) {
102        py::module m("example", "pybind11 example plugin");
103
104        m.def("add", &add, "A function which adds two numbers");
105
106        return m.ptr();
107    }
108
109.. [#f1] In practice, implementation and binding code will generally be located
110         in separate files.
111
112The :func:`PYBIND11_PLUGIN` macro creates a function that will be called when an
113``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
134    $ c++ -O3 -shared -std=c++11 -I <path-to-pybind11>/include `python-config --cflags --ldflags` example.cpp -o example.so
135
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
145.. code-block:: pycon
146
147    $ python
148    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
154    >>>
155
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
174.. code-block:: pycon
175
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
182.. code-block:: pycon
183
184    >>> help(example)
185
186    ....
187
188    FUNCTIONS
189        add(...)
190            Signature : (i: int, j: int) -> int
191
192            A function which adds two numbers
193
194A shorter notation for named arguments is also available:
195
196.. code-block:: cpp
197
198    // 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
204The :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
207from the ``pybind11`` namespace except for literals.
208
209.. _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
233.. code-block:: pycon
234
235    >>> help(example)
236
237    ....
238
239    FUNCTIONS
240        add(...)
241            Signature : (i: int = 1, j: int = 2) -> int
242
243            A function which adds two numbers
244
245The shorthand notation is also available for default arguments:
246
247.. code-block:: cpp
248
249    // 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
254Exporting variables
255===================
256
257To 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
260converted using the function ``py::cast``.
261
262.. code-block:: cpp
263
264    PYBIND11_PLUGIN(example) {
265        py::module m("example", "pybind11 example plugin");
266        m.attr("the_answer") = 42;
267        py::object world = py::cast("World");
268        m.attr("what") = world;
269        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
282.. _supported_types:
283
284Supported data types
285====================
286
287A 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.
290