basics.rst revision 12037:d28054ac6ec9
12SN/A.. _basics:
211856Sbrandon.potter@amd.com
31762SN/AFirst steps
42SN/A###########
52SN/A
62SN/AThis sections demonstrates the basic features of pybind11. Before getting
72SN/Astarted, make sure that development environment is set up to compile the
82SN/Aincluded set of test cases.
92SN/A
102SN/A
112SN/ACompiling the test cases
122SN/A========================
132SN/A
142SN/ALinux/MacOS
152SN/A-----------
162SN/A
172SN/AOn Linux  you'll need to install the **python-dev** or **python3-dev** packages as
182SN/Awell as **cmake**. On Mac OS, the included python version works out of the box,
192SN/Abut **cmake** must still be installed.
202SN/A
212SN/AAfter installing the prerequisites, run
222SN/A
232SN/A.. code-block:: bash
242SN/A
252SN/A   mkdir build
262SN/A   cd build
272SN/A   cmake ..
282665Ssaidi@eecs.umich.edu   make check -j 4
292665Ssaidi@eecs.umich.edu
302665Ssaidi@eecs.umich.eduThe last line will both compile and run the tests.
3111856Sbrandon.potter@amd.com
322SN/AWindows
332SN/A-------
34360SN/A
35360SN/AOn Windows, only **Visual Studio 2015** and newer are supported since pybind11 relies
362SN/Aon various C++11 language features that break older versions of Visual Studio.
3711854Sbrandon.potter@amd.com
3811854Sbrandon.potter@amd.comTo compile and run the tests:
3911800Sbrandon.potter@amd.com
404117Sgblack@eecs.umich.edu.. code-block:: batch
41180SN/A
422SN/A   mkdir build
436329Sgblack@eecs.umich.edu   cd build
442378SN/A   cmake ..
456214Snate@binkert.org   cmake --build . --config Release --target check
466658Snate@binkert.org
478852Sandreas.hansson@arm.comThis will create a Visual Studio project, compile and run the target, all from the
4811856Sbrandon.potter@amd.comcommand line.
4910930Sbrandon.potter@amd.com
5011905SBrandon.Potter@amd.com.. Note::
5156SN/A
522SN/A    If all tests fail, make sure that the Python binary and the testcases are compiled
538737Skoansin.tan@gmail.com    for the same processor type and bitness (i.e. either **i386** or **x86_64**). You
5411800Sbrandon.potter@amd.com    can specify **x86_64** as the target architecture for the generated Visual Studio
5511800Sbrandon.potter@amd.com    project using ``cmake -A x64 ..``.
5611851Sbrandon.potter@amd.com
5712448Sgabeblack@google.com.. seealso::
585154Sgblack@eecs.umich.edu
5911800Sbrandon.potter@amd.com    Advanced users who are already familiar with Boost.Python may want to skip
605154Sgblack@eecs.umich.edu    the tutorial and look at the test cases in the :file:`tests` directory,
612680Sktlim@umich.edu    which exercise all features of pybind11.
622378SN/A
632SN/AHeader and namespace conventions
642SN/A================================
652SN/A
6612448Sgabeblack@google.comFor brevity, all code examples assume that the following two lines are present:
6712431Sgabeblack@google.com
682SN/A.. code-block:: cpp
6911854Sbrandon.potter@amd.com
7011854Sbrandon.potter@amd.com    #include <pybind11/pybind11.h>
712SN/A
7211169Sandreas.hansson@arm.com    namespace py = pybind11;
7311168Sandreas.hansson@arm.com
7410905Sandreas.sandberg@arm.comSome features may require additional headers, but those will be specified as needed.
7512044Sgabeblack@google.com
7613557Sgabeblack@google.comCreating bindings for a simple function
7713557Sgabeblack@google.com=======================================
7813557Sgabeblack@google.com
7911854Sbrandon.potter@amd.comLet's start by creating Python bindings for an extremely simple function, which
8011854Sbrandon.potter@amd.comadds two numbers and returns their result:
8111854Sbrandon.potter@amd.com
822SN/A.. code-block:: cpp
8311854Sbrandon.potter@amd.com
8411854Sbrandon.potter@amd.com    int add(int i, int j) {
8511854Sbrandon.potter@amd.com        return i + j;
8611854Sbrandon.potter@amd.com    }
8711854Sbrandon.potter@amd.com
8811854Sbrandon.potter@amd.comFor simplicity [#f1]_, we'll put both this function and the binding code into
8911885Sbrandon.potter@amd.coma file named :file:`example.cpp` with the following contents:
9011885Sbrandon.potter@amd.com
9111885Sbrandon.potter@amd.com.. code-block:: cpp
9210554Salexandru.dutu@amd.com
9311854Sbrandon.potter@amd.com    #include <pybind11/pybind11.h>
948852Sandreas.hansson@arm.com
9511854Sbrandon.potter@amd.com    int add(int i, int j) {
9611854Sbrandon.potter@amd.com        return i + j;
9711854Sbrandon.potter@amd.com    }
9811854Sbrandon.potter@amd.com
9911919SBrandon.Potter@amd.com    namespace py = pybind11;
10011854Sbrandon.potter@amd.com
10111854Sbrandon.potter@amd.com    PYBIND11_PLUGIN(example) {
1028852Sandreas.hansson@arm.com        py::module m("example", "pybind11 example plugin");
10311854Sbrandon.potter@amd.com
10411854Sbrandon.potter@amd.com        m.def("add", &add, "A function which adds two numbers");
10511854Sbrandon.potter@amd.com
10611854Sbrandon.potter@amd.com        return m.ptr();
10711854Sbrandon.potter@amd.com    }
10811854Sbrandon.potter@amd.com
10911854Sbrandon.potter@amd.com.. [#f1] In practice, implementation and binding code will generally be located
1105282Srstrong@cs.ucsd.edu         in separate files.
1112SN/A
11211169Sandreas.hansson@arm.comThe :func:`PYBIND11_PLUGIN` macro creates a function that will be called when an
1132SN/A``import`` statement is issued from within Python. The next line creates a
1148601Ssteve.reinhardt@amd.commodule named ``example`` (with the supplied docstring). The method
1158601Ssteve.reinhardt@amd.com:func:`module::def` generates binding code that exposes the
1168539Sgblack@eecs.umich.edu``add()`` function to Python. The last line returns the internal Python object
1178539Sgblack@eecs.umich.eduassociated with ``m`` to the Python interpreter.
1188539Sgblack@eecs.umich.edu
1194434Ssaidi@eecs.umich.edu.. note::
12011854Sbrandon.potter@amd.com
12111854Sbrandon.potter@amd.com    Notice how little code was needed to expose our function to Python: all
12211854Sbrandon.potter@amd.com    details regarding the function's parameters and return value were
12311854Sbrandon.potter@amd.com    automatically inferred using template metaprogramming. This overall
12411854Sbrandon.potter@amd.com    approach and the used syntax are borrowed from Boost.Python, though the
12511854Sbrandon.potter@amd.com    underlying implementation is very different.
12611854Sbrandon.potter@amd.com
12711854Sbrandon.potter@amd.compybind11 is a header-only-library, hence it is not necessary to link against
12811854Sbrandon.potter@amd.comany special libraries (other than Python itself). On Windows, use the CMake
12911854Sbrandon.potter@amd.combuild file discussed in section :ref:`cmake`. On Linux and Mac OS, the above
13011854Sbrandon.potter@amd.comexample can be compiled using the following command
13111854Sbrandon.potter@amd.com
13211886Sbrandon.potter@amd.com.. code-block:: bash
13311886Sbrandon.potter@amd.com
13411886Sbrandon.potter@amd.com    $ c++ -O3 -shared -std=c++11 -I <path-to-pybind11>/include `python-config --cflags --ldflags` example.cpp -o example.so
13511886Sbrandon.potter@amd.com
13611886Sbrandon.potter@amd.comIn general, it is advisable to include several additional build parameters
13711886Sbrandon.potter@amd.comthat can considerably reduce the size of the created binary. Refer to section
13811886Sbrandon.potter@amd.com:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
13911854Sbrandon.potter@amd.combuild system.
14011854Sbrandon.potter@amd.com
14111854Sbrandon.potter@amd.comAssuming that the created file :file:`example.so` (:file:`example.pyd` on Windows)
14211854Sbrandon.potter@amd.comis located in the current directory, the following interactive Python session
14311854Sbrandon.potter@amd.comshows how to load and execute the example.
1449110Ssteve.reinhardt@amd.com
14510558Salexandru.dutu@amd.com.. code-block:: pycon
1469110Ssteve.reinhardt@amd.com
14710558Salexandru.dutu@amd.com    $ python
14810558Salexandru.dutu@amd.com    Python 2.7.10 (default, Aug 22 2015, 20:33:39)
1499110Ssteve.reinhardt@amd.com    [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
1509110Ssteve.reinhardt@amd.com    Type "help", "copyright", "credits" or "license" for more information.
1519110Ssteve.reinhardt@amd.com    >>> import example
1529110Ssteve.reinhardt@amd.com    >>> example.add(1, 2)
15310558Salexandru.dutu@amd.com    3L
1549110Ssteve.reinhardt@amd.com    >>>
1559110Ssteve.reinhardt@amd.com
1569110Ssteve.reinhardt@amd.com.. _keyword_args:
15710558Salexandru.dutu@amd.com
1589110Ssteve.reinhardt@amd.comKeyword arguments
15911886Sbrandon.potter@amd.com=================
16011886Sbrandon.potter@amd.com
16111886Sbrandon.potter@amd.comWith a simple modification code, it is possible to inform Python about the
16212141Sspwilson2@wisc.edunames of the arguments ("i" and "j" in this case).
16313557Sgabeblack@google.com
16411886Sbrandon.potter@amd.com.. code-block:: cpp
16511854Sbrandon.potter@amd.com
16611854Sbrandon.potter@amd.com    m.def("add", &add, "A function which adds two numbers",
16711854Sbrandon.potter@amd.com          py::arg("i"), py::arg("j"));
16811854Sbrandon.potter@amd.com
16911854Sbrandon.potter@amd.com:class:`arg` is one of several special tag classes which can be used to pass
17011854Sbrandon.potter@amd.commetadata into :func:`module::def`. With this modified binding code, we can now
17111886Sbrandon.potter@amd.comcall the function using keyword arguments, which is a more readable alternative
17211854Sbrandon.potter@amd.comparticularly for functions taking many parameters:
17313867Salexandru.dutu@amd.com
17413867Salexandru.dutu@amd.com.. code-block:: pycon
17513867Salexandru.dutu@amd.com
17613867Salexandru.dutu@amd.com    >>> import example
17713867Salexandru.dutu@amd.com    >>> example.add(i=1, j=2)
17813867Salexandru.dutu@amd.com    3L
17911854Sbrandon.potter@amd.com
18012448Sgabeblack@google.comThe keyword names also appear in the function signatures within the documentation.
18111854Sbrandon.potter@amd.com
18211854Sbrandon.potter@amd.com.. code-block:: pycon
18311854Sbrandon.potter@amd.com
18411851Sbrandon.potter@amd.com    >>> help(example)
18511851Sbrandon.potter@amd.com
18611851Sbrandon.potter@amd.com    ....
18711851Sbrandon.potter@amd.com
18811851Sbrandon.potter@amd.com    FUNCTIONS
18913883Sdavid.hashe@amd.com        add(...)
19013883Sdavid.hashe@amd.com            Signature : (i: int, j: int) -> int
19113883Sdavid.hashe@amd.com
19213883Sdavid.hashe@amd.com            A function which adds two numbers
19313883Sdavid.hashe@amd.com
19413883Sdavid.hashe@amd.comA shorter notation for named arguments is also available:
19513883Sdavid.hashe@amd.com
19613883Sdavid.hashe@amd.com.. code-block:: cpp
19713883Sdavid.hashe@amd.com
19813883Sdavid.hashe@amd.com    // regular notation
19913883Sdavid.hashe@amd.com    m.def("add1", &add, py::arg("i"), py::arg("j"));
20013883Sdavid.hashe@amd.com    // shorthand
20113883Sdavid.hashe@amd.com    using namespace pybind11::literals;
20213883Sdavid.hashe@amd.com    m.def("add2", &add, "i"_a, "j"_a);
20313883Sdavid.hashe@amd.com
20413883Sdavid.hashe@amd.comThe :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
20513883Sdavid.hashe@amd.comNote that the literal operator must first be made visible with the directive
20613883Sdavid.hashe@amd.com``using namespace pybind11::literals``. This does not bring in anything else
20713883Sdavid.hashe@amd.comfrom the ``pybind11`` namespace except for literals.
20813883Sdavid.hashe@amd.com
20913883Sdavid.hashe@amd.com.. _default_args:
21013883Sdavid.hashe@amd.com
21113883Sdavid.hashe@amd.comDefault arguments
21213883Sdavid.hashe@amd.com=================
21313883Sdavid.hashe@amd.com
21413883Sdavid.hashe@amd.comSuppose now that the function to be bound has default arguments, e.g.:
21513883Sdavid.hashe@amd.com
21613883Sdavid.hashe@amd.com.. code-block:: cpp
21713883Sdavid.hashe@amd.com
21813883Sdavid.hashe@amd.com    int add(int i = 1, int j = 2) {
21913883Sdavid.hashe@amd.com        return i + j;
22013883Sdavid.hashe@amd.com    }
22113883Sdavid.hashe@amd.com
22213883Sdavid.hashe@amd.comUnfortunately, pybind11 cannot automatically extract these parameters, since they
22313883Sdavid.hashe@amd.comare not part of the function's type information. However, they are simple to specify
22413883Sdavid.hashe@amd.comusing an extension of :class:`arg`:
22513883Sdavid.hashe@amd.com
22613883Sdavid.hashe@amd.com.. code-block:: cpp
22711801Sbrandon.potter@amd.com
22811801Sbrandon.potter@amd.com    m.def("add", &add, "A function which adds two numbers",
22911801Sbrandon.potter@amd.com          py::arg("i") = 1, py::arg("j") = 2);
23011801Sbrandon.potter@amd.com
23111801Sbrandon.potter@amd.comThe default values also appear within the documentation.
23211801Sbrandon.potter@amd.com
23311801Sbrandon.potter@amd.com.. code-block:: pycon
23411801Sbrandon.potter@amd.com
23511801Sbrandon.potter@amd.com    >>> help(example)
23611885Sbrandon.potter@amd.com
23711885Sbrandon.potter@amd.com    ....
23811801Sbrandon.potter@amd.com
23910496Ssteve.reinhardt@amd.com    FUNCTIONS
24010496Ssteve.reinhardt@amd.com        add(...)
24111856Sbrandon.potter@amd.com            Signature : (i: int = 1, j: int = 2) -> int
24211856Sbrandon.potter@amd.com
24311886Sbrandon.potter@amd.com            A function which adds two numbers
24411886Sbrandon.potter@amd.com
24511905SBrandon.Potter@amd.comThe shorthand notation is also available for default arguments:
24611886Sbrandon.potter@amd.com
24711886Sbrandon.potter@amd.com.. code-block:: cpp
24811886Sbrandon.potter@amd.com
24911886Sbrandon.potter@amd.com    // regular notation
25011886Sbrandon.potter@amd.com    m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
25111886Sbrandon.potter@amd.com    // shorthand
25211886Sbrandon.potter@amd.com    m.def("add2", &add, "i"_a=1, "j"_a=2);
25311886Sbrandon.potter@amd.com
25411886Sbrandon.potter@amd.comExporting variables
2552SN/A===================
2562SN/A
257360SN/ATo 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