object.rst 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. Python types
  2. ############
  3. .. _wrappers:
  4. Available wrappers
  5. ==================
  6. All major Python types are available as thin C++ wrapper classes. These
  7. can also be used as function parameters -- see :ref:`python_objects_as_args`.
  8. Available types include :class:`handle`, :class:`object`, :class:`bool_`,
  9. :class:`int_`, :class:`float_`, :class:`str`, :class:`bytes`, :class:`tuple`,
  10. :class:`list`, :class:`dict`, :class:`slice`, :class:`none`, :class:`capsule`,
  11. :class:`iterable`, :class:`iterator`, :class:`function`, :class:`buffer`,
  12. :class:`array`, and :class:`array_t`.
  13. .. warning::
  14. Be sure to review the :ref:`pytypes_gotchas` before using this heavily in
  15. your C++ API.
  16. .. _casting_back_and_forth:
  17. Casting back and forth
  18. ======================
  19. In this kind of mixed code, it is often necessary to convert arbitrary C++
  20. types to Python, which can be done using :func:`py::cast`:
  21. .. code-block:: cpp
  22. MyClass *cls = ..;
  23. py::object obj = py::cast(cls);
  24. The reverse direction uses the following syntax:
  25. .. code-block:: cpp
  26. py::object obj = ...;
  27. MyClass *cls = obj.cast<MyClass *>();
  28. When conversion fails, both directions throw the exception :class:`cast_error`.
  29. .. _python_libs:
  30. Accessing Python libraries from C++
  31. ===================================
  32. It is also possible to import objects defined in the Python standard
  33. library or available in the current Python environment (``sys.path``) and work
  34. with these in C++.
  35. This example obtains a reference to the Python ``Decimal`` class.
  36. .. code-block:: cpp
  37. // Equivalent to "from decimal import Decimal"
  38. py::object Decimal = py::module_::import("decimal").attr("Decimal");
  39. .. code-block:: cpp
  40. // Try to import scipy
  41. py::object scipy = py::module_::import("scipy");
  42. return scipy.attr("__version__");
  43. .. _calling_python_functions:
  44. Calling Python functions
  45. ========================
  46. It is also possible to call Python classes, functions and methods
  47. via ``operator()``.
  48. .. code-block:: cpp
  49. // Construct a Python object of class Decimal
  50. py::object pi = Decimal("3.14159");
  51. .. code-block:: cpp
  52. // Use Python to make our directories
  53. py::object os = py::module_::import("os");
  54. py::object makedirs = os.attr("makedirs");
  55. makedirs("/tmp/path/to/somewhere");
  56. One can convert the result obtained from Python to a pure C++ version
  57. if a ``py::class_`` or type conversion is defined.
  58. .. code-block:: cpp
  59. py::function f = <...>;
  60. py::object result_py = f(1234, "hello", some_instance);
  61. MyClass &result = result_py.cast<MyClass>();
  62. .. _calling_python_methods:
  63. Calling Python methods
  64. ========================
  65. To call an object's method, one can again use ``.attr`` to obtain access to the
  66. Python method.
  67. .. code-block:: cpp
  68. // Calculate e^π in decimal
  69. py::object exp_pi = pi.attr("exp")();
  70. py::print(py::str(exp_pi));
  71. In the example above ``pi.attr("exp")`` is a *bound method*: it will always call
  72. the method for that same instance of the class. Alternately one can create an
  73. *unbound method* via the Python class (instead of instance) and pass the ``self``
  74. object explicitly, followed by other arguments.
  75. .. code-block:: cpp
  76. py::object decimal_exp = Decimal.attr("exp");
  77. // Compute the e^n for n=0..4
  78. for (int n = 0; n < 5; n++) {
  79. py::print(decimal_exp(Decimal(n));
  80. }
  81. Keyword arguments
  82. =================
  83. Keyword arguments are also supported. In Python, there is the usual call syntax:
  84. .. code-block:: python
  85. def f(number, say, to):
  86. ... # function code
  87. f(1234, say="hello", to=some_instance) # keyword call in Python
  88. In C++, the same call can be made using:
  89. .. code-block:: cpp
  90. using namespace pybind11::literals; // to bring in the `_a` literal
  91. f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
  92. Unpacking arguments
  93. ===================
  94. Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with
  95. other arguments:
  96. .. code-block:: cpp
  97. // * unpacking
  98. py::tuple args = py::make_tuple(1234, "hello", some_instance);
  99. f(*args);
  100. // ** unpacking
  101. py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance);
  102. f(**kwargs);
  103. // mixed keywords, * and ** unpacking
  104. py::tuple args = py::make_tuple(1234);
  105. py::dict kwargs = py::dict("to"_a=some_instance);
  106. f(*args, "say"_a="hello", **kwargs);
  107. Generalized unpacking according to PEP448_ is also supported:
  108. .. code-block:: cpp
  109. py::dict kwargs1 = py::dict("number"_a=1234);
  110. py::dict kwargs2 = py::dict("to"_a=some_instance);
  111. f(**kwargs1, "say"_a="hello", **kwargs2);
  112. .. seealso::
  113. The file :file:`tests/test_pytypes.cpp` contains a complete
  114. example that demonstrates passing native Python types in more detail. The
  115. file :file:`tests/test_callbacks.cpp` presents a few examples of calling
  116. Python functions from C++, including keywords arguments and unpacking.
  117. .. _PEP448: https://www.python.org/dev/peps/pep-0448/
  118. .. _implicit_casting:
  119. Implicit casting
  120. ================
  121. When using the C++ interface for Python types, or calling Python functions,
  122. objects of type :class:`object` are returned. It is possible to invoke implicit
  123. conversions to subclasses like :class:`dict`. The same holds for the proxy objects
  124. returned by ``operator[]`` or ``obj.attr()``.
  125. Casting to subtypes improves code readability and allows values to be passed to
  126. C++ functions that require a specific subtype rather than a generic :class:`object`.
  127. .. code-block:: cpp
  128. #include <pybind11/numpy.h>
  129. using namespace pybind11::literals;
  130. py::module_ os = py::module_::import("os");
  131. py::module_ path = py::module_::import("os.path"); // like 'import os.path as path'
  132. py::module_ np = py::module_::import("numpy"); // like 'import numpy as np'
  133. py::str curdir_abs = path.attr("abspath")(path.attr("curdir"));
  134. py::print(py::str("Current directory: ") + curdir_abs);
  135. py::dict environ = os.attr("environ");
  136. py::print(environ["HOME"]);
  137. py::array_t<float> arr = np.attr("ones")(3, "dtype"_a="float32");
  138. py::print(py::repr(arr + py::int_(1)));
  139. These implicit conversions are available for subclasses of :class:`object`; there
  140. is no need to call ``obj.cast()`` explicitly as for custom classes, see
  141. :ref:`casting_back_and_forth`.
  142. .. note::
  143. If a trivial conversion via move constructor is not possible, both implicit and
  144. explicit casting (calling ``obj.cast()``) will attempt a "rich" conversion.
  145. For instance, ``py::list env = os.attr("environ");`` will succeed and is
  146. equivalent to the Python code ``env = list(os.environ)`` that produces a
  147. list of the dict keys.
  148. .. TODO: Adapt text once PR #2349 has landed
  149. Handling exceptions
  150. ===================
  151. Python exceptions from wrapper classes will be thrown as a ``py::error_already_set``.
  152. See :ref:`Handling exceptions from Python in C++
  153. <handling_python_exceptions_cpp>` for more information on handling exceptions
  154. raised when calling C++ wrapper classes.
  155. .. _pytypes_gotchas:
  156. Gotchas
  157. =======
  158. Default-Constructed Wrappers
  159. ----------------------------
  160. When a wrapper type is default-constructed, it is **not** a valid Python object (i.e. it is not ``py::none()``). It is simply the same as
  161. ``PyObject*`` null pointer. To check for this, use
  162. ``static_cast<bool>(my_wrapper)``.
  163. Assigning py::none() to wrappers
  164. --------------------------------
  165. You may be tempted to use types like ``py::str`` and ``py::dict`` in C++
  166. signatures (either pure C++, or in bound signatures), and assign them default
  167. values of ``py::none()``. However, in a best case scenario, it will fail fast
  168. because ``None`` is not convertible to that type (e.g. ``py::dict``), or in a
  169. worse case scenario, it will silently work but corrupt the types you want to
  170. work with (e.g. ``py::str(py::none())`` will yield ``"None"`` in Python).