basics.rst revision 12391
11060SN/A.. _basics: 27944SGiacomo.Gabrielli@arm.com 37944SGiacomo.Gabrielli@arm.comFirst steps 47944SGiacomo.Gabrielli@arm.com########### 57944SGiacomo.Gabrielli@arm.com 67944SGiacomo.Gabrielli@arm.comThis sections demonstrates the basic features of pybind11. Before getting 77944SGiacomo.Gabrielli@arm.comstarted, make sure that development environment is set up to compile the 87944SGiacomo.Gabrielli@arm.comincluded set of test cases. 97944SGiacomo.Gabrielli@arm.com 107944SGiacomo.Gabrielli@arm.com 117944SGiacomo.Gabrielli@arm.comCompiling the test cases 127944SGiacomo.Gabrielli@arm.com======================== 137944SGiacomo.Gabrielli@arm.com 142702Sktlim@umich.eduLinux/MacOS 156973Stjones1@inf.ed.ac.uk----------- 161060SN/A 171060SN/AOn Linux you'll need to install the **python-dev** or **python3-dev** packages as 181060SN/Awell as **cmake**. On Mac OS, the included python version works out of the box, 191060SN/Abut **cmake** must still be installed. 201060SN/A 211060SN/AAfter installing the prerequisites, run 221060SN/A 231060SN/A.. code-block:: bash 241060SN/A 251060SN/A mkdir build 261060SN/A cd build 271060SN/A cmake .. 281060SN/A make check -j 4 291060SN/A 301060SN/AThe last line will both compile and run the tests. 311060SN/A 321060SN/AWindows 331060SN/A------- 341060SN/A 351060SN/AOn Windows, only **Visual Studio 2015** and newer are supported since pybind11 relies 361060SN/Aon various C++11 language features that break older versions of Visual Studio. 371060SN/A 381060SN/ATo compile and run the tests: 391060SN/A 402665Ssaidi@eecs.umich.edu.. code-block:: batch 412665Ssaidi@eecs.umich.edu 426973Stjones1@inf.ed.ac.uk mkdir build 431060SN/A cd build 441060SN/A cmake .. 451464SN/A cmake --build . --config Release --target check 461464SN/A 471060SN/AThis will create a Visual Studio project, compile and run the target, all from the 482731Sktlim@umich.educommand line. 492292SN/A 501464SN/A.. Note:: 518733Sgeoffrey.blake@arm.com 521060SN/A If all tests fail, make sure that the Python binary and the testcases are compiled 537720Sgblack@eecs.umich.edu for the same processor type and bitness (i.e. either **i386** or **x86_64**). You 541060SN/A can specify **x86_64** as the target architecture for the generated Visual Studio 551060SN/A project using ``cmake -A x64 ..``. 566658Snate@binkert.org 578733Sgeoffrey.blake@arm.com.. seealso:: 583770Sgblack@eecs.umich.edu 591464SN/A Advanced users who are already familiar with Boost.Python may want to skip 601464SN/A the tutorial and look at the test cases in the :file:`tests` directory, 612669Sktlim@umich.edu which exercise all features of pybind11. 621060SN/A 636973Stjones1@inf.ed.ac.ukHeader and namespace conventions 642669Sktlim@umich.edu================================ 657678Sgblack@eecs.umich.edu 668817Sgblack@eecs.umich.eduFor brevity, all code examples assume that the following two lines are present: 672292SN/A 686023Snate@binkert.org.. code-block:: cpp 691060SN/A 701060SN/A #include <pybind11/pybind11.h> 711060SN/A 721060SN/A namespace py = pybind11; 731060SN/A 741060SN/ASome features may require additional headers, but those will be specified as needed. 751060SN/A 761061SN/A.. _simple_example: 771060SN/A 781060SN/ACreating bindings for a simple function 791060SN/A======================================= 802733Sktlim@umich.edu 812733Sktlim@umich.eduLet's start by creating Python bindings for an extremely simple function, which 821060SN/Aadds two numbers and returns their result: 832292SN/A 842107SN/A.. code-block:: cpp 852690Sktlim@umich.edu 862107SN/A int add(int i, int j) { 872690Sktlim@umich.edu return i + j; 882690Sktlim@umich.edu } 891060SN/A 902292SN/AFor simplicity [#f1]_, we'll put both this function and the binding code into 912292SN/Aa file named :file:`example.cpp` with the following contents: 928486Sgblack@eecs.umich.edu 932292SN/A.. code-block:: cpp 942292SN/A 952292SN/A #include <pybind11/pybind11.h> 962292SN/A 971060SN/A int add(int i, int j) { 985543Ssaidi@eecs.umich.edu return i + j; 995543Ssaidi@eecs.umich.edu } 1001060SN/A 1011060SN/A PYBIND11_MODULE(example, m) { 1022292SN/A m.doc() = "pybind11 example plugin"; // optional module docstring 1032107SN/A 1048502Sgblack@eecs.umich.edu m.def("add", &add, "A function which adds two numbers"); 1051060SN/A } 1061060SN/A 1071060SN/A.. [#f1] In practice, implementation and binding code will generally be located 1081060SN/A in separate files. 1091060SN/A 1101060SN/AThe :func:`PYBIND11_MODULE` macro creates a function that will be called when an 1112292SN/A``import`` statement is issued from within Python. The module name (``example``) 1121060SN/Ais given as the first macro argument (it should not be in quotes). The second 1131060SN/Aargument (``m``) defines a variable of type :class:`py::module <module>` which 1145358Sgblack@eecs.umich.eduis the main interface for creating bindings. The method :func:`module::def` 1155358Sgblack@eecs.umich.edugenerates binding code that exposes the ``add()`` function to Python. 1165358Sgblack@eecs.umich.edu 1175358Sgblack@eecs.umich.edu.. note:: 1185358Sgblack@eecs.umich.edu 1195358Sgblack@eecs.umich.edu Notice how little code was needed to expose our function to Python: all 1205358Sgblack@eecs.umich.edu details regarding the function's parameters and return value were 1215358Sgblack@eecs.umich.edu automatically inferred using template metaprogramming. This overall 1225358Sgblack@eecs.umich.edu approach and the used syntax are borrowed from Boost.Python, though the 1235358Sgblack@eecs.umich.edu underlying implementation is very different. 1245358Sgblack@eecs.umich.edu 1255358Sgblack@eecs.umich.edupybind11 is a header-only library, hence it is not necessary to link against 1265358Sgblack@eecs.umich.eduany special libraries and there are no intermediate (magic) translation steps. 1278444Sgblack@eecs.umich.eduOn Linux, the above example can be compiled using the following command: 1287520Sgblack@eecs.umich.edu 1298444Sgblack@eecs.umich.edu.. code-block:: bash 1308444Sgblack@eecs.umich.edu 1317520Sgblack@eecs.umich.edu $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix` 1326974Stjones1@inf.ed.ac.uk 1336974Stjones1@inf.ed.ac.ukFor more details on the required compiler flags on Linux and MacOS, see 1346974Stjones1@inf.ed.ac.uk:ref:`building_manually`. For complete cross-platform compilation instructions, 1356974Stjones1@inf.ed.ac.ukrefer to the :ref:`compiling` page. 1366973Stjones1@inf.ed.ac.uk 1376974Stjones1@inf.ed.ac.ukThe `python_example`_ and `cmake_example`_ repositories are also a good place 1386974Stjones1@inf.ed.ac.ukto start. They are both complete project examples with cross-platform build 1396973Stjones1@inf.ed.ac.uksystems. The only difference between the two is that `python_example`_ uses 1406973Stjones1@inf.ed.ac.ukPython's ``setuptools`` to build the module, while `cmake_example`_ uses CMake 1416973Stjones1@inf.ed.ac.uk(which may be preferable for existing C++ projects). 1426973Stjones1@inf.ed.ac.uk 1431060SN/A.. _python_example: https://github.com/pybind/python_example 1447944SGiacomo.Gabrielli@arm.com.. _cmake_example: https://github.com/pybind/cmake_example 1457944SGiacomo.Gabrielli@arm.com 1467944SGiacomo.Gabrielli@arm.comBuilding the above C++ code will produce a binary module file that can be 1477944SGiacomo.Gabrielli@arm.comimported to Python. Assuming that the compiled module is located in the 1487944SGiacomo.Gabrielli@arm.comcurrent directory, the following interactive Python session shows how to 1497944SGiacomo.Gabrielli@arm.comload and execute the example: 1508545Ssaidi@eecs.umich.edu 1518545Ssaidi@eecs.umich.edu.. code-block:: pycon 1528545Ssaidi@eecs.umich.edu 1538545Ssaidi@eecs.umich.edu $ python 1548545Ssaidi@eecs.umich.edu Python 2.7.10 (default, Aug 22 2015, 20:33:39) 1558545Ssaidi@eecs.umich.edu [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin 1568545Ssaidi@eecs.umich.edu Type "help", "copyright", "credits" or "license" for more information. 1578545Ssaidi@eecs.umich.edu >>> import example 1588545Ssaidi@eecs.umich.edu >>> example.add(1, 2) 1598545Ssaidi@eecs.umich.edu 3L 1608545Ssaidi@eecs.umich.edu >>> 1618545Ssaidi@eecs.umich.edu 1628545Ssaidi@eecs.umich.edu.. _keyword_args: 1637944SGiacomo.Gabrielli@arm.com 1647944SGiacomo.Gabrielli@arm.comKeyword arguments 1657944SGiacomo.Gabrielli@arm.com================= 1667944SGiacomo.Gabrielli@arm.com 1677944SGiacomo.Gabrielli@arm.comWith a simple modification code, it is possible to inform Python about the 1687944SGiacomo.Gabrielli@arm.comnames of the arguments ("i" and "j" in this case). 1697944SGiacomo.Gabrielli@arm.com 1707944SGiacomo.Gabrielli@arm.com.. code-block:: cpp 1717944SGiacomo.Gabrielli@arm.com 1727944SGiacomo.Gabrielli@arm.com m.def("add", &add, "A function which adds two numbers", 1737944SGiacomo.Gabrielli@arm.com py::arg("i"), py::arg("j")); 1747944SGiacomo.Gabrielli@arm.com 1757944SGiacomo.Gabrielli@arm.com:class:`arg` is one of several special tag classes which can be used to pass 1767944SGiacomo.Gabrielli@arm.commetadata into :func:`module::def`. With this modified binding code, we can now 1777944SGiacomo.Gabrielli@arm.comcall the function using keyword arguments, which is a more readable alternative 1787944SGiacomo.Gabrielli@arm.comparticularly for functions taking many parameters: 1797944SGiacomo.Gabrielli@arm.com 1808733Sgeoffrey.blake@arm.com.. code-block:: pycon 1818733Sgeoffrey.blake@arm.com 1828733Sgeoffrey.blake@arm.com >>> import example 1838733Sgeoffrey.blake@arm.com >>> example.add(i=1, j=2) 1848733Sgeoffrey.blake@arm.com 3L 1851684SN/A 1861060SN/AThe keyword names also appear in the function signatures within the documentation. 1871060SN/A 1881060SN/A.. code-block:: pycon 1891060SN/A 1902731Sktlim@umich.edu >>> help(example) 1912731Sktlim@umich.edu 1922731Sktlim@umich.edu .... 1932731Sktlim@umich.edu 1942731Sktlim@umich.edu FUNCTIONS 1952731Sktlim@umich.edu add(...) 1962731Sktlim@umich.edu Signature : (i: int, j: int) -> int 1972731Sktlim@umich.edu 1982731Sktlim@umich.edu A function which adds two numbers 1992731Sktlim@umich.edu 2002731Sktlim@umich.eduA shorter notation for named arguments is also available: 2012731Sktlim@umich.edu 2022731Sktlim@umich.edu.. code-block:: cpp 2032731Sktlim@umich.edu 2042731Sktlim@umich.edu // regular notation 2052731Sktlim@umich.edu m.def("add1", &add, py::arg("i"), py::arg("j")); 2062731Sktlim@umich.edu // shorthand 2072731Sktlim@umich.edu using namespace pybind11::literals; 2082731Sktlim@umich.edu m.def("add2", &add, "i"_a, "j"_a); 2092731Sktlim@umich.edu 2102731Sktlim@umich.eduThe :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`. 2112731Sktlim@umich.eduNote that the literal operator must first be made visible with the directive 2122731Sktlim@umich.edu``using namespace pybind11::literals``. This does not bring in anything else 2132731Sktlim@umich.edufrom the ``pybind11`` namespace except for literals. 2142731Sktlim@umich.edu 2152292SN/A.. _default_args: 2162731Sktlim@umich.edu 2172731Sktlim@umich.eduDefault arguments 2181060SN/A================= 2191060SN/A 2206221Snate@binkert.orgSuppose now that the function to be bound has default arguments, e.g.: 2211060SN/A 2221060SN/A.. code-block:: cpp 2231060SN/A 2241060SN/A int add(int i = 1, int j = 2) { 2252292SN/A return i + j; 2262292SN/A } 2272292SN/A 2282733Sktlim@umich.eduUnfortunately, pybind11 cannot automatically extract these parameters, since they 2292733Sktlim@umich.eduare not part of the function's type information. However, they are simple to specify 2301060SN/Ausing an extension of :class:`arg`: 2312680Sktlim@umich.edu 2322292SN/A.. code-block:: cpp 2331060SN/A 2341060SN/A m.def("add", &add, "A function which adds two numbers", 2352132SN/A py::arg("i") = 1, py::arg("j") = 2); 2361060SN/A 2372702Sktlim@umich.eduThe default values also appear within the documentation. 2382669Sktlim@umich.edu 2392292SN/A.. code-block:: pycon 2401060SN/A 2411060SN/A >>> help(example) 2421060SN/A 2438199SAli.Saidi@ARM.com .... 2448199SAli.Saidi@ARM.com 2458199SAli.Saidi@ARM.com FUNCTIONS 2464032Sktlim@umich.edu add(...) 2474032Sktlim@umich.edu Signature : (i: int = 1, j: int = 2) -> int 2484032Sktlim@umich.edu 2491060SN/A A function which adds two numbers 2501060SN/A 2511060SN/AThe shorthand notation is also available for default arguments: 2521060SN/A 2531060SN/A.. code-block:: cpp 2541060SN/A 2551464SN/A // regular notation 2561464SN/A m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2); 2571464SN/A // shorthand 2588733Sgeoffrey.blake@arm.com m.def("add2", &add, "i"_a=1, "j"_a=2); 2598733Sgeoffrey.blake@arm.com 2608733Sgeoffrey.blake@arm.comExporting variables 2618733Sgeoffrey.blake@arm.com=================== 2621464SN/A 2631060SN/ATo expose a value from C++, use the ``attr`` function to register it in a 2648733Sgeoffrey.blake@arm.commodule as shown below. Built-in types and general objects (more on that later) 2658733Sgeoffrey.blake@arm.comare automatically converted when assigned as attributes, and can be explicitly 2661464SN/Aconverted using the function ``py::cast``. 2678733Sgeoffrey.blake@arm.com 2681060SN/A.. code-block:: cpp 2693326Sktlim@umich.edu 2703326Sktlim@umich.edu PYBIND11_MODULE(example, m) { 2713326Sktlim@umich.edu m.attr("the_answer") = 42; 2727597Sminkyu.jeong@arm.com py::object world = py::cast("World"); 2737597Sminkyu.jeong@arm.com m.attr("what") = world; 2747597Sminkyu.jeong@arm.com } 2753965Sgblack@eecs.umich.edu 2767720Sgblack@eecs.umich.eduThese are then accessible from Python: 2777720Sgblack@eecs.umich.edu 2781060SN/A.. code-block:: pycon 2797720Sgblack@eecs.umich.edu 2807720Sgblack@eecs.umich.edu >>> import example 2814636Sgblack@eecs.umich.edu >>> example.the_answer 2823794Sgblack@eecs.umich.edu 42 2833794Sgblack@eecs.umich.edu >>> example.what 2843794Sgblack@eecs.umich.edu 'World' 2853965Sgblack@eecs.umich.edu 2863965Sgblack@eecs.umich.edu.. _supported_types: 2872292SN/A 2882292SN/ASupported data types 2892292SN/A==================== 2902292SN/A 2912292SN/AA large number of data types are supported out of the box and can be used 2922292SN/Aseamlessly as functions arguments, return values or with ``py::cast`` in general. 2931060SN/AFor a full overview, see the :doc:`advanced/cast/index` section. 2941060SN/A