Back to home page

EIC code displayed by LXR

 
 

    


Warning, /jana2/src/python/externals/pybind11-2.10.3/docs/advanced/pycpp/object.rst is written in an unsupported language. File is not indexed.

0001 Python types
0002 ############
0003 
0004 .. _wrappers:
0005 
0006 Available wrappers
0007 ==================
0008 
0009 All major Python types are available as thin C++ wrapper classes. These
0010 can also be used as function parameters -- see :ref:`python_objects_as_args`.
0011 
0012 Available types include :class:`handle`, :class:`object`, :class:`bool_`,
0013 :class:`int_`, :class:`float_`, :class:`str`, :class:`bytes`, :class:`tuple`,
0014 :class:`list`, :class:`dict`, :class:`slice`, :class:`none`, :class:`capsule`,
0015 :class:`iterable`, :class:`iterator`, :class:`function`, :class:`buffer`,
0016 :class:`array`, and :class:`array_t`.
0017 
0018 .. warning::
0019 
0020     Be sure to review the :ref:`pytypes_gotchas` before using this heavily in
0021     your C++ API.
0022 
0023 .. _instantiating_compound_types:
0024 
0025 Instantiating compound Python types from C++
0026 ============================================
0027 
0028 Dictionaries can be initialized in the :class:`dict` constructor:
0029 
0030 .. code-block:: cpp
0031 
0032     using namespace pybind11::literals; // to bring in the `_a` literal
0033     py::dict d("spam"_a=py::none(), "eggs"_a=42);
0034 
0035 A tuple of python objects can be instantiated using :func:`py::make_tuple`:
0036 
0037 .. code-block:: cpp
0038 
0039     py::tuple tup = py::make_tuple(42, py::none(), "spam");
0040 
0041 Each element is converted to a supported Python type.
0042 
0043 A `simple namespace`_ can be instantiated using
0044 
0045 .. code-block:: cpp
0046 
0047     using namespace pybind11::literals;  // to bring in the `_a` literal
0048     py::object SimpleNamespace = py::module_::import("types").attr("SimpleNamespace");
0049     py::object ns = SimpleNamespace("spam"_a=py::none(), "eggs"_a=42);
0050 
0051 Attributes on a namespace can be modified with the :func:`py::delattr`,
0052 :func:`py::getattr`, and :func:`py::setattr` functions. Simple namespaces can
0053 be useful as lightweight stand-ins for class instances.
0054 
0055 .. _simple namespace: https://docs.python.org/3/library/types.html#types.SimpleNamespace
0056 
0057 .. _casting_back_and_forth:
0058 
0059 Casting back and forth
0060 ======================
0061 
0062 In this kind of mixed code, it is often necessary to convert arbitrary C++
0063 types to Python, which can be done using :func:`py::cast`:
0064 
0065 .. code-block:: cpp
0066 
0067     MyClass *cls = ...;
0068     py::object obj = py::cast(cls);
0069 
0070 The reverse direction uses the following syntax:
0071 
0072 .. code-block:: cpp
0073 
0074     py::object obj = ...;
0075     MyClass *cls = obj.cast<MyClass *>();
0076 
0077 When conversion fails, both directions throw the exception :class:`cast_error`.
0078 
0079 .. _python_libs:
0080 
0081 Accessing Python libraries from C++
0082 ===================================
0083 
0084 It is also possible to import objects defined in the Python standard
0085 library or available in the current Python environment (``sys.path``) and work
0086 with these in C++.
0087 
0088 This example obtains a reference to the Python ``Decimal`` class.
0089 
0090 .. code-block:: cpp
0091 
0092     // Equivalent to "from decimal import Decimal"
0093     py::object Decimal = py::module_::import("decimal").attr("Decimal");
0094 
0095 .. code-block:: cpp
0096 
0097     // Try to import scipy
0098     py::object scipy = py::module_::import("scipy");
0099     return scipy.attr("__version__");
0100 
0101 
0102 .. _calling_python_functions:
0103 
0104 Calling Python functions
0105 ========================
0106 
0107 It is also possible to call Python classes, functions and methods
0108 via ``operator()``.
0109 
0110 .. code-block:: cpp
0111 
0112     // Construct a Python object of class Decimal
0113     py::object pi = Decimal("3.14159");
0114 
0115 .. code-block:: cpp
0116 
0117     // Use Python to make our directories
0118     py::object os = py::module_::import("os");
0119     py::object makedirs = os.attr("makedirs");
0120     makedirs("/tmp/path/to/somewhere");
0121 
0122 One can convert the result obtained from Python to a pure C++ version
0123 if a ``py::class_`` or type conversion is defined.
0124 
0125 .. code-block:: cpp
0126 
0127     py::function f = <...>;
0128     py::object result_py = f(1234, "hello", some_instance);
0129     MyClass &result = result_py.cast<MyClass>();
0130 
0131 .. _calling_python_methods:
0132 
0133 Calling Python methods
0134 ========================
0135 
0136 To call an object's method, one can again use ``.attr`` to obtain access to the
0137 Python method.
0138 
0139 .. code-block:: cpp
0140 
0141     // Calculate e^π in decimal
0142     py::object exp_pi = pi.attr("exp")();
0143     py::print(py::str(exp_pi));
0144 
0145 In the example above ``pi.attr("exp")`` is a *bound method*: it will always call
0146 the method for that same instance of the class. Alternately one can create an
0147 *unbound method* via the Python class (instead of instance) and pass the ``self``
0148 object explicitly, followed by other arguments.
0149 
0150 .. code-block:: cpp
0151 
0152     py::object decimal_exp = Decimal.attr("exp");
0153 
0154     // Compute the e^n for n=0..4
0155     for (int n = 0; n < 5; n++) {
0156         py::print(decimal_exp(Decimal(n));
0157     }
0158 
0159 Keyword arguments
0160 =================
0161 
0162 Keyword arguments are also supported. In Python, there is the usual call syntax:
0163 
0164 .. code-block:: python
0165 
0166     def f(number, say, to):
0167         ...  # function code
0168 
0169 
0170     f(1234, say="hello", to=some_instance)  # keyword call in Python
0171 
0172 In C++, the same call can be made using:
0173 
0174 .. code-block:: cpp
0175 
0176     using namespace pybind11::literals; // to bring in the `_a` literal
0177     f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
0178 
0179 Unpacking arguments
0180 ===================
0181 
0182 Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with
0183 other arguments:
0184 
0185 .. code-block:: cpp
0186 
0187     // * unpacking
0188     py::tuple args = py::make_tuple(1234, "hello", some_instance);
0189     f(*args);
0190 
0191     // ** unpacking
0192     py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance);
0193     f(**kwargs);
0194 
0195     // mixed keywords, * and ** unpacking
0196     py::tuple args = py::make_tuple(1234);
0197     py::dict kwargs = py::dict("to"_a=some_instance);
0198     f(*args, "say"_a="hello", **kwargs);
0199 
0200 Generalized unpacking according to PEP448_ is also supported:
0201 
0202 .. code-block:: cpp
0203 
0204     py::dict kwargs1 = py::dict("number"_a=1234);
0205     py::dict kwargs2 = py::dict("to"_a=some_instance);
0206     f(**kwargs1, "say"_a="hello", **kwargs2);
0207 
0208 .. seealso::
0209 
0210     The file :file:`tests/test_pytypes.cpp` contains a complete
0211     example that demonstrates passing native Python types in more detail. The
0212     file :file:`tests/test_callbacks.cpp` presents a few examples of calling
0213     Python functions from C++, including keywords arguments and unpacking.
0214 
0215 .. _PEP448: https://www.python.org/dev/peps/pep-0448/
0216 
0217 .. _implicit_casting:
0218 
0219 Implicit casting
0220 ================
0221 
0222 When using the C++ interface for Python types, or calling Python functions,
0223 objects of type :class:`object` are returned. It is possible to invoke implicit
0224 conversions to subclasses like :class:`dict`. The same holds for the proxy objects
0225 returned by ``operator[]`` or ``obj.attr()``.
0226 Casting to subtypes improves code readability and allows values to be passed to
0227 C++ functions that require a specific subtype rather than a generic :class:`object`.
0228 
0229 .. code-block:: cpp
0230 
0231     #include <pybind11/numpy.h>
0232     using namespace pybind11::literals;
0233 
0234     py::module_ os = py::module_::import("os");
0235     py::module_ path = py::module_::import("os.path");  // like 'import os.path as path'
0236     py::module_ np = py::module_::import("numpy");  // like 'import numpy as np'
0237 
0238     py::str curdir_abs = path.attr("abspath")(path.attr("curdir"));
0239     py::print(py::str("Current directory: ") + curdir_abs);
0240     py::dict environ = os.attr("environ");
0241     py::print(environ["HOME"]);
0242     py::array_t<float> arr = np.attr("ones")(3, "dtype"_a="float32");
0243     py::print(py::repr(arr + py::int_(1)));
0244 
0245 These implicit conversions are available for subclasses of :class:`object`; there
0246 is no need to call ``obj.cast()`` explicitly as for custom classes, see
0247 :ref:`casting_back_and_forth`.
0248 
0249 .. note::
0250     If a trivial conversion via move constructor is not possible, both implicit and
0251     explicit casting (calling ``obj.cast()``) will attempt a "rich" conversion.
0252     For instance, ``py::list env = os.attr("environ");`` will succeed and is
0253     equivalent to the Python code ``env = list(os.environ)`` that produces a
0254     list of the dict keys.
0255 
0256 ..  TODO: Adapt text once PR #2349 has landed
0257 
0258 Handling exceptions
0259 ===================
0260 
0261 Python exceptions from wrapper classes will be thrown as a ``py::error_already_set``.
0262 See :ref:`Handling exceptions from Python in C++
0263 <handling_python_exceptions_cpp>` for more information on handling exceptions
0264 raised when calling C++ wrapper classes.
0265 
0266 .. _pytypes_gotchas:
0267 
0268 Gotchas
0269 =======
0270 
0271 Default-Constructed Wrappers
0272 ----------------------------
0273 
0274 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
0275 ``PyObject*`` null pointer. To check for this, use
0276 ``static_cast<bool>(my_wrapper)``.
0277 
0278 Assigning py::none() to wrappers
0279 --------------------------------
0280 
0281 You may be tempted to use types like ``py::str`` and ``py::dict`` in C++
0282 signatures (either pure C++, or in bound signatures), and assign them default
0283 values of ``py::none()``. However, in a best case scenario, it will fail fast
0284 because ``None`` is not convertible to that type (e.g. ``py::dict``), or in a
0285 worse case scenario, it will silently work but corrupt the types you want to
0286 work with (e.g. ``py::str(py::none())`` will yield ``"None"`` in Python).