basics.rst revision 12391:ceeca8b41e4b
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 check -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 check
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
76.. _simple_example:
77
78Creating 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
95    #include <pybind11/pybind11.h>
96
97    int add(int i, int j) {
98        return i + j;
99    }
100
101    PYBIND11_MODULE(example, m) {
102        m.doc() = "pybind11 example plugin"; // optional module docstring
103
104        m.def("add", &add, "A function which adds two numbers");
105    }
106
107.. [#f1] In practice, implementation and binding code will generally be located
108         in separate files.
109
110The :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``)
112is given as the first macro argument (it should not be in quotes). The second
113argument (``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.
116
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
125pybind11 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:
128
129.. code-block:: bash
130
131    $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
132
133For 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.
136
137The `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:
150
151.. code-block:: pycon
152
153    $ python
154    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
160    >>>
161
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
180.. code-block:: pycon
181
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
188.. code-block:: pycon
189
190    >>> help(example)
191
192    ....
193
194    FUNCTIONS
195        add(...)
196            Signature : (i: int, j: int) -> int
197
198            A function which adds two numbers
199
200A shorter notation for named arguments is also available:
201
202.. code-block:: cpp
203
204    // 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
210The :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
213from the ``pybind11`` namespace except for literals.
214
215.. _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
239.. code-block:: pycon
240
241    >>> help(example)
242
243    ....
244
245    FUNCTIONS
246        add(...)
247            Signature : (i: int = 1, j: int = 2) -> int
248
249            A function which adds two numbers
250
251The shorthand notation is also available for default arguments:
252
253.. code-block:: cpp
254
255    // 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
260Exporting variables
261===================
262
263To 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
266converted using the function ``py::cast``.
267
268.. code-block:: cpp
269
270    PYBIND11_MODULE(example, m) {
271        m.attr("the_answer") = 42;
272        py::object world = py::cast("World");
273        m.attr("what") = world;
274    }
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
286.. _supported_types:
287
288Supported data types
289====================
290
291A 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.
294