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 macOS, 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
38.. 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 advised.
43
44..  _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017
45
46To compile and run the tests:
47
48.. code-block:: batch
49
50   mkdir build
51   cd build
52   cmake ..
53   cmake --build . --config Release --target check
54
55This will create a Visual Studio project, compile and run the target, all from the
56command line.
57
58.. Note::
59
60    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 ..``.
64
65.. seealso::
66
67    Advanced users who are already familiar with Boost.Python may want to skip
68    the tutorial and look at the test cases in the :file:`tests` directory,
69    which exercise all features of pybind11.
70
71Header 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
84.. _simple_example:
85
86Creating 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
103    #include <pybind11/pybind11.h>
104
105    int add(int i, int j) {
106        return i + j;
107    }
108
109    PYBIND11_MODULE(example, m) {
110        m.doc() = "pybind11 example plugin"; // optional module docstring
111
112        m.def("add", &add, "A function which adds two numbers");
113    }
114
115.. [#f1] In practice, implementation and binding code will generally be located
116         in separate files.
117
118The :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``)
120is given as the first macro argument (it should not be in quotes). The second
121argument (``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.
124
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
133pybind11 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:
136
137.. code-block:: bash
138
139    $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
140
141.. note::
142
143    If you used :ref:`include_as_a_submodule` to get the pybind11 source, then
144    use ``$(python3-config --includes) -Iextern/pybind11/include`` instead of
145    ``$(python3 -m pybind11 --includes)`` in the above compilation, as
146    explained in :ref:`building_manually`.
147
148For more details on the required compiler flags on Linux and macOS, see
149:ref:`building_manually`. For complete cross-platform compilation instructions,
150refer to the :ref:`compiling` page.
151
152The `python_example`_ and `cmake_example`_ repositories are also a good place
153to start. They are both complete project examples with cross-platform build
154systems. The only difference between the two is that `python_example`_ uses
155Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake
156(which may be preferable for existing C++ projects).
157
158.. _python_example: https://github.com/pybind/python_example
159.. _cmake_example: https://github.com/pybind/cmake_example
160
161Building the above C++ code will produce a binary module file that can be
162imported to Python. Assuming that the compiled module is located in the
163current directory, the following interactive Python session shows how to
164load and execute the example:
165
166.. code-block:: pycon
167
168    $ python
169    Python 2.7.10 (default, Aug 22 2015, 20:33:39)
170    [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
171    Type "help", "copyright", "credits" or "license" for more information.
172    >>> import example
173    >>> example.add(1, 2)
174    3L
175    >>>
176
177.. _keyword_args:
178
179Keyword arguments
180=================
181
182With a simple code modification, it is possible to inform Python about the
183names of the arguments ("i" and "j" in this case).
184
185.. code-block:: cpp
186
187    m.def("add", &add, "A function which adds two numbers",
188          py::arg("i"), py::arg("j"));
189
190:class:`arg` is one of several special tag classes which can be used to pass
191metadata into :func:`module_::def`. With this modified binding code, we can now
192call the function using keyword arguments, which is a more readable alternative
193particularly for functions taking many parameters:
194
195.. code-block:: pycon
196
197    >>> import example
198    >>> example.add(i=1, j=2)
199    3L
200
201The keyword names also appear in the function signatures within the documentation.
202
203.. code-block:: pycon
204
205    >>> help(example)
206
207    ....
208
209    FUNCTIONS
210        add(...)
211            Signature : (i: int, j: int) -> int
212
213            A function which adds two numbers
214
215A shorter notation for named arguments is also available:
216
217.. code-block:: cpp
218
219    // regular notation
220    m.def("add1", &add, py::arg("i"), py::arg("j"));
221    // shorthand
222    using namespace pybind11::literals;
223    m.def("add2", &add, "i"_a, "j"_a);
224
225The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
226Note that the literal operator must first be made visible with the directive
227``using namespace pybind11::literals``. This does not bring in anything else
228from the ``pybind11`` namespace except for literals.
229
230.. _default_args:
231
232Default arguments
233=================
234
235Suppose now that the function to be bound has default arguments, e.g.:
236
237.. code-block:: cpp
238
239    int add(int i = 1, int j = 2) {
240        return i + j;
241    }
242
243Unfortunately, pybind11 cannot automatically extract these parameters, since they
244are not part of the function's type information. However, they are simple to specify
245using an extension of :class:`arg`:
246
247.. code-block:: cpp
248
249    m.def("add", &add, "A function which adds two numbers",
250          py::arg("i") = 1, py::arg("j") = 2);
251
252The default values also appear within the documentation.
253
254.. code-block:: pycon
255
256    >>> help(example)
257
258    ....
259
260    FUNCTIONS
261        add(...)
262            Signature : (i: int = 1, j: int = 2) -> int
263
264            A function which adds two numbers
265
266The shorthand notation is also available for default arguments:
267
268.. code-block:: cpp
269
270    // regular notation
271    m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
272    // shorthand
273    m.def("add2", &add, "i"_a=1, "j"_a=2);
274
275Exporting variables
276===================
277
278To expose a value from C++, use the ``attr`` function to register it in a
279module as shown below. Built-in types and general objects (more on that later)
280are automatically converted when assigned as attributes, and can be explicitly
281converted using the function ``py::cast``.
282
283.. code-block:: cpp
284
285    PYBIND11_MODULE(example, m) {
286        m.attr("the_answer") = 42;
287        py::object world = py::cast("World");
288        m.attr("what") = world;
289    }
290
291These are then accessible from Python:
292
293.. code-block:: pycon
294
295    >>> import example
296    >>> example.the_answer
297    42
298    >>> example.what
299    'World'
300
301.. _supported_types:
302
303Supported data types
304====================
305
306A large number of data types are supported out of the box and can be used
307seamlessly as functions arguments, return values or with ``py::cast`` in general.
308For a full overview, see the :doc:`advanced/cast/index` section.
309