Warning, /jana2/src/python/externals/pybind11-2.10.3/docs/basics.rst is written in an unsupported language. File is not indexed.
0001 .. _basics:
0002
0003 First steps
0004 ###########
0005
0006 This sections demonstrates the basic features of pybind11. Before getting
0007 started, make sure that development environment is set up to compile the
0008 included set of test cases.
0009
0010
0011 Compiling the test cases
0012 ========================
0013
0014 Linux/macOS
0015 -----------
0016
0017 On Linux you'll need to install the **python-dev** or **python3-dev** packages as
0018 well as **cmake**. On macOS, the included python version works out of the box,
0019 but **cmake** must still be installed.
0020
0021 After installing the prerequisites, run
0022
0023 .. code-block:: bash
0024
0025 mkdir build
0026 cd build
0027 cmake ..
0028 make check -j 4
0029
0030 The last line will both compile and run the tests.
0031
0032 Windows
0033 -------
0034
0035 On Windows, only **Visual Studio 2017** and newer are supported.
0036
0037 .. Note::
0038
0039 To use the C++17 in Visual Studio 2017 (MSVC 14.1), pybind11 requires the flag
0040 ``/permissive-`` to be passed to the compiler `to enforce standard conformance`_. When
0041 building with Visual Studio 2019, this is not strictly necessary, but still advised.
0042
0043 .. _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017
0044
0045 To compile and run the tests:
0046
0047 .. code-block:: batch
0048
0049 mkdir build
0050 cd build
0051 cmake ..
0052 cmake --build . --config Release --target check
0053
0054 This will create a Visual Studio project, compile and run the target, all from the
0055 command line.
0056
0057 .. Note::
0058
0059 If all tests fail, make sure that the Python binary and the testcases are compiled
0060 for the same processor type and bitness (i.e. either **i386** or **x86_64**). You
0061 can specify **x86_64** as the target architecture for the generated Visual Studio
0062 project using ``cmake -A x64 ..``.
0063
0064 .. seealso::
0065
0066 Advanced users who are already familiar with Boost.Python may want to skip
0067 the tutorial and look at the test cases in the :file:`tests` directory,
0068 which exercise all features of pybind11.
0069
0070 Header and namespace conventions
0071 ================================
0072
0073 For brevity, all code examples assume that the following two lines are present:
0074
0075 .. code-block:: cpp
0076
0077 #include <pybind11/pybind11.h>
0078
0079 namespace py = pybind11;
0080
0081 Some features may require additional headers, but those will be specified as needed.
0082
0083 .. _simple_example:
0084
0085 Creating bindings for a simple function
0086 =======================================
0087
0088 Let's start by creating Python bindings for an extremely simple function, which
0089 adds two numbers and returns their result:
0090
0091 .. code-block:: cpp
0092
0093 int add(int i, int j) {
0094 return i + j;
0095 }
0096
0097 For simplicity [#f1]_, we'll put both this function and the binding code into
0098 a file named :file:`example.cpp` with the following contents:
0099
0100 .. code-block:: cpp
0101
0102 #include <pybind11/pybind11.h>
0103
0104 int add(int i, int j) {
0105 return i + j;
0106 }
0107
0108 PYBIND11_MODULE(example, m) {
0109 m.doc() = "pybind11 example plugin"; // optional module docstring
0110
0111 m.def("add", &add, "A function that adds two numbers");
0112 }
0113
0114 .. [#f1] In practice, implementation and binding code will generally be located
0115 in separate files.
0116
0117 The :func:`PYBIND11_MODULE` macro creates a function that will be called when an
0118 ``import`` statement is issued from within Python. The module name (``example``)
0119 is given as the first macro argument (it should not be in quotes). The second
0120 argument (``m``) defines a variable of type :class:`py::module_ <module>` which
0121 is the main interface for creating bindings. The method :func:`module_::def`
0122 generates binding code that exposes the ``add()`` function to Python.
0123
0124 .. note::
0125
0126 Notice how little code was needed to expose our function to Python: all
0127 details regarding the function's parameters and return value were
0128 automatically inferred using template metaprogramming. This overall
0129 approach and the used syntax are borrowed from Boost.Python, though the
0130 underlying implementation is very different.
0131
0132 pybind11 is a header-only library, hence it is not necessary to link against
0133 any special libraries and there are no intermediate (magic) translation steps.
0134 On Linux, the above example can be compiled using the following command:
0135
0136 .. code-block:: bash
0137
0138 $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
0139
0140 .. note::
0141
0142 If you used :ref:`include_as_a_submodule` to get the pybind11 source, then
0143 use ``$(python3-config --includes) -Iextern/pybind11/include`` instead of
0144 ``$(python3 -m pybind11 --includes)`` in the above compilation, as
0145 explained in :ref:`building_manually`.
0146
0147 For more details on the required compiler flags on Linux and macOS, see
0148 :ref:`building_manually`. For complete cross-platform compilation instructions,
0149 refer to the :ref:`compiling` page.
0150
0151 The `python_example`_ and `cmake_example`_ repositories are also a good place
0152 to start. They are both complete project examples with cross-platform build
0153 systems. The only difference between the two is that `python_example`_ uses
0154 Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake
0155 (which may be preferable for existing C++ projects).
0156
0157 .. _python_example: https://github.com/pybind/python_example
0158 .. _cmake_example: https://github.com/pybind/cmake_example
0159
0160 Building the above C++ code will produce a binary module file that can be
0161 imported to Python. Assuming that the compiled module is located in the
0162 current directory, the following interactive Python session shows how to
0163 load and execute the example:
0164
0165 .. code-block:: pycon
0166
0167 $ python
0168 Python 3.9.10 (main, Jan 15 2022, 11:48:04)
0169 [Clang 13.0.0 (clang-1300.0.29.3)] on darwin
0170 Type "help", "copyright", "credits" or "license" for more information.
0171 >>> import example
0172 >>> example.add(1, 2)
0173 3
0174 >>>
0175
0176 .. _keyword_args:
0177
0178 Keyword arguments
0179 =================
0180
0181 With a simple code modification, it is possible to inform Python about the
0182 names of the arguments ("i" and "j" in this case).
0183
0184 .. code-block:: cpp
0185
0186 m.def("add", &add, "A function which adds two numbers",
0187 py::arg("i"), py::arg("j"));
0188
0189 :class:`arg` is one of several special tag classes which can be used to pass
0190 metadata into :func:`module_::def`. With this modified binding code, we can now
0191 call the function using keyword arguments, which is a more readable alternative
0192 particularly for functions taking many parameters:
0193
0194 .. code-block:: pycon
0195
0196 >>> import example
0197 >>> example.add(i=1, j=2)
0198 3L
0199
0200 The keyword names also appear in the function signatures within the documentation.
0201
0202 .. code-block:: pycon
0203
0204 >>> help(example)
0205
0206 ....
0207
0208 FUNCTIONS
0209 add(...)
0210 Signature : (i: int, j: int) -> int
0211
0212 A function which adds two numbers
0213
0214 A shorter notation for named arguments is also available:
0215
0216 .. code-block:: cpp
0217
0218 // regular notation
0219 m.def("add1", &add, py::arg("i"), py::arg("j"));
0220 // shorthand
0221 using namespace pybind11::literals;
0222 m.def("add2", &add, "i"_a, "j"_a);
0223
0224 The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
0225 Note that the literal operator must first be made visible with the directive
0226 ``using namespace pybind11::literals``. This does not bring in anything else
0227 from the ``pybind11`` namespace except for literals.
0228
0229 .. _default_args:
0230
0231 Default arguments
0232 =================
0233
0234 Suppose now that the function to be bound has default arguments, e.g.:
0235
0236 .. code-block:: cpp
0237
0238 int add(int i = 1, int j = 2) {
0239 return i + j;
0240 }
0241
0242 Unfortunately, pybind11 cannot automatically extract these parameters, since they
0243 are not part of the function's type information. However, they are simple to specify
0244 using an extension of :class:`arg`:
0245
0246 .. code-block:: cpp
0247
0248 m.def("add", &add, "A function which adds two numbers",
0249 py::arg("i") = 1, py::arg("j") = 2);
0250
0251 The default values also appear within the documentation.
0252
0253 .. code-block:: pycon
0254
0255 >>> help(example)
0256
0257 ....
0258
0259 FUNCTIONS
0260 add(...)
0261 Signature : (i: int = 1, j: int = 2) -> int
0262
0263 A function which adds two numbers
0264
0265 The shorthand notation is also available for default arguments:
0266
0267 .. code-block:: cpp
0268
0269 // regular notation
0270 m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
0271 // shorthand
0272 m.def("add2", &add, "i"_a=1, "j"_a=2);
0273
0274 Exporting variables
0275 ===================
0276
0277 To expose a value from C++, use the ``attr`` function to register it in a
0278 module as shown below. Built-in types and general objects (more on that later)
0279 are automatically converted when assigned as attributes, and can be explicitly
0280 converted using the function ``py::cast``.
0281
0282 .. code-block:: cpp
0283
0284 PYBIND11_MODULE(example, m) {
0285 m.attr("the_answer") = 42;
0286 py::object world = py::cast("World");
0287 m.attr("what") = world;
0288 }
0289
0290 These are then accessible from Python:
0291
0292 .. code-block:: pycon
0293
0294 >>> import example
0295 >>> example.the_answer
0296 42
0297 >>> example.what
0298 'World'
0299
0300 .. _supported_types:
0301
0302 Supported data types
0303 ====================
0304
0305 A large number of data types are supported out of the box and can be used
0306 seamlessly as functions arguments, return values or with ``py::cast`` in general.
0307 For a full overview, see the :doc:`advanced/cast/index` section.