github.com/kaydxh/golang@v0.0.131/pkg/gocv/cgo/third_path/pybind11/docs/advanced/pycpp/object.rst (about) 1 Python types 2 ############ 3 4 .. _wrappers: 5 6 Available wrappers 7 ================== 8 9 All major Python types are available as thin C++ wrapper classes. These 10 can also be used as function parameters -- see :ref:`python_objects_as_args`. 11 12 Available types include :class:`handle`, :class:`object`, :class:`bool_`, 13 :class:`int_`, :class:`float_`, :class:`str`, :class:`bytes`, :class:`tuple`, 14 :class:`list`, :class:`dict`, :class:`slice`, :class:`none`, :class:`capsule`, 15 :class:`iterable`, :class:`iterator`, :class:`function`, :class:`buffer`, 16 :class:`array`, and :class:`array_t`. 17 18 .. warning:: 19 20 Be sure to review the :ref:`pytypes_gotchas` before using this heavily in 21 your C++ API. 22 23 .. _instantiating_compound_types: 24 25 Instantiating compound Python types from C++ 26 ============================================ 27 28 Dictionaries can be initialized in the :class:`dict` constructor: 29 30 .. code-block:: cpp 31 32 using namespace pybind11::literals; // to bring in the `_a` literal 33 py::dict d("spam"_a=py::none(), "eggs"_a=42); 34 35 A tuple of python objects can be instantiated using :func:`py::make_tuple`: 36 37 .. code-block:: cpp 38 39 py::tuple tup = py::make_tuple(42, py::none(), "spam"); 40 41 Each element is converted to a supported Python type. 42 43 A `simple namespace`_ can be instantiated using 44 45 .. code-block:: cpp 46 47 using namespace pybind11::literals; // to bring in the `_a` literal 48 py::object SimpleNamespace = py::module_::import("types").attr("SimpleNamespace"); 49 py::object ns = SimpleNamespace("spam"_a=py::none(), "eggs"_a=42); 50 51 Attributes on a namespace can be modified with the :func:`py::delattr`, 52 :func:`py::getattr`, and :func:`py::setattr` functions. Simple namespaces can 53 be useful as lightweight stand-ins for class instances. 54 55 .. _simple namespace: https://docs.python.org/3/library/types.html#types.SimpleNamespace 56 57 .. _casting_back_and_forth: 58 59 Casting back and forth 60 ====================== 61 62 In this kind of mixed code, it is often necessary to convert arbitrary C++ 63 types to Python, which can be done using :func:`py::cast`: 64 65 .. code-block:: cpp 66 67 MyClass *cls = ...; 68 py::object obj = py::cast(cls); 69 70 The reverse direction uses the following syntax: 71 72 .. code-block:: cpp 73 74 py::object obj = ...; 75 MyClass *cls = obj.cast<MyClass *>(); 76 77 When conversion fails, both directions throw the exception :class:`cast_error`. 78 79 .. _python_libs: 80 81 Accessing Python libraries from C++ 82 =================================== 83 84 It is also possible to import objects defined in the Python standard 85 library or available in the current Python environment (``sys.path``) and work 86 with these in C++. 87 88 This example obtains a reference to the Python ``Decimal`` class. 89 90 .. code-block:: cpp 91 92 // Equivalent to "from decimal import Decimal" 93 py::object Decimal = py::module_::import("decimal").attr("Decimal"); 94 95 .. code-block:: cpp 96 97 // Try to import scipy 98 py::object scipy = py::module_::import("scipy"); 99 return scipy.attr("__version__"); 100 101 102 .. _calling_python_functions: 103 104 Calling Python functions 105 ======================== 106 107 It is also possible to call Python classes, functions and methods 108 via ``operator()``. 109 110 .. code-block:: cpp 111 112 // Construct a Python object of class Decimal 113 py::object pi = Decimal("3.14159"); 114 115 .. code-block:: cpp 116 117 // Use Python to make our directories 118 py::object os = py::module_::import("os"); 119 py::object makedirs = os.attr("makedirs"); 120 makedirs("/tmp/path/to/somewhere"); 121 122 One can convert the result obtained from Python to a pure C++ version 123 if a ``py::class_`` or type conversion is defined. 124 125 .. code-block:: cpp 126 127 py::function f = <...>; 128 py::object result_py = f(1234, "hello", some_instance); 129 MyClass &result = result_py.cast<MyClass>(); 130 131 .. _calling_python_methods: 132 133 Calling Python methods 134 ======================== 135 136 To call an object's method, one can again use ``.attr`` to obtain access to the 137 Python method. 138 139 .. code-block:: cpp 140 141 // Calculate e^π in decimal 142 py::object exp_pi = pi.attr("exp")(); 143 py::print(py::str(exp_pi)); 144 145 In the example above ``pi.attr("exp")`` is a *bound method*: it will always call 146 the method for that same instance of the class. Alternately one can create an 147 *unbound method* via the Python class (instead of instance) and pass the ``self`` 148 object explicitly, followed by other arguments. 149 150 .. code-block:: cpp 151 152 py::object decimal_exp = Decimal.attr("exp"); 153 154 // Compute the e^n for n=0..4 155 for (int n = 0; n < 5; n++) { 156 py::print(decimal_exp(Decimal(n)); 157 } 158 159 Keyword arguments 160 ================= 161 162 Keyword arguments are also supported. In Python, there is the usual call syntax: 163 164 .. code-block:: python 165 166 def f(number, say, to): 167 ... # function code 168 169 170 f(1234, say="hello", to=some_instance) # keyword call in Python 171 172 In C++, the same call can be made using: 173 174 .. code-block:: cpp 175 176 using namespace pybind11::literals; // to bring in the `_a` literal 177 f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++ 178 179 Unpacking arguments 180 =================== 181 182 Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with 183 other arguments: 184 185 .. code-block:: cpp 186 187 // * unpacking 188 py::tuple args = py::make_tuple(1234, "hello", some_instance); 189 f(*args); 190 191 // ** unpacking 192 py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance); 193 f(**kwargs); 194 195 // mixed keywords, * and ** unpacking 196 py::tuple args = py::make_tuple(1234); 197 py::dict kwargs = py::dict("to"_a=some_instance); 198 f(*args, "say"_a="hello", **kwargs); 199 200 Generalized unpacking according to PEP448_ is also supported: 201 202 .. code-block:: cpp 203 204 py::dict kwargs1 = py::dict("number"_a=1234); 205 py::dict kwargs2 = py::dict("to"_a=some_instance); 206 f(**kwargs1, "say"_a="hello", **kwargs2); 207 208 .. seealso:: 209 210 The file :file:`tests/test_pytypes.cpp` contains a complete 211 example that demonstrates passing native Python types in more detail. The 212 file :file:`tests/test_callbacks.cpp` presents a few examples of calling 213 Python functions from C++, including keywords arguments and unpacking. 214 215 .. _PEP448: https://www.python.org/dev/peps/pep-0448/ 216 217 .. _implicit_casting: 218 219 Implicit casting 220 ================ 221 222 When using the C++ interface for Python types, or calling Python functions, 223 objects of type :class:`object` are returned. It is possible to invoke implicit 224 conversions to subclasses like :class:`dict`. The same holds for the proxy objects 225 returned by ``operator[]`` or ``obj.attr()``. 226 Casting to subtypes improves code readability and allows values to be passed to 227 C++ functions that require a specific subtype rather than a generic :class:`object`. 228 229 .. code-block:: cpp 230 231 #include <pybind11/numpy.h> 232 using namespace pybind11::literals; 233 234 py::module_ os = py::module_::import("os"); 235 py::module_ path = py::module_::import("os.path"); // like 'import os.path as path' 236 py::module_ np = py::module_::import("numpy"); // like 'import numpy as np' 237 238 py::str curdir_abs = path.attr("abspath")(path.attr("curdir")); 239 py::print(py::str("Current directory: ") + curdir_abs); 240 py::dict environ = os.attr("environ"); 241 py::print(environ["HOME"]); 242 py::array_t<float> arr = np.attr("ones")(3, "dtype"_a="float32"); 243 py::print(py::repr(arr + py::int_(1))); 244 245 These implicit conversions are available for subclasses of :class:`object`; there 246 is no need to call ``obj.cast()`` explicitly as for custom classes, see 247 :ref:`casting_back_and_forth`. 248 249 .. note:: 250 If a trivial conversion via move constructor is not possible, both implicit and 251 explicit casting (calling ``obj.cast()``) will attempt a "rich" conversion. 252 For instance, ``py::list env = os.attr("environ");`` will succeed and is 253 equivalent to the Python code ``env = list(os.environ)`` that produces a 254 list of the dict keys. 255 256 .. TODO: Adapt text once PR #2349 has landed 257 258 Handling exceptions 259 =================== 260 261 Python exceptions from wrapper classes will be thrown as a ``py::error_already_set``. 262 See :ref:`Handling exceptions from Python in C++ 263 <handling_python_exceptions_cpp>` for more information on handling exceptions 264 raised when calling C++ wrapper classes. 265 266 .. _pytypes_gotchas: 267 268 Gotchas 269 ======= 270 271 Default-Constructed Wrappers 272 ---------------------------- 273 274 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 275 ``PyObject*`` null pointer. To check for this, use 276 ``static_cast<bool>(my_wrapper)``. 277 278 Assigning py::none() to wrappers 279 -------------------------------- 280 281 You may be tempted to use types like ``py::str`` and ``py::dict`` in C++ 282 signatures (either pure C++, or in bound signatures), and assign them default 283 values of ``py::none()``. However, in a best case scenario, it will fail fast 284 because ``None`` is not convertible to that type (e.g. ``py::dict``), or in a 285 worse case scenario, it will silently work but corrupt the types you want to 286 work with (e.g. ``py::str(py::none())`` will yield ``"None"`` in Python).