1 | /* |
2 | pybind11/pytypes.h: Convenience wrapper classes for basic Python types |
3 | |
4 | Copyright (c) 2016 Wenzel Jakob <[email protected]> |
5 | |
6 | All rights reserved. Use of this source code is governed by a |
7 | BSD-style license that can be found in the LICENSE file. |
8 | */ |
9 | |
10 | #pragma once |
11 | |
12 | #include "detail/common.h" |
13 | #include "buffer_info.h" |
14 | |
15 | #include <assert.h> |
16 | #include <cstddef> |
17 | #include <exception> |
18 | #include <frameobject.h> |
19 | #include <iterator> |
20 | #include <memory> |
21 | #include <string> |
22 | #include <type_traits> |
23 | #include <typeinfo> |
24 | #include <utility> |
25 | |
26 | #if defined(PYBIND11_HAS_OPTIONAL) |
27 | # include <optional> |
28 | #endif |
29 | |
30 | #ifdef PYBIND11_HAS_STRING_VIEW |
31 | # include <string_view> |
32 | #endif |
33 | |
34 | PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) |
35 | |
36 | /* A few forward declarations */ |
37 | class handle; |
38 | class object; |
39 | class str; |
40 | class iterator; |
41 | class type; |
42 | struct arg; |
43 | struct arg_v; |
44 | |
45 | PYBIND11_NAMESPACE_BEGIN(detail) |
46 | class args_proxy; |
47 | bool isinstance_generic(handle obj, const std::type_info &tp); |
48 | |
49 | // Accessor forward declarations |
50 | template <typename Policy> |
51 | class accessor; |
52 | namespace accessor_policies { |
53 | struct obj_attr; |
54 | struct str_attr; |
55 | struct generic_item; |
56 | struct sequence_item; |
57 | struct list_item; |
58 | struct tuple_item; |
59 | } // namespace accessor_policies |
60 | using obj_attr_accessor = accessor<accessor_policies::obj_attr>; |
61 | using str_attr_accessor = accessor<accessor_policies::str_attr>; |
62 | using item_accessor = accessor<accessor_policies::generic_item>; |
63 | using sequence_accessor = accessor<accessor_policies::sequence_item>; |
64 | using list_accessor = accessor<accessor_policies::list_item>; |
65 | using tuple_accessor = accessor<accessor_policies::tuple_item>; |
66 | |
67 | /// Tag and check to identify a class which implements the Python object API |
68 | class pyobject_tag {}; |
69 | template <typename T> |
70 | using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>; |
71 | |
72 | /** \rst |
73 | A mixin class which adds common functions to `handle`, `object` and various accessors. |
74 | The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``. |
75 | \endrst */ |
76 | template <typename Derived> |
77 | class object_api : public pyobject_tag { |
78 | const Derived &derived() const { return static_cast<const Derived &>(*this); } |
79 | |
80 | public: |
81 | /** \rst |
82 | Return an iterator equivalent to calling ``iter()`` in Python. The object |
83 | must be a collection which supports the iteration protocol. |
84 | \endrst */ |
85 | iterator begin() const; |
86 | /// Return a sentinel which ends iteration. |
87 | iterator end() const; |
88 | |
89 | /** \rst |
90 | Return an internal functor to invoke the object's sequence protocol. Casting |
91 | the returned ``detail::item_accessor`` instance to a `handle` or `object` |
92 | subclass causes a corresponding call to ``__getitem__``. Assigning a `handle` |
93 | or `object` subclass causes a call to ``__setitem__``. |
94 | \endrst */ |
95 | item_accessor operator[](handle key) const; |
96 | /// See above (the only difference is that the key's reference is stolen) |
97 | item_accessor operator[](object &&key) const; |
98 | /// See above (the only difference is that the key is provided as a string literal) |
99 | item_accessor operator[](const char *key) const; |
100 | |
101 | /** \rst |
102 | Return an internal functor to access the object's attributes. Casting the |
103 | returned ``detail::obj_attr_accessor`` instance to a `handle` or `object` |
104 | subclass causes a corresponding call to ``getattr``. Assigning a `handle` |
105 | or `object` subclass causes a call to ``setattr``. |
106 | \endrst */ |
107 | obj_attr_accessor attr(handle key) const; |
108 | /// See above (the only difference is that the key's reference is stolen) |
109 | obj_attr_accessor attr(object &&key) const; |
110 | /// See above (the only difference is that the key is provided as a string literal) |
111 | str_attr_accessor attr(const char *key) const; |
112 | |
113 | /** \rst |
114 | Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple`` |
115 | or ``list`` for a function call. Applying another * to the result yields |
116 | ** unpacking, e.g. to unpack a dict as function keyword arguments. |
117 | See :ref:`calling_python_functions`. |
118 | \endrst */ |
119 | args_proxy operator*() const; |
120 | |
121 | /// Check if the given item is contained within this object, i.e. ``item in obj``. |
122 | template <typename T> |
123 | bool contains(T &&item) const; |
124 | |
125 | /** \rst |
126 | Assuming the Python object is a function or implements the ``__call__`` |
127 | protocol, ``operator()`` invokes the underlying function, passing an |
128 | arbitrary set of parameters. The result is returned as a `object` and |
129 | may need to be converted back into a Python object using `handle::cast()`. |
130 | |
131 | When some of the arguments cannot be converted to Python objects, the |
132 | function will throw a `cast_error` exception. When the Python function |
133 | call fails, a `error_already_set` exception is thrown. |
134 | \endrst */ |
135 | template <return_value_policy policy = return_value_policy::automatic_reference, |
136 | typename... Args> |
137 | object operator()(Args &&...args) const; |
138 | template <return_value_policy policy = return_value_policy::automatic_reference, |
139 | typename... Args> |
140 | PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)" ) |
141 | object call(Args &&...args) const; |
142 | |
143 | /// Equivalent to ``obj is other`` in Python. |
144 | bool is(object_api const &other) const { return derived().ptr() == other.derived().ptr(); } |
145 | /// Equivalent to ``obj is None`` in Python. |
146 | bool is_none() const { return derived().ptr() == Py_None; } |
147 | /// Equivalent to obj == other in Python |
148 | bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); } |
149 | bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); } |
150 | bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); } |
151 | bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); } |
152 | bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); } |
153 | bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); } |
154 | |
155 | object operator-() const; |
156 | object operator~() const; |
157 | object operator+(object_api const &other) const; |
158 | object operator+=(object_api const &other); |
159 | object operator-(object_api const &other) const; |
160 | object operator-=(object_api const &other); |
161 | object operator*(object_api const &other) const; |
162 | object operator*=(object_api const &other); |
163 | object operator/(object_api const &other) const; |
164 | object operator/=(object_api const &other); |
165 | object operator|(object_api const &other) const; |
166 | object operator|=(object_api const &other); |
167 | object operator&(object_api const &other) const; |
168 | object operator&=(object_api const &other); |
169 | object operator^(object_api const &other) const; |
170 | object operator^=(object_api const &other); |
171 | object operator<<(object_api const &other) const; |
172 | object operator<<=(object_api const &other); |
173 | object operator>>(object_api const &other) const; |
174 | object operator>>=(object_api const &other); |
175 | |
176 | PYBIND11_DEPRECATED("Use py::str(obj) instead" ) |
177 | pybind11::str str() const; |
178 | |
179 | /// Get or set the object's docstring, i.e. ``obj.__doc__``. |
180 | str_attr_accessor doc() const; |
181 | |
182 | /// Return the object's current reference count |
183 | int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); } |
184 | |
185 | // TODO PYBIND11_DEPRECATED( |
186 | // "Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()") |
187 | handle get_type() const; |
188 | |
189 | private: |
190 | bool rich_compare(object_api const &other, int value) const; |
191 | }; |
192 | |
193 | template <typename T> |
194 | using is_pyobj_ptr_or_nullptr_t = detail::any_of<std::is_same<T, PyObject *>, |
195 | std::is_same<T, PyObject *const>, |
196 | std::is_same<T, std::nullptr_t>>; |
197 | |
198 | PYBIND11_NAMESPACE_END(detail) |
199 | |
200 | #if !defined(PYBIND11_HANDLE_REF_DEBUG) && !defined(NDEBUG) |
201 | # define PYBIND11_HANDLE_REF_DEBUG |
202 | #endif |
203 | |
204 | /** \rst |
205 | Holds a reference to a Python object (no reference counting) |
206 | |
207 | The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a |
208 | ``PyObject *`` in Python's C API). It does not perform any automatic reference |
209 | counting and merely provides a basic C++ interface to various Python API functions. |
210 | |
211 | .. seealso:: |
212 | The `object` class inherits from `handle` and adds automatic reference |
213 | counting features. |
214 | \endrst */ |
215 | class handle : public detail::object_api<handle> { |
216 | public: |
217 | /// The default constructor creates a handle with a ``nullptr``-valued pointer |
218 | handle() = default; |
219 | |
220 | /// Enable implicit conversion from ``PyObject *`` and ``nullptr``. |
221 | /// Not using ``handle(PyObject *ptr)`` to avoid implicit conversion from ``0``. |
222 | template <typename T, |
223 | detail::enable_if_t<detail::is_pyobj_ptr_or_nullptr_t<T>::value, int> = 0> |
224 | // NOLINTNEXTLINE(google-explicit-constructor) |
225 | handle(T ptr) : m_ptr(ptr) {} |
226 | |
227 | /// Enable implicit conversion through ``T::operator PyObject *()``. |
228 | template < |
229 | typename T, |
230 | detail::enable_if_t<detail::all_of<detail::none_of<std::is_base_of<handle, T>, |
231 | detail::is_pyobj_ptr_or_nullptr_t<T>>, |
232 | std::is_convertible<T, PyObject *>>::value, |
233 | int> = 0> |
234 | // NOLINTNEXTLINE(google-explicit-constructor) |
235 | handle(T &obj) : m_ptr(obj) {} |
236 | |
237 | /// Return the underlying ``PyObject *`` pointer |
238 | PyObject *ptr() const { return m_ptr; } |
239 | PyObject *&ptr() { return m_ptr; } |
240 | |
241 | /** \rst |
242 | Manually increase the reference count of the Python object. Usually, it is |
243 | preferable to use the `object` class which derives from `handle` and calls |
244 | this function automatically. Returns a reference to itself. |
245 | \endrst */ |
246 | const handle &inc_ref() const & { |
247 | #ifdef PYBIND11_HANDLE_REF_DEBUG |
248 | inc_ref_counter(1); |
249 | #endif |
250 | Py_XINCREF(m_ptr); |
251 | return *this; |
252 | } |
253 | |
254 | /** \rst |
255 | Manually decrease the reference count of the Python object. Usually, it is |
256 | preferable to use the `object` class which derives from `handle` and calls |
257 | this function automatically. Returns a reference to itself. |
258 | \endrst */ |
259 | const handle &dec_ref() const & { |
260 | Py_XDECREF(m_ptr); |
261 | return *this; |
262 | } |
263 | |
264 | /** \rst |
265 | Attempt to cast the Python object into the given C++ type. A `cast_error` |
266 | will be throw upon failure. |
267 | \endrst */ |
268 | template <typename T> |
269 | T cast() const; |
270 | /// Return ``true`` when the `handle` wraps a valid Python object |
271 | explicit operator bool() const { return m_ptr != nullptr; } |
272 | /** \rst |
273 | Deprecated: Check that the underlying pointers are the same. |
274 | Equivalent to ``obj1 is obj2`` in Python. |
275 | \endrst */ |
276 | PYBIND11_DEPRECATED("Use obj1.is(obj2) instead" ) |
277 | bool operator==(const handle &h) const { return m_ptr == h.m_ptr; } |
278 | PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead" ) |
279 | bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; } |
280 | PYBIND11_DEPRECATED("Use handle::operator bool() instead" ) |
281 | bool check() const { return m_ptr != nullptr; } |
282 | |
283 | protected: |
284 | PyObject *m_ptr = nullptr; |
285 | |
286 | #ifdef PYBIND11_HANDLE_REF_DEBUG |
287 | private: |
288 | static std::size_t inc_ref_counter(std::size_t add) { |
289 | thread_local std::size_t counter = 0; |
290 | counter += add; |
291 | return counter; |
292 | } |
293 | |
294 | public: |
295 | static std::size_t inc_ref_counter() { return inc_ref_counter(0); } |
296 | #endif |
297 | }; |
298 | |
299 | /** \rst |
300 | Holds a reference to a Python object (with reference counting) |
301 | |
302 | Like `handle`, the `object` class is a thin wrapper around an arbitrary Python |
303 | object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it |
304 | optionally increases the object's reference count upon construction, and it |
305 | *always* decreases the reference count when the `object` instance goes out of |
306 | scope and is destructed. When using `object` instances consistently, it is much |
307 | easier to get reference counting right at the first attempt. |
308 | \endrst */ |
309 | class object : public handle { |
310 | public: |
311 | object() = default; |
312 | PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()" ) |
313 | object(handle h, bool is_borrowed) : handle(h) { |
314 | if (is_borrowed) { |
315 | inc_ref(); |
316 | } |
317 | } |
318 | /// Copy constructor; always increases the reference count |
319 | object(const object &o) : handle(o) { inc_ref(); } |
320 | /// Move constructor; steals the object from ``other`` and preserves its reference count |
321 | object(object &&other) noexcept : handle(other) { other.m_ptr = nullptr; } |
322 | /// Destructor; automatically calls `handle::dec_ref()` |
323 | ~object() { dec_ref(); } |
324 | |
325 | /** \rst |
326 | Resets the internal pointer to ``nullptr`` without decreasing the |
327 | object's reference count. The function returns a raw handle to the original |
328 | Python object. |
329 | \endrst */ |
330 | handle release() { |
331 | PyObject *tmp = m_ptr; |
332 | m_ptr = nullptr; |
333 | return handle(tmp); |
334 | } |
335 | |
336 | object &operator=(const object &other) { |
337 | // Skip inc_ref and dec_ref if both objects are the same |
338 | if (!this->is(other)) { |
339 | other.inc_ref(); |
340 | // Use temporary variable to ensure `*this` remains valid while |
341 | // `Py_XDECREF` executes, in case `*this` is accessible from Python. |
342 | handle temp(m_ptr); |
343 | m_ptr = other.m_ptr; |
344 | temp.dec_ref(); |
345 | } |
346 | return *this; |
347 | } |
348 | |
349 | object &operator=(object &&other) noexcept { |
350 | if (this != &other) { |
351 | handle temp(m_ptr); |
352 | m_ptr = other.m_ptr; |
353 | other.m_ptr = nullptr; |
354 | temp.dec_ref(); |
355 | } |
356 | return *this; |
357 | } |
358 | |
359 | #define PYBIND11_INPLACE_OP(iop) \ |
360 | object iop(object_api const &other) { return operator=(handle::iop(other)); } |
361 | |
362 | PYBIND11_INPLACE_OP(operator+=) |
363 | PYBIND11_INPLACE_OP(operator-=) |
364 | PYBIND11_INPLACE_OP(operator*=) |
365 | PYBIND11_INPLACE_OP(operator/=) |
366 | PYBIND11_INPLACE_OP(operator|=) |
367 | PYBIND11_INPLACE_OP(operator&=) |
368 | PYBIND11_INPLACE_OP(operator^=) |
369 | PYBIND11_INPLACE_OP(operator<<=) |
370 | PYBIND11_INPLACE_OP(operator>>=) |
371 | #undef PYBIND11_INPLACE_OP |
372 | |
373 | // Calling cast() on an object lvalue just copies (via handle::cast) |
374 | template <typename T> |
375 | T cast() const &; |
376 | // Calling on an object rvalue does a move, if needed and/or possible |
377 | template <typename T> |
378 | T cast() &&; |
379 | |
380 | protected: |
381 | // Tags for choosing constructors from raw PyObject * |
382 | struct borrowed_t {}; |
383 | struct stolen_t {}; |
384 | |
385 | /// @cond BROKEN |
386 | template <typename T> |
387 | friend T reinterpret_borrow(handle); |
388 | template <typename T> |
389 | friend T reinterpret_steal(handle); |
390 | /// @endcond |
391 | |
392 | public: |
393 | // Only accessible from derived classes and the reinterpret_* functions |
394 | object(handle h, borrowed_t) : handle(h) { inc_ref(); } |
395 | object(handle h, stolen_t) : handle(h) {} |
396 | }; |
397 | |
398 | /** \rst |
399 | Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference. |
400 | The target type ``T`` must be `object` or one of its derived classes. The function |
401 | doesn't do any conversions or checks. It's up to the user to make sure that the |
402 | target type is correct. |
403 | |
404 | .. code-block:: cpp |
405 | |
406 | PyObject *p = PyList_GetItem(obj, index); |
407 | py::object o = reinterpret_borrow<py::object>(p); |
408 | // or |
409 | py::tuple t = reinterpret_borrow<py::tuple>(p); // <-- `p` must be already be a `tuple` |
410 | \endrst */ |
411 | template <typename T> |
412 | T reinterpret_borrow(handle h) { |
413 | return {h, object::borrowed_t{}}; |
414 | } |
415 | |
416 | /** \rst |
417 | Like `reinterpret_borrow`, but steals the reference. |
418 | |
419 | .. code-block:: cpp |
420 | |
421 | PyObject *p = PyObject_Str(obj); |
422 | py::str s = reinterpret_steal<py::str>(p); // <-- `p` must be already be a `str` |
423 | \endrst */ |
424 | template <typename T> |
425 | T reinterpret_steal(handle h) { |
426 | return {h, object::stolen_t{}}; |
427 | } |
428 | |
429 | PYBIND11_NAMESPACE_BEGIN(detail) |
430 | |
431 | // Equivalent to obj.__class__.__name__ (or obj.__name__ if obj is a class). |
432 | inline const char *obj_class_name(PyObject *obj) { |
433 | if (Py_TYPE(obj) == &PyType_Type) { |
434 | return reinterpret_cast<PyTypeObject *>(obj)->tp_name; |
435 | } |
436 | return Py_TYPE(obj)->tp_name; |
437 | } |
438 | |
439 | std::string error_string(); |
440 | |
441 | struct error_fetch_and_normalize { |
442 | // Immediate normalization is long-established behavior (starting with |
443 | // https://github.com/pybind/pybind11/commit/135ba8deafb8bf64a15b24d1513899eb600e2011 |
444 | // from Sep 2016) and safest. Normalization could be deferred, but this could mask |
445 | // errors elsewhere, the performance gain is very minor in typical situations |
446 | // (usually the dominant bottleneck is EH unwinding), and the implementation here |
447 | // would be more complex. |
448 | explicit error_fetch_and_normalize(const char *called) { |
449 | PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr()); |
450 | if (!m_type) { |
451 | pybind11_fail("Internal error: " + std::string(called) |
452 | + " called while " |
453 | "Python error indicator not set." ); |
454 | } |
455 | const char *exc_type_name_orig = detail::obj_class_name(m_type.ptr()); |
456 | if (exc_type_name_orig == nullptr) { |
457 | pybind11_fail("Internal error: " + std::string(called) |
458 | + " failed to obtain the name " |
459 | "of the original active exception type." ); |
460 | } |
461 | m_lazy_error_string = exc_type_name_orig; |
462 | // PyErr_NormalizeException() may change the exception type if there are cascading |
463 | // failures. This can potentially be extremely confusing. |
464 | PyErr_NormalizeException(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr()); |
465 | if (m_type.ptr() == nullptr) { |
466 | pybind11_fail("Internal error: " + std::string(called) |
467 | + " failed to normalize the " |
468 | "active exception." ); |
469 | } |
470 | const char *exc_type_name_norm = detail::obj_class_name(m_type.ptr()); |
471 | if (exc_type_name_orig == nullptr) { |
472 | pybind11_fail("Internal error: " + std::string(called) |
473 | + " failed to obtain the name " |
474 | "of the normalized active exception type." ); |
475 | } |
476 | #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x07030a00 |
477 | // This behavior runs the risk of masking errors in the error handling, but avoids a |
478 | // conflict with PyPy, which relies on the normalization here to change OSError to |
479 | // FileNotFoundError (https://github.com/pybind/pybind11/issues/4075). |
480 | m_lazy_error_string = exc_type_name_norm; |
481 | #else |
482 | if (exc_type_name_norm != m_lazy_error_string) { |
483 | std::string msg = std::string(called) |
484 | + ": MISMATCH of original and normalized " |
485 | "active exception types: " ; |
486 | msg += "ORIGINAL " ; |
487 | msg += m_lazy_error_string; |
488 | msg += " REPLACED BY " ; |
489 | msg += exc_type_name_norm; |
490 | msg += ": " + format_value_and_trace(); |
491 | pybind11_fail(msg); |
492 | } |
493 | #endif |
494 | } |
495 | |
496 | error_fetch_and_normalize(const error_fetch_and_normalize &) = delete; |
497 | error_fetch_and_normalize(error_fetch_and_normalize &&) = delete; |
498 | |
499 | std::string format_value_and_trace() const { |
500 | std::string result; |
501 | std::string message_error_string; |
502 | if (m_value) { |
503 | auto value_str = reinterpret_steal<object>(PyObject_Str(m_value.ptr())); |
504 | constexpr const char *message_unavailable_exc |
505 | = "<MESSAGE UNAVAILABLE DUE TO ANOTHER EXCEPTION>" ; |
506 | if (!value_str) { |
507 | message_error_string = detail::error_string(); |
508 | result = message_unavailable_exc; |
509 | } else { |
510 | // Not using `value_str.cast<std::string>()`, to not potentially throw a secondary |
511 | // error_already_set that will then result in process termination (#4288). |
512 | auto value_bytes = reinterpret_steal<object>( |
513 | PyUnicode_AsEncodedString(value_str.ptr(), "utf-8" , "backslashreplace" )); |
514 | if (!value_bytes) { |
515 | message_error_string = detail::error_string(); |
516 | result = message_unavailable_exc; |
517 | } else { |
518 | char *buffer = nullptr; |
519 | Py_ssize_t length = 0; |
520 | if (PyBytes_AsStringAndSize(value_bytes.ptr(), &buffer, &length) == -1) { |
521 | message_error_string = detail::error_string(); |
522 | result = message_unavailable_exc; |
523 | } else { |
524 | result = std::string(buffer, static_cast<std::size_t>(length)); |
525 | } |
526 | } |
527 | } |
528 | } else { |
529 | result = "<MESSAGE UNAVAILABLE>" ; |
530 | } |
531 | if (result.empty()) { |
532 | result = "<EMPTY MESSAGE>" ; |
533 | } |
534 | |
535 | bool have_trace = false; |
536 | if (m_trace) { |
537 | #if !defined(PYPY_VERSION) |
538 | auto *tb = reinterpret_cast<PyTracebackObject *>(m_trace.ptr()); |
539 | |
540 | // Get the deepest trace possible. |
541 | while (tb->tb_next) { |
542 | tb = tb->tb_next; |
543 | } |
544 | |
545 | PyFrameObject *frame = tb->tb_frame; |
546 | Py_XINCREF(frame); |
547 | result += "\n\nAt:\n" ; |
548 | while (frame) { |
549 | # if PY_VERSION_HEX >= 0x030900B1 |
550 | PyCodeObject *f_code = PyFrame_GetCode(frame); |
551 | # else |
552 | PyCodeObject *f_code = frame->f_code; |
553 | Py_INCREF(f_code); |
554 | # endif |
555 | int lineno = PyFrame_GetLineNumber(frame); |
556 | result += " " ; |
557 | result += handle(f_code->co_filename).cast<std::string>(); |
558 | result += '('; |
559 | result += std::to_string(lineno); |
560 | result += "): " ; |
561 | result += handle(f_code->co_name).cast<std::string>(); |
562 | result += '\n'; |
563 | Py_DECREF(f_code); |
564 | # if PY_VERSION_HEX >= 0x030900B1 |
565 | auto *b_frame = PyFrame_GetBack(frame); |
566 | # else |
567 | auto *b_frame = frame->f_back; |
568 | Py_XINCREF(b_frame); |
569 | # endif |
570 | Py_DECREF(frame); |
571 | frame = b_frame; |
572 | } |
573 | |
574 | have_trace = true; |
575 | #endif //! defined(PYPY_VERSION) |
576 | } |
577 | |
578 | if (!message_error_string.empty()) { |
579 | if (!have_trace) { |
580 | result += '\n'; |
581 | } |
582 | result += "\nMESSAGE UNAVAILABLE DUE TO EXCEPTION: " + message_error_string; |
583 | } |
584 | |
585 | return result; |
586 | } |
587 | |
588 | std::string const &error_string() const { |
589 | if (!m_lazy_error_string_completed) { |
590 | m_lazy_error_string += ": " + format_value_and_trace(); |
591 | m_lazy_error_string_completed = true; |
592 | } |
593 | return m_lazy_error_string; |
594 | } |
595 | |
596 | void restore() { |
597 | if (m_restore_called) { |
598 | pybind11_fail("Internal error: pybind11::detail::error_fetch_and_normalize::restore() " |
599 | "called a second time. ORIGINAL ERROR: " |
600 | + error_string()); |
601 | } |
602 | PyErr_Restore(m_type.inc_ref().ptr(), m_value.inc_ref().ptr(), m_trace.inc_ref().ptr()); |
603 | m_restore_called = true; |
604 | } |
605 | |
606 | bool matches(handle exc) const { |
607 | return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0); |
608 | } |
609 | |
610 | // Not protecting these for simplicity. |
611 | object m_type, m_value, m_trace; |
612 | |
613 | private: |
614 | // Only protecting invariants. |
615 | mutable std::string m_lazy_error_string; |
616 | mutable bool m_lazy_error_string_completed = false; |
617 | mutable bool m_restore_called = false; |
618 | }; |
619 | |
620 | inline std::string error_string() { |
621 | return error_fetch_and_normalize("pybind11::detail::error_string" ).error_string(); |
622 | } |
623 | |
624 | PYBIND11_NAMESPACE_END(detail) |
625 | |
626 | #if defined(_MSC_VER) |
627 | # pragma warning(push) |
628 | # pragma warning(disable : 4275 4251) |
629 | // warning C4275: An exported class was derived from a class that wasn't exported. |
630 | // Can be ignored when derived from a STL class. |
631 | #endif |
632 | /// Fetch and hold an error which was already set in Python. An instance of this is typically |
633 | /// thrown to propagate python-side errors back through C++ which can either be caught manually or |
634 | /// else falls back to the function dispatcher (which then raises the captured error back to |
635 | /// python). |
636 | class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::exception { |
637 | public: |
638 | /// Fetches the current Python exception (using PyErr_Fetch()), which will clear the |
639 | /// current Python error indicator. |
640 | error_already_set() |
641 | : m_fetched_error{new detail::error_fetch_and_normalize("pybind11::error_already_set" ), |
642 | m_fetched_error_deleter} {} |
643 | |
644 | /// The what() result is built lazily on demand. |
645 | /// WARNING: This member function needs to acquire the Python GIL. This can lead to |
646 | /// crashes (undefined behavior) if the Python interpreter is finalizing. |
647 | const char *what() const noexcept override; |
648 | |
649 | /// Restores the currently-held Python error (which will clear the Python error indicator first |
650 | /// if already set). |
651 | /// NOTE: This member function will always restore the normalized exception, which may or may |
652 | /// not be the original Python exception. |
653 | /// WARNING: The GIL must be held when this member function is called! |
654 | void restore() { m_fetched_error->restore(); } |
655 | |
656 | /// If it is impossible to raise the currently-held error, such as in a destructor, we can |
657 | /// write it out using Python's unraisable hook (`sys.unraisablehook`). The error context |
658 | /// should be some object whose `repr()` helps identify the location of the error. Python |
659 | /// already knows the type and value of the error, so there is no need to repeat that. |
660 | void discard_as_unraisable(object err_context) { |
661 | restore(); |
662 | PyErr_WriteUnraisable(err_context.ptr()); |
663 | } |
664 | /// An alternate version of `discard_as_unraisable()`, where a string provides information on |
665 | /// the location of the error. For example, `__func__` could be helpful. |
666 | /// WARNING: The GIL must be held when this member function is called! |
667 | void discard_as_unraisable(const char *err_context) { |
668 | discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context))); |
669 | } |
670 | |
671 | // Does nothing; provided for backwards compatibility. |
672 | PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated" ) |
673 | void clear() {} |
674 | |
675 | /// Check if the currently trapped error type matches the given Python exception class (or a |
676 | /// subclass thereof). May also be passed a tuple to search for any exception class matches in |
677 | /// the given tuple. |
678 | bool matches(handle exc) const { return m_fetched_error->matches(exc); } |
679 | |
680 | const object &type() const { return m_fetched_error->m_type; } |
681 | const object &value() const { return m_fetched_error->m_value; } |
682 | const object &trace() const { return m_fetched_error->m_trace; } |
683 | |
684 | private: |
685 | std::shared_ptr<detail::error_fetch_and_normalize> m_fetched_error; |
686 | |
687 | /// WARNING: This custom deleter needs to acquire the Python GIL. This can lead to |
688 | /// crashes (undefined behavior) if the Python interpreter is finalizing. |
689 | static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr); |
690 | }; |
691 | #if defined(_MSC_VER) |
692 | # pragma warning(pop) |
693 | #endif |
694 | |
695 | /// Replaces the current Python error indicator with the chosen error, performing a |
696 | /// 'raise from' to indicate that the chosen error was caused by the original error. |
697 | inline void raise_from(PyObject *type, const char *message) { |
698 | // Based on _PyErr_FormatVFromCause: |
699 | // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405 |
700 | // See https://github.com/pybind/pybind11/pull/2112 for details. |
701 | PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr; |
702 | |
703 | assert(PyErr_Occurred()); |
704 | PyErr_Fetch(&exc, &val, &tb); |
705 | PyErr_NormalizeException(&exc, &val, &tb); |
706 | if (tb != nullptr) { |
707 | PyException_SetTraceback(val, tb); |
708 | Py_DECREF(tb); |
709 | } |
710 | Py_DECREF(exc); |
711 | assert(!PyErr_Occurred()); |
712 | |
713 | PyErr_SetString(type, message); |
714 | |
715 | PyErr_Fetch(&exc, &val2, &tb); |
716 | PyErr_NormalizeException(&exc, &val2, &tb); |
717 | Py_INCREF(val); |
718 | PyException_SetCause(val2, val); |
719 | PyException_SetContext(val2, val); |
720 | PyErr_Restore(exc, val2, tb); |
721 | } |
722 | |
723 | /// Sets the current Python error indicator with the chosen error, performing a 'raise from' |
724 | /// from the error contained in error_already_set to indicate that the chosen error was |
725 | /// caused by the original error. |
726 | inline void raise_from(error_already_set &err, PyObject *type, const char *message) { |
727 | err.restore(); |
728 | raise_from(type, message); |
729 | } |
730 | |
731 | /** \defgroup python_builtins const_name |
732 | Unless stated otherwise, the following C++ functions behave the same |
733 | as their Python counterparts. |
734 | */ |
735 | |
736 | /** \ingroup python_builtins |
737 | \rst |
738 | Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of |
739 | `object` or a class which was exposed to Python as ``py::class_<T>``. |
740 | \endrst */ |
741 | template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0> |
742 | bool isinstance(handle obj) { |
743 | return T::check_(obj); |
744 | } |
745 | |
746 | template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0> |
747 | bool isinstance(handle obj) { |
748 | return detail::isinstance_generic(obj, typeid(T)); |
749 | } |
750 | |
751 | template <> |
752 | inline bool isinstance<handle>(handle) = delete; |
753 | template <> |
754 | inline bool isinstance<object>(handle obj) { |
755 | return obj.ptr() != nullptr; |
756 | } |
757 | |
758 | /// \ingroup python_builtins |
759 | /// Return true if ``obj`` is an instance of the ``type``. |
760 | inline bool isinstance(handle obj, handle type) { |
761 | const auto result = PyObject_IsInstance(obj.ptr(), type.ptr()); |
762 | if (result == -1) { |
763 | throw error_already_set(); |
764 | } |
765 | return result != 0; |
766 | } |
767 | |
768 | /// \addtogroup python_builtins |
769 | /// @{ |
770 | inline bool hasattr(handle obj, handle name) { |
771 | return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1; |
772 | } |
773 | |
774 | inline bool hasattr(handle obj, const char *name) { |
775 | return PyObject_HasAttrString(obj.ptr(), name) == 1; |
776 | } |
777 | |
778 | inline void delattr(handle obj, handle name) { |
779 | if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) { |
780 | throw error_already_set(); |
781 | } |
782 | } |
783 | |
784 | inline void delattr(handle obj, const char *name) { |
785 | if (PyObject_DelAttrString(obj.ptr(), name) != 0) { |
786 | throw error_already_set(); |
787 | } |
788 | } |
789 | |
790 | inline object getattr(handle obj, handle name) { |
791 | PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr()); |
792 | if (!result) { |
793 | throw error_already_set(); |
794 | } |
795 | return reinterpret_steal<object>(result); |
796 | } |
797 | |
798 | inline object getattr(handle obj, const char *name) { |
799 | PyObject *result = PyObject_GetAttrString(obj.ptr(), name); |
800 | if (!result) { |
801 | throw error_already_set(); |
802 | } |
803 | return reinterpret_steal<object>(result); |
804 | } |
805 | |
806 | inline object getattr(handle obj, handle name, handle default_) { |
807 | if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) { |
808 | return reinterpret_steal<object>(result); |
809 | } |
810 | PyErr_Clear(); |
811 | return reinterpret_borrow<object>(default_); |
812 | } |
813 | |
814 | inline object getattr(handle obj, const char *name, handle default_) { |
815 | if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) { |
816 | return reinterpret_steal<object>(result); |
817 | } |
818 | PyErr_Clear(); |
819 | return reinterpret_borrow<object>(default_); |
820 | } |
821 | |
822 | inline void setattr(handle obj, handle name, handle value) { |
823 | if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) { |
824 | throw error_already_set(); |
825 | } |
826 | } |
827 | |
828 | inline void setattr(handle obj, const char *name, handle value) { |
829 | if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { |
830 | throw error_already_set(); |
831 | } |
832 | } |
833 | |
834 | inline ssize_t hash(handle obj) { |
835 | auto h = PyObject_Hash(obj.ptr()); |
836 | if (h == -1) { |
837 | throw error_already_set(); |
838 | } |
839 | return h; |
840 | } |
841 | |
842 | /// @} python_builtins |
843 | |
844 | PYBIND11_NAMESPACE_BEGIN(detail) |
845 | inline handle get_function(handle value) { |
846 | if (value) { |
847 | if (PyInstanceMethod_Check(value.ptr())) { |
848 | value = PyInstanceMethod_GET_FUNCTION(value.ptr()); |
849 | } else if (PyMethod_Check(value.ptr())) { |
850 | value = PyMethod_GET_FUNCTION(value.ptr()); |
851 | } |
852 | } |
853 | return value; |
854 | } |
855 | |
856 | // Reimplementation of python's dict helper functions to ensure that exceptions |
857 | // aren't swallowed (see #2862) |
858 | |
859 | // copied from cpython _PyDict_GetItemStringWithError |
860 | inline PyObject *dict_getitemstring(PyObject *v, const char *key) { |
861 | PyObject *kv = nullptr, *rv = nullptr; |
862 | kv = PyUnicode_FromString(key); |
863 | if (kv == nullptr) { |
864 | throw error_already_set(); |
865 | } |
866 | |
867 | rv = PyDict_GetItemWithError(v, kv); |
868 | Py_DECREF(kv); |
869 | if (rv == nullptr && PyErr_Occurred()) { |
870 | throw error_already_set(); |
871 | } |
872 | return rv; |
873 | } |
874 | |
875 | inline PyObject *dict_getitem(PyObject *v, PyObject *key) { |
876 | PyObject *rv = PyDict_GetItemWithError(v, key); |
877 | if (rv == nullptr && PyErr_Occurred()) { |
878 | throw error_already_set(); |
879 | } |
880 | return rv; |
881 | } |
882 | |
883 | // Helper aliases/functions to support implicit casting of values given to python |
884 | // accessors/methods. When given a pyobject, this simply returns the pyobject as-is; for other C++ |
885 | // type, the value goes through pybind11::cast(obj) to convert it to an `object`. |
886 | template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0> |
887 | auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) { |
888 | return std::forward<T>(o); |
889 | } |
890 | // The following casting version is implemented in cast.h: |
891 | template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0> |
892 | object object_or_cast(T &&o); |
893 | // Match a PyObject*, which we want to convert directly to handle via its converting constructor |
894 | inline handle object_or_cast(PyObject *ptr) { return ptr; } |
895 | |
896 | #if defined(_MSC_VER) && _MSC_VER < 1920 |
897 | # pragma warning(push) |
898 | # pragma warning(disable : 4522) // warning C4522: multiple assignment operators specified |
899 | #endif |
900 | template <typename Policy> |
901 | class accessor : public object_api<accessor<Policy>> { |
902 | using key_type = typename Policy::key_type; |
903 | |
904 | public: |
905 | accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) {} |
906 | accessor(const accessor &) = default; |
907 | accessor(accessor &&) noexcept = default; |
908 | |
909 | // accessor overload required to override default assignment operator (templates are not |
910 | // allowed to replace default compiler-generated assignments). |
911 | void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); } |
912 | void operator=(const accessor &a) & { operator=(handle(a)); } |
913 | |
914 | template <typename T> |
915 | void operator=(T &&value) && { |
916 | Policy::set(obj, key, object_or_cast(std::forward<T>(value))); |
917 | } |
918 | template <typename T> |
919 | void operator=(T &&value) & { |
920 | get_cache() = ensure_object(object_or_cast(std::forward<T>(value))); |
921 | } |
922 | |
923 | template <typename T = Policy> |
924 | PYBIND11_DEPRECATED( |
925 | "Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)" ) |
926 | explicit |
927 | operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value |
928 | || std::is_same<T, accessor_policies::obj_attr>::value, |
929 | bool>() const { |
930 | return hasattr(obj, key); |
931 | } |
932 | template <typename T = Policy> |
933 | PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)" ) |
934 | explicit |
935 | operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const { |
936 | return obj.contains(key); |
937 | } |
938 | |
939 | // NOLINTNEXTLINE(google-explicit-constructor) |
940 | operator object() const { return get_cache(); } |
941 | PyObject *ptr() const { return get_cache().ptr(); } |
942 | template <typename T> |
943 | T cast() const { |
944 | return get_cache().template cast<T>(); |
945 | } |
946 | |
947 | private: |
948 | static object ensure_object(object &&o) { return std::move(o); } |
949 | static object ensure_object(handle h) { return reinterpret_borrow<object>(h); } |
950 | |
951 | object &get_cache() const { |
952 | if (!cache) { |
953 | cache = Policy::get(obj, key); |
954 | } |
955 | return cache; |
956 | } |
957 | |
958 | private: |
959 | handle obj; |
960 | key_type key; |
961 | mutable object cache; |
962 | }; |
963 | #if defined(_MSC_VER) && _MSC_VER < 1920 |
964 | # pragma warning(pop) |
965 | #endif |
966 | |
967 | PYBIND11_NAMESPACE_BEGIN(accessor_policies) |
968 | struct obj_attr { |
969 | using key_type = object; |
970 | static object get(handle obj, handle key) { return getattr(obj, key); } |
971 | static void set(handle obj, handle key, handle val) { setattr(obj, key, val); } |
972 | }; |
973 | |
974 | struct str_attr { |
975 | using key_type = const char *; |
976 | static object get(handle obj, const char *key) { return getattr(obj, key); } |
977 | static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); } |
978 | }; |
979 | |
980 | struct generic_item { |
981 | using key_type = object; |
982 | |
983 | static object get(handle obj, handle key) { |
984 | PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr()); |
985 | if (!result) { |
986 | throw error_already_set(); |
987 | } |
988 | return reinterpret_steal<object>(result); |
989 | } |
990 | |
991 | static void set(handle obj, handle key, handle val) { |
992 | if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) { |
993 | throw error_already_set(); |
994 | } |
995 | } |
996 | }; |
997 | |
998 | struct sequence_item { |
999 | using key_type = size_t; |
1000 | |
1001 | template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> |
1002 | static object get(handle obj, const IdxType &index) { |
1003 | PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index)); |
1004 | if (!result) { |
1005 | throw error_already_set(); |
1006 | } |
1007 | return reinterpret_steal<object>(result); |
1008 | } |
1009 | |
1010 | template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> |
1011 | static void set(handle obj, const IdxType &index, handle val) { |
1012 | // PySequence_SetItem does not steal a reference to 'val' |
1013 | if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) { |
1014 | throw error_already_set(); |
1015 | } |
1016 | } |
1017 | }; |
1018 | |
1019 | struct list_item { |
1020 | using key_type = size_t; |
1021 | |
1022 | template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> |
1023 | static object get(handle obj, const IdxType &index) { |
1024 | PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index)); |
1025 | if (!result) { |
1026 | throw error_already_set(); |
1027 | } |
1028 | return reinterpret_borrow<object>(result); |
1029 | } |
1030 | |
1031 | template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> |
1032 | static void set(handle obj, const IdxType &index, handle val) { |
1033 | // PyList_SetItem steals a reference to 'val' |
1034 | if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) { |
1035 | throw error_already_set(); |
1036 | } |
1037 | } |
1038 | }; |
1039 | |
1040 | struct tuple_item { |
1041 | using key_type = size_t; |
1042 | |
1043 | template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> |
1044 | static object get(handle obj, const IdxType &index) { |
1045 | PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index)); |
1046 | if (!result) { |
1047 | throw error_already_set(); |
1048 | } |
1049 | return reinterpret_borrow<object>(result); |
1050 | } |
1051 | |
1052 | template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> |
1053 | static void set(handle obj, const IdxType &index, handle val) { |
1054 | // PyTuple_SetItem steals a reference to 'val' |
1055 | if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) { |
1056 | throw error_already_set(); |
1057 | } |
1058 | } |
1059 | }; |
1060 | PYBIND11_NAMESPACE_END(accessor_policies) |
1061 | |
1062 | /// STL iterator template used for tuple, list, sequence and dict |
1063 | template <typename Policy> |
1064 | class generic_iterator : public Policy { |
1065 | using It = generic_iterator; |
1066 | |
1067 | public: |
1068 | using difference_type = ssize_t; |
1069 | using iterator_category = typename Policy::iterator_category; |
1070 | using value_type = typename Policy::value_type; |
1071 | using reference = typename Policy::reference; |
1072 | using pointer = typename Policy::pointer; |
1073 | |
1074 | generic_iterator() = default; |
1075 | generic_iterator(handle seq, ssize_t index) : Policy(seq, index) {} |
1076 | |
1077 | // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 |
1078 | reference operator*() const { return Policy::dereference(); } |
1079 | // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 |
1080 | reference operator[](difference_type n) const { return *(*this + n); } |
1081 | pointer operator->() const { return **this; } |
1082 | |
1083 | It &operator++() { |
1084 | Policy::increment(); |
1085 | return *this; |
1086 | } |
1087 | It operator++(int) { |
1088 | auto copy = *this; |
1089 | Policy::increment(); |
1090 | return copy; |
1091 | } |
1092 | It &operator--() { |
1093 | Policy::decrement(); |
1094 | return *this; |
1095 | } |
1096 | It operator--(int) { |
1097 | auto copy = *this; |
1098 | Policy::decrement(); |
1099 | return copy; |
1100 | } |
1101 | It &operator+=(difference_type n) { |
1102 | Policy::advance(n); |
1103 | return *this; |
1104 | } |
1105 | It &operator-=(difference_type n) { |
1106 | Policy::advance(-n); |
1107 | return *this; |
1108 | } |
1109 | |
1110 | friend It operator+(const It &a, difference_type n) { |
1111 | auto copy = a; |
1112 | return copy += n; |
1113 | } |
1114 | friend It operator+(difference_type n, const It &b) { return b + n; } |
1115 | friend It operator-(const It &a, difference_type n) { |
1116 | auto copy = a; |
1117 | return copy -= n; |
1118 | } |
1119 | friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); } |
1120 | |
1121 | friend bool operator==(const It &a, const It &b) { return a.equal(b); } |
1122 | friend bool operator!=(const It &a, const It &b) { return !(a == b); } |
1123 | friend bool operator<(const It &a, const It &b) { return b - a > 0; } |
1124 | friend bool operator>(const It &a, const It &b) { return b < a; } |
1125 | friend bool operator>=(const It &a, const It &b) { return !(a < b); } |
1126 | friend bool operator<=(const It &a, const It &b) { return !(a > b); } |
1127 | }; |
1128 | |
1129 | PYBIND11_NAMESPACE_BEGIN(iterator_policies) |
1130 | /// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers |
1131 | template <typename T> |
1132 | struct arrow_proxy { |
1133 | T value; |
1134 | |
1135 | // NOLINTNEXTLINE(google-explicit-constructor) |
1136 | arrow_proxy(T &&value) noexcept : value(std::move(value)) {} |
1137 | T *operator->() const { return &value; } |
1138 | }; |
1139 | |
1140 | /// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS`` |
1141 | class sequence_fast_readonly { |
1142 | protected: |
1143 | using iterator_category = std::random_access_iterator_tag; |
1144 | using value_type = handle; |
1145 | using reference = const handle; // PR #3263 |
1146 | using pointer = arrow_proxy<const handle>; |
1147 | |
1148 | sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) {} |
1149 | |
1150 | // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 |
1151 | reference dereference() const { return *ptr; } |
1152 | void increment() { ++ptr; } |
1153 | void decrement() { --ptr; } |
1154 | void advance(ssize_t n) { ptr += n; } |
1155 | bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; } |
1156 | ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; } |
1157 | |
1158 | private: |
1159 | PyObject **ptr; |
1160 | }; |
1161 | |
1162 | /// Full read and write access using the sequence protocol: see ``detail::sequence_accessor`` |
1163 | class sequence_slow_readwrite { |
1164 | protected: |
1165 | using iterator_category = std::random_access_iterator_tag; |
1166 | using value_type = object; |
1167 | using reference = sequence_accessor; |
1168 | using pointer = arrow_proxy<const sequence_accessor>; |
1169 | |
1170 | sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) {} |
1171 | |
1172 | reference dereference() const { return {obj, static_cast<size_t>(index)}; } |
1173 | void increment() { ++index; } |
1174 | void decrement() { --index; } |
1175 | void advance(ssize_t n) { index += n; } |
1176 | bool equal(const sequence_slow_readwrite &b) const { return index == b.index; } |
1177 | ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; } |
1178 | |
1179 | private: |
1180 | handle obj; |
1181 | ssize_t index; |
1182 | }; |
1183 | |
1184 | /// Python's dictionary protocol permits this to be a forward iterator |
1185 | class dict_readonly { |
1186 | protected: |
1187 | using iterator_category = std::forward_iterator_tag; |
1188 | using value_type = std::pair<handle, handle>; |
1189 | using reference = const value_type; // PR #3263 |
1190 | using pointer = arrow_proxy<const value_type>; |
1191 | |
1192 | dict_readonly() = default; |
1193 | dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); } |
1194 | |
1195 | // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 |
1196 | reference dereference() const { return {key, value}; } |
1197 | void increment() { |
1198 | if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) { |
1199 | pos = -1; |
1200 | } |
1201 | } |
1202 | bool equal(const dict_readonly &b) const { return pos == b.pos; } |
1203 | |
1204 | private: |
1205 | handle obj; |
1206 | PyObject *key = nullptr, *value = nullptr; |
1207 | ssize_t pos = -1; |
1208 | }; |
1209 | PYBIND11_NAMESPACE_END(iterator_policies) |
1210 | |
1211 | #if !defined(PYPY_VERSION) |
1212 | using tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>; |
1213 | using list_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>; |
1214 | #else |
1215 | using tuple_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>; |
1216 | using list_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>; |
1217 | #endif |
1218 | |
1219 | using sequence_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>; |
1220 | using dict_iterator = generic_iterator<iterator_policies::dict_readonly>; |
1221 | |
1222 | inline bool PyIterable_Check(PyObject *obj) { |
1223 | PyObject *iter = PyObject_GetIter(obj); |
1224 | if (iter) { |
1225 | Py_DECREF(iter); |
1226 | return true; |
1227 | } |
1228 | PyErr_Clear(); |
1229 | return false; |
1230 | } |
1231 | |
1232 | inline bool PyNone_Check(PyObject *o) { return o == Py_None; } |
1233 | inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; } |
1234 | |
1235 | #ifdef PYBIND11_STR_LEGACY_PERMISSIVE |
1236 | inline bool PyUnicode_Check_Permissive(PyObject *o) { |
1237 | return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); |
1238 | } |
1239 | # define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive |
1240 | #else |
1241 | # define PYBIND11_STR_CHECK_FUN PyUnicode_Check |
1242 | #endif |
1243 | |
1244 | inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; } |
1245 | |
1246 | class kwargs_proxy : public handle { |
1247 | public: |
1248 | explicit kwargs_proxy(handle h) : handle(h) {} |
1249 | }; |
1250 | |
1251 | class args_proxy : public handle { |
1252 | public: |
1253 | explicit args_proxy(handle h) : handle(h) {} |
1254 | kwargs_proxy operator*() const { return kwargs_proxy(*this); } |
1255 | }; |
1256 | |
1257 | /// Python argument categories (using PEP 448 terms) |
1258 | template <typename T> |
1259 | using is_keyword = std::is_base_of<arg, T>; |
1260 | template <typename T> |
1261 | using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking |
1262 | template <typename T> |
1263 | using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking |
1264 | template <typename T> |
1265 | using is_positional = satisfies_none_of<T, is_keyword, is_s_unpacking, is_ds_unpacking>; |
1266 | template <typename T> |
1267 | using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>; |
1268 | |
1269 | // Call argument collector forward declarations |
1270 | template <return_value_policy policy = return_value_policy::automatic_reference> |
1271 | class simple_collector; |
1272 | template <return_value_policy policy = return_value_policy::automatic_reference> |
1273 | class unpacking_collector; |
1274 | |
1275 | PYBIND11_NAMESPACE_END(detail) |
1276 | |
1277 | // TODO: After the deprecated constructors are removed, this macro can be simplified by |
1278 | // inheriting ctors: `using Parent::Parent`. It's not an option right now because |
1279 | // the `using` statement triggers the parent deprecation warning even if the ctor |
1280 | // isn't even used. |
1281 | #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ |
1282 | public: \ |
1283 | PYBIND11_DEPRECATED("Use reinterpret_borrow<" #Name ">() or reinterpret_steal<" #Name ">()") \ |
1284 | Name(handle h, bool is_borrowed) \ |
1285 | : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {} \ |
1286 | Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {} \ |
1287 | Name(handle h, stolen_t) : Parent(h, stolen_t{}) {} \ |
1288 | PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \ |
1289 | bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \ |
1290 | static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \ |
1291 | template <typename Policy_> /* NOLINTNEXTLINE(google-explicit-constructor) */ \ |
1292 | Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) {} |
1293 | |
1294 | #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \ |
1295 | PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ |
1296 | /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ |
1297 | /* NOLINTNEXTLINE(google-explicit-constructor) */ \ |
1298 | Name(const object &o) \ |
1299 | : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \ |
1300 | if (!m_ptr) \ |
1301 | throw ::pybind11::error_already_set(); \ |
1302 | } \ |
1303 | /* NOLINTNEXTLINE(google-explicit-constructor) */ \ |
1304 | Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \ |
1305 | if (!m_ptr) \ |
1306 | throw ::pybind11::error_already_set(); \ |
1307 | } |
1308 | |
1309 | #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \ |
1310 | PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \ |
1311 | Name() = default; |
1312 | |
1313 | #define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \ |
1314 | ::pybind11::type_error("Object of type '" \ |
1315 | + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) \ |
1316 | + "' is not an instance of '" #Name "'") |
1317 | |
1318 | #define PYBIND11_OBJECT(Name, Parent, CheckFun) \ |
1319 | PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ |
1320 | /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ |
1321 | /* NOLINTNEXTLINE(google-explicit-constructor) */ \ |
1322 | Name(const object &o) : Parent(o) { \ |
1323 | if (m_ptr && !check_(m_ptr)) \ |
1324 | throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \ |
1325 | } \ |
1326 | /* NOLINTNEXTLINE(google-explicit-constructor) */ \ |
1327 | Name(object &&o) : Parent(std::move(o)) { \ |
1328 | if (m_ptr && !check_(m_ptr)) \ |
1329 | throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \ |
1330 | } |
1331 | |
1332 | #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \ |
1333 | PYBIND11_OBJECT(Name, Parent, CheckFun) \ |
1334 | Name() = default; |
1335 | |
1336 | /// \addtogroup pytypes |
1337 | /// @{ |
1338 | |
1339 | /** \rst |
1340 | Wraps a Python iterator so that it can also be used as a C++ input iterator |
1341 | |
1342 | Caveat: copying an iterator does not (and cannot) clone the internal |
1343 | state of the Python iterable. This also applies to the post-increment |
1344 | operator. This iterator should only be used to retrieve the current |
1345 | value using ``operator*()``. |
1346 | \endrst */ |
1347 | class iterator : public object { |
1348 | public: |
1349 | using iterator_category = std::input_iterator_tag; |
1350 | using difference_type = ssize_t; |
1351 | using value_type = handle; |
1352 | using reference = const handle; // PR #3263 |
1353 | using pointer = const handle *; |
1354 | |
1355 | PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check) |
1356 | |
1357 | iterator &operator++() { |
1358 | advance(); |
1359 | return *this; |
1360 | } |
1361 | |
1362 | iterator operator++(int) { |
1363 | auto rv = *this; |
1364 | advance(); |
1365 | return rv; |
1366 | } |
1367 | |
1368 | // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 |
1369 | reference operator*() const { |
1370 | if (m_ptr && !value.ptr()) { |
1371 | auto &self = const_cast<iterator &>(*this); |
1372 | self.advance(); |
1373 | } |
1374 | return value; |
1375 | } |
1376 | |
1377 | pointer operator->() const { |
1378 | operator*(); |
1379 | return &value; |
1380 | } |
1381 | |
1382 | /** \rst |
1383 | The value which marks the end of the iteration. ``it == iterator::sentinel()`` |
1384 | is equivalent to catching ``StopIteration`` in Python. |
1385 | |
1386 | .. code-block:: cpp |
1387 | |
1388 | void foo(py::iterator it) { |
1389 | while (it != py::iterator::sentinel()) { |
1390 | // use `*it` |
1391 | ++it; |
1392 | } |
1393 | } |
1394 | \endrst */ |
1395 | static iterator sentinel() { return {}; } |
1396 | |
1397 | friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); } |
1398 | friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); } |
1399 | |
1400 | private: |
1401 | void advance() { |
1402 | value = reinterpret_steal<object>(PyIter_Next(m_ptr)); |
1403 | if (value.ptr() == nullptr && PyErr_Occurred()) { |
1404 | throw error_already_set(); |
1405 | } |
1406 | } |
1407 | |
1408 | private: |
1409 | object value = {}; |
1410 | }; |
1411 | |
1412 | class type : public object { |
1413 | public: |
1414 | PYBIND11_OBJECT(type, object, PyType_Check) |
1415 | |
1416 | /// Return a type handle from a handle or an object |
1417 | static handle handle_of(handle h) { return handle((PyObject *) Py_TYPE(h.ptr())); } |
1418 | |
1419 | /// Return a type object from a handle or an object |
1420 | static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); } |
1421 | |
1422 | // Defined in pybind11/cast.h |
1423 | /// Convert C++ type to handle if previously registered. Does not convert |
1424 | /// standard types, like int, float. etc. yet. |
1425 | /// See https://github.com/pybind/pybind11/issues/2486 |
1426 | template <typename T> |
1427 | static handle handle_of(); |
1428 | |
1429 | /// Convert C++ type to type if previously registered. Does not convert |
1430 | /// standard types, like int, float. etc. yet. |
1431 | /// See https://github.com/pybind/pybind11/issues/2486 |
1432 | template <typename T> |
1433 | static type of() { |
1434 | return type(type::handle_of<T>(), borrowed_t{}); |
1435 | } |
1436 | }; |
1437 | |
1438 | class iterable : public object { |
1439 | public: |
1440 | PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check) |
1441 | }; |
1442 | |
1443 | class bytes; |
1444 | |
1445 | class str : public object { |
1446 | public: |
1447 | PYBIND11_OBJECT_CVT(str, object, PYBIND11_STR_CHECK_FUN, raw_str) |
1448 | |
1449 | template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> |
1450 | str(const char *c, const SzType &n) |
1451 | : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) { |
1452 | if (!m_ptr) { |
1453 | if (PyErr_Occurred()) { |
1454 | throw error_already_set(); |
1455 | } |
1456 | pybind11_fail("Could not allocate string object!" ); |
1457 | } |
1458 | } |
1459 | |
1460 | // 'explicit' is explicitly omitted from the following constructors to allow implicit |
1461 | // conversion to py::str from C++ string-like objects |
1462 | // NOLINTNEXTLINE(google-explicit-constructor) |
1463 | str(const char *c = "" ) : object(PyUnicode_FromString(c), stolen_t{}) { |
1464 | if (!m_ptr) { |
1465 | if (PyErr_Occurred()) { |
1466 | throw error_already_set(); |
1467 | } |
1468 | pybind11_fail("Could not allocate string object!" ); |
1469 | } |
1470 | } |
1471 | |
1472 | // NOLINTNEXTLINE(google-explicit-constructor) |
1473 | str(const std::string &s) : str(s.data(), s.size()) {} |
1474 | |
1475 | #ifdef PYBIND11_HAS_STRING_VIEW |
1476 | // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521). |
1477 | template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0> |
1478 | // NOLINTNEXTLINE(google-explicit-constructor) |
1479 | str(T s) : str(s.data(), s.size()) {} |
1480 | |
1481 | # ifdef PYBIND11_HAS_U8STRING |
1482 | // reinterpret_cast here is safe (C++20 guarantees char8_t has the same size/alignment as char) |
1483 | // NOLINTNEXTLINE(google-explicit-constructor) |
1484 | str(std::u8string_view s) : str(reinterpret_cast<const char *>(s.data()), s.size()) {} |
1485 | # endif |
1486 | |
1487 | #endif |
1488 | |
1489 | explicit str(const bytes &b); |
1490 | |
1491 | /** \rst |
1492 | Return a string representation of the object. This is analogous to |
1493 | the ``str()`` function in Python. |
1494 | \endrst */ |
1495 | explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { |
1496 | if (!m_ptr) { |
1497 | throw error_already_set(); |
1498 | } |
1499 | } |
1500 | |
1501 | // NOLINTNEXTLINE(google-explicit-constructor) |
1502 | operator std::string() const { |
1503 | object temp = *this; |
1504 | if (PyUnicode_Check(m_ptr)) { |
1505 | temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr)); |
1506 | if (!temp) { |
1507 | throw error_already_set(); |
1508 | } |
1509 | } |
1510 | char *buffer = nullptr; |
1511 | ssize_t length = 0; |
1512 | if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) { |
1513 | throw error_already_set(); |
1514 | } |
1515 | return std::string(buffer, (size_t) length); |
1516 | } |
1517 | |
1518 | template <typename... Args> |
1519 | str format(Args &&...args) const { |
1520 | return attr("format" )(std::forward<Args>(args)...); |
1521 | } |
1522 | |
1523 | private: |
1524 | /// Return string representation -- always returns a new reference, even if already a str |
1525 | static PyObject *raw_str(PyObject *op) { |
1526 | PyObject *str_value = PyObject_Str(op); |
1527 | return str_value; |
1528 | } |
1529 | }; |
1530 | /// @} pytypes |
1531 | |
1532 | inline namespace literals { |
1533 | /** \rst |
1534 | String literal version of `str` |
1535 | \endrst */ |
1536 | inline str operator"" _s(const char *s, size_t size) { return {s, size}; } |
1537 | } // namespace literals |
1538 | |
1539 | /// \addtogroup pytypes |
1540 | /// @{ |
1541 | class bytes : public object { |
1542 | public: |
1543 | PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK) |
1544 | |
1545 | // Allow implicit conversion: |
1546 | // NOLINTNEXTLINE(google-explicit-constructor) |
1547 | bytes(const char *c = "" ) : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) { |
1548 | if (!m_ptr) { |
1549 | pybind11_fail("Could not allocate bytes object!" ); |
1550 | } |
1551 | } |
1552 | |
1553 | template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> |
1554 | bytes(const char *c, const SzType &n) |
1555 | : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, ssize_t_cast(n)), stolen_t{}) { |
1556 | if (!m_ptr) { |
1557 | pybind11_fail("Could not allocate bytes object!" ); |
1558 | } |
1559 | } |
1560 | |
1561 | // Allow implicit conversion: |
1562 | // NOLINTNEXTLINE(google-explicit-constructor) |
1563 | bytes(const std::string &s) : bytes(s.data(), s.size()) {} |
1564 | |
1565 | explicit bytes(const pybind11::str &s); |
1566 | |
1567 | // NOLINTNEXTLINE(google-explicit-constructor) |
1568 | operator std::string() const { return string_op<std::string>(); } |
1569 | |
1570 | #ifdef PYBIND11_HAS_STRING_VIEW |
1571 | // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521). |
1572 | template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0> |
1573 | // NOLINTNEXTLINE(google-explicit-constructor) |
1574 | bytes(T s) : bytes(s.data(), s.size()) {} |
1575 | |
1576 | // Obtain a string view that views the current `bytes` buffer value. Note that this is only |
1577 | // valid so long as the `bytes` instance remains alive and so generally should not outlive the |
1578 | // lifetime of the `bytes` instance. |
1579 | // NOLINTNEXTLINE(google-explicit-constructor) |
1580 | operator std::string_view() const { return string_op<std::string_view>(); } |
1581 | #endif |
1582 | private: |
1583 | template <typename T> |
1584 | T string_op() const { |
1585 | char *buffer = nullptr; |
1586 | ssize_t length = 0; |
1587 | if (PyBytes_AsStringAndSize(m_ptr, &buffer, &length) != 0) { |
1588 | throw error_already_set(); |
1589 | } |
1590 | return {buffer, static_cast<size_t>(length)}; |
1591 | } |
1592 | }; |
1593 | // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors |
1594 | // are included in the doxygen group; close here and reopen after as a workaround |
1595 | /// @} pytypes |
1596 | |
1597 | inline bytes::bytes(const pybind11::str &s) { |
1598 | object temp = s; |
1599 | if (PyUnicode_Check(s.ptr())) { |
1600 | temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr())); |
1601 | if (!temp) { |
1602 | throw error_already_set(); |
1603 | } |
1604 | } |
1605 | char *buffer = nullptr; |
1606 | ssize_t length = 0; |
1607 | if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) { |
1608 | throw error_already_set(); |
1609 | } |
1610 | auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length)); |
1611 | if (!obj) { |
1612 | pybind11_fail("Could not allocate bytes object!" ); |
1613 | } |
1614 | m_ptr = obj.release().ptr(); |
1615 | } |
1616 | |
1617 | inline str::str(const bytes &b) { |
1618 | char *buffer = nullptr; |
1619 | ssize_t length = 0; |
1620 | if (PyBytes_AsStringAndSize(b.ptr(), &buffer, &length) != 0) { |
1621 | throw error_already_set(); |
1622 | } |
1623 | auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, length)); |
1624 | if (!obj) { |
1625 | if (PyErr_Occurred()) { |
1626 | throw error_already_set(); |
1627 | } |
1628 | pybind11_fail("Could not allocate string object!" ); |
1629 | } |
1630 | m_ptr = obj.release().ptr(); |
1631 | } |
1632 | |
1633 | /// \addtogroup pytypes |
1634 | /// @{ |
1635 | class bytearray : public object { |
1636 | public: |
1637 | PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject) |
1638 | |
1639 | template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> |
1640 | bytearray(const char *c, const SzType &n) |
1641 | : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) { |
1642 | if (!m_ptr) { |
1643 | pybind11_fail("Could not allocate bytearray object!" ); |
1644 | } |
1645 | } |
1646 | |
1647 | bytearray() : bytearray("" , 0) {} |
1648 | |
1649 | explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) {} |
1650 | |
1651 | size_t size() const { return static_cast<size_t>(PyByteArray_Size(m_ptr)); } |
1652 | |
1653 | explicit operator std::string() const { |
1654 | char *buffer = PyByteArray_AS_STRING(m_ptr); |
1655 | ssize_t size = PyByteArray_GET_SIZE(m_ptr); |
1656 | return std::string(buffer, static_cast<size_t>(size)); |
1657 | } |
1658 | }; |
1659 | // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors |
1660 | // are included in the doxygen group; close here and reopen after as a workaround |
1661 | /// @} pytypes |
1662 | |
1663 | /// \addtogroup pytypes |
1664 | /// @{ |
1665 | class none : public object { |
1666 | public: |
1667 | PYBIND11_OBJECT(none, object, detail::PyNone_Check) |
1668 | none() : object(Py_None, borrowed_t{}) {} |
1669 | }; |
1670 | |
1671 | class ellipsis : public object { |
1672 | public: |
1673 | PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check) |
1674 | ellipsis() : object(Py_Ellipsis, borrowed_t{}) {} |
1675 | }; |
1676 | |
1677 | class bool_ : public object { |
1678 | public: |
1679 | PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool) |
1680 | bool_() : object(Py_False, borrowed_t{}) {} |
1681 | // Allow implicit conversion from and to `bool`: |
1682 | // NOLINTNEXTLINE(google-explicit-constructor) |
1683 | bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) {} |
1684 | // NOLINTNEXTLINE(google-explicit-constructor) |
1685 | operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; } |
1686 | |
1687 | private: |
1688 | /// Return the truth value of an object -- always returns a new reference |
1689 | static PyObject *raw_bool(PyObject *op) { |
1690 | const auto value = PyObject_IsTrue(op); |
1691 | if (value == -1) { |
1692 | return nullptr; |
1693 | } |
1694 | return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr(); |
1695 | } |
1696 | }; |
1697 | |
1698 | PYBIND11_NAMESPACE_BEGIN(detail) |
1699 | // Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1; |
1700 | // otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned). |
1701 | // (The distinction is critically important when casting a returned -1 error value to some other |
1702 | // unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes). |
1703 | template <typename Unsigned> |
1704 | Unsigned as_unsigned(PyObject *o) { |
1705 | if (PYBIND11_SILENCE_MSVC_C4127(sizeof(Unsigned) <= sizeof(unsigned long))) { |
1706 | unsigned long v = PyLong_AsUnsignedLong(o); |
1707 | return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v; |
1708 | } |
1709 | unsigned long long v = PyLong_AsUnsignedLongLong(o); |
1710 | return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v; |
1711 | } |
1712 | PYBIND11_NAMESPACE_END(detail) |
1713 | |
1714 | class int_ : public object { |
1715 | public: |
1716 | PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long) |
1717 | int_() : object(PyLong_FromLong(0), stolen_t{}) {} |
1718 | // Allow implicit conversion from C++ integral types: |
1719 | template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0> |
1720 | // NOLINTNEXTLINE(google-explicit-constructor) |
1721 | int_(T value) { |
1722 | if (PYBIND11_SILENCE_MSVC_C4127(sizeof(T) <= sizeof(long))) { |
1723 | if (std::is_signed<T>::value) { |
1724 | m_ptr = PyLong_FromLong((long) value); |
1725 | } else { |
1726 | m_ptr = PyLong_FromUnsignedLong((unsigned long) value); |
1727 | } |
1728 | } else { |
1729 | if (std::is_signed<T>::value) { |
1730 | m_ptr = PyLong_FromLongLong((long long) value); |
1731 | } else { |
1732 | m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value); |
1733 | } |
1734 | } |
1735 | if (!m_ptr) { |
1736 | pybind11_fail("Could not allocate int object!" ); |
1737 | } |
1738 | } |
1739 | |
1740 | template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0> |
1741 | // NOLINTNEXTLINE(google-explicit-constructor) |
1742 | operator T() const { |
1743 | return std::is_unsigned<T>::value ? detail::as_unsigned<T>(m_ptr) |
1744 | : sizeof(T) <= sizeof(long) ? (T) PyLong_AsLong(m_ptr) |
1745 | : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr); |
1746 | } |
1747 | }; |
1748 | |
1749 | class float_ : public object { |
1750 | public: |
1751 | PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float) |
1752 | // Allow implicit conversion from float/double: |
1753 | // NOLINTNEXTLINE(google-explicit-constructor) |
1754 | float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) { |
1755 | if (!m_ptr) { |
1756 | pybind11_fail("Could not allocate float object!" ); |
1757 | } |
1758 | } |
1759 | // NOLINTNEXTLINE(google-explicit-constructor) |
1760 | float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) { |
1761 | if (!m_ptr) { |
1762 | pybind11_fail("Could not allocate float object!" ); |
1763 | } |
1764 | } |
1765 | // NOLINTNEXTLINE(google-explicit-constructor) |
1766 | operator float() const { return (float) PyFloat_AsDouble(m_ptr); } |
1767 | // NOLINTNEXTLINE(google-explicit-constructor) |
1768 | operator double() const { return (double) PyFloat_AsDouble(m_ptr); } |
1769 | }; |
1770 | |
1771 | class weakref : public object { |
1772 | public: |
1773 | PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref) |
1774 | explicit weakref(handle obj, handle callback = {}) |
1775 | : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) { |
1776 | if (!m_ptr) { |
1777 | if (PyErr_Occurred()) { |
1778 | throw error_already_set(); |
1779 | } |
1780 | pybind11_fail("Could not allocate weak reference!" ); |
1781 | } |
1782 | } |
1783 | |
1784 | private: |
1785 | static PyObject *raw_weakref(PyObject *o) { return PyWeakref_NewRef(o, nullptr); } |
1786 | }; |
1787 | |
1788 | class slice : public object { |
1789 | public: |
1790 | PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check) |
1791 | slice(handle start, handle stop, handle step) |
1792 | : object(PySlice_New(start.ptr(), stop.ptr(), step.ptr()), stolen_t{}) { |
1793 | if (!m_ptr) { |
1794 | pybind11_fail("Could not allocate slice object!" ); |
1795 | } |
1796 | } |
1797 | |
1798 | #ifdef PYBIND11_HAS_OPTIONAL |
1799 | slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t> step) |
1800 | : slice(index_to_object(start), index_to_object(stop), index_to_object(step)) {} |
1801 | #else |
1802 | slice(ssize_t start_, ssize_t stop_, ssize_t step_) |
1803 | : slice(int_(start_), int_(stop_), int_(step_)) {} |
1804 | #endif |
1805 | |
1806 | bool |
1807 | compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const { |
1808 | return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr, |
1809 | (ssize_t) length, |
1810 | (ssize_t *) start, |
1811 | (ssize_t *) stop, |
1812 | (ssize_t *) step, |
1813 | (ssize_t *) slicelength) |
1814 | == 0; |
1815 | } |
1816 | bool compute( |
1817 | ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const { |
1818 | return PySlice_GetIndicesEx( |
1819 | (PYBIND11_SLICE_OBJECT *) m_ptr, length, start, stop, step, slicelength) |
1820 | == 0; |
1821 | } |
1822 | |
1823 | private: |
1824 | template <typename T> |
1825 | static object index_to_object(T index) { |
1826 | return index ? object(int_(*index)) : object(none()); |
1827 | } |
1828 | }; |
1829 | |
1830 | class capsule : public object { |
1831 | public: |
1832 | PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact) |
1833 | PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()" ) |
1834 | capsule(PyObject *ptr, bool is_borrowed) |
1835 | : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) {} |
1836 | |
1837 | explicit capsule(const void *value, |
1838 | const char *name = nullptr, |
1839 | PyCapsule_Destructor destructor = nullptr) |
1840 | : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) { |
1841 | if (!m_ptr) { |
1842 | throw error_already_set(); |
1843 | } |
1844 | } |
1845 | |
1846 | PYBIND11_DEPRECATED("Please use the ctor with value, name, destructor args" ) |
1847 | capsule(const void *value, PyCapsule_Destructor destructor) |
1848 | : object(PyCapsule_New(const_cast<void *>(value), nullptr, destructor), stolen_t{}) { |
1849 | if (!m_ptr) { |
1850 | throw error_already_set(); |
1851 | } |
1852 | } |
1853 | |
1854 | capsule(const void *value, void (*destructor)(void *)) { |
1855 | m_ptr = PyCapsule_New(const_cast<void *>(value), nullptr, [](PyObject *o) { |
1856 | // guard if destructor called while err indicator is set |
1857 | error_scope error_guard; |
1858 | auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o)); |
1859 | if (destructor == nullptr && PyErr_Occurred()) { |
1860 | throw error_already_set(); |
1861 | } |
1862 | const char *name = get_name_in_error_scope(o); |
1863 | void *ptr = PyCapsule_GetPointer(o, name); |
1864 | if (ptr == nullptr) { |
1865 | throw error_already_set(); |
1866 | } |
1867 | |
1868 | if (destructor != nullptr) { |
1869 | destructor(ptr); |
1870 | } |
1871 | }); |
1872 | |
1873 | if (!m_ptr || PyCapsule_SetContext(m_ptr, reinterpret_cast<void *>(destructor)) != 0) { |
1874 | throw error_already_set(); |
1875 | } |
1876 | } |
1877 | |
1878 | explicit capsule(void (*destructor)()) { |
1879 | m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) { |
1880 | const char *name = get_name_in_error_scope(o); |
1881 | auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, name)); |
1882 | if (destructor == nullptr) { |
1883 | throw error_already_set(); |
1884 | } |
1885 | destructor(); |
1886 | }); |
1887 | |
1888 | if (!m_ptr) { |
1889 | throw error_already_set(); |
1890 | } |
1891 | } |
1892 | |
1893 | template <typename T> |
1894 | operator T *() const { // NOLINT(google-explicit-constructor) |
1895 | return get_pointer<T>(); |
1896 | } |
1897 | |
1898 | /// Get the pointer the capsule holds. |
1899 | template <typename T = void> |
1900 | T *get_pointer() const { |
1901 | const auto *name = this->name(); |
1902 | T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name)); |
1903 | if (!result) { |
1904 | throw error_already_set(); |
1905 | } |
1906 | return result; |
1907 | } |
1908 | |
1909 | /// Replaces a capsule's pointer *without* calling the destructor on the existing one. |
1910 | void set_pointer(const void *value) { |
1911 | if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0) { |
1912 | throw error_already_set(); |
1913 | } |
1914 | } |
1915 | |
1916 | const char *name() const { |
1917 | const char *name = PyCapsule_GetName(m_ptr); |
1918 | if ((name == nullptr) && PyErr_Occurred()) { |
1919 | throw error_already_set(); |
1920 | } |
1921 | return name; |
1922 | } |
1923 | |
1924 | /// Replaces a capsule's name *without* calling the destructor on the existing one. |
1925 | void set_name(const char *new_name) { |
1926 | if (PyCapsule_SetName(m_ptr, new_name) != 0) { |
1927 | throw error_already_set(); |
1928 | } |
1929 | } |
1930 | |
1931 | private: |
1932 | static const char *get_name_in_error_scope(PyObject *o) { |
1933 | error_scope error_guard; |
1934 | |
1935 | const char *name = PyCapsule_GetName(o); |
1936 | if ((name == nullptr) && PyErr_Occurred()) { |
1937 | // write out and consume error raised by call to PyCapsule_GetName |
1938 | PyErr_WriteUnraisable(o); |
1939 | } |
1940 | |
1941 | return name; |
1942 | } |
1943 | }; |
1944 | |
1945 | class tuple : public object { |
1946 | public: |
1947 | PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple) |
1948 | template <typename SzType = ssize_t, |
1949 | detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> |
1950 | // Some compilers generate link errors when using `const SzType &` here: |
1951 | explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) { |
1952 | if (!m_ptr) { |
1953 | pybind11_fail("Could not allocate tuple object!" ); |
1954 | } |
1955 | } |
1956 | size_t size() const { return (size_t) PyTuple_Size(m_ptr); } |
1957 | bool empty() const { return size() == 0; } |
1958 | detail::tuple_accessor operator[](size_t index) const { return {*this, index}; } |
1959 | template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0> |
1960 | detail::item_accessor operator[](T &&o) const { |
1961 | return object::operator[](std::forward<T>(o)); |
1962 | } |
1963 | detail::tuple_iterator begin() const { return {*this, 0}; } |
1964 | detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; } |
1965 | }; |
1966 | |
1967 | // We need to put this into a separate function because the Intel compiler |
1968 | // fails to compile enable_if_t<all_of<is_keyword_or_ds<Args>...>::value> part below |
1969 | // (tested with ICC 2021.1 Beta 20200827). |
1970 | template <typename... Args> |
1971 | constexpr bool args_are_all_keyword_or_ds() { |
1972 | return detail::all_of<detail::is_keyword_or_ds<Args>...>::value; |
1973 | } |
1974 | |
1975 | class dict : public object { |
1976 | public: |
1977 | PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict) |
1978 | dict() : object(PyDict_New(), stolen_t{}) { |
1979 | if (!m_ptr) { |
1980 | pybind11_fail("Could not allocate dict object!" ); |
1981 | } |
1982 | } |
1983 | template <typename... Args, |
1984 | typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>, |
1985 | // MSVC workaround: it can't compile an out-of-line definition, so defer the |
1986 | // collector |
1987 | typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>> |
1988 | explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) {} |
1989 | |
1990 | size_t size() const { return (size_t) PyDict_Size(m_ptr); } |
1991 | bool empty() const { return size() == 0; } |
1992 | detail::dict_iterator begin() const { return {*this, 0}; } |
1993 | detail::dict_iterator end() const { return {}; } |
1994 | void clear() /* py-non-const */ { PyDict_Clear(ptr()); } |
1995 | template <typename T> |
1996 | bool contains(T &&key) const { |
1997 | auto result = PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr()); |
1998 | if (result == -1) { |
1999 | throw error_already_set(); |
2000 | } |
2001 | return result == 1; |
2002 | } |
2003 | |
2004 | private: |
2005 | /// Call the `dict` Python type -- always returns a new reference |
2006 | static PyObject *raw_dict(PyObject *op) { |
2007 | if (PyDict_Check(op)) { |
2008 | return handle(op).inc_ref().ptr(); |
2009 | } |
2010 | return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr); |
2011 | } |
2012 | }; |
2013 | |
2014 | class sequence : public object { |
2015 | public: |
2016 | PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check) |
2017 | size_t size() const { |
2018 | ssize_t result = PySequence_Size(m_ptr); |
2019 | if (result == -1) { |
2020 | throw error_already_set(); |
2021 | } |
2022 | return (size_t) result; |
2023 | } |
2024 | bool empty() const { return size() == 0; } |
2025 | detail::sequence_accessor operator[](size_t index) const { return {*this, index}; } |
2026 | template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0> |
2027 | detail::item_accessor operator[](T &&o) const { |
2028 | return object::operator[](std::forward<T>(o)); |
2029 | } |
2030 | detail::sequence_iterator begin() const { return {*this, 0}; } |
2031 | detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; } |
2032 | }; |
2033 | |
2034 | class list : public object { |
2035 | public: |
2036 | PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List) |
2037 | template <typename SzType = ssize_t, |
2038 | detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> |
2039 | // Some compilers generate link errors when using `const SzType &` here: |
2040 | explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) { |
2041 | if (!m_ptr) { |
2042 | pybind11_fail("Could not allocate list object!" ); |
2043 | } |
2044 | } |
2045 | size_t size() const { return (size_t) PyList_Size(m_ptr); } |
2046 | bool empty() const { return size() == 0; } |
2047 | detail::list_accessor operator[](size_t index) const { return {*this, index}; } |
2048 | template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0> |
2049 | detail::item_accessor operator[](T &&o) const { |
2050 | return object::operator[](std::forward<T>(o)); |
2051 | } |
2052 | detail::list_iterator begin() const { return {*this, 0}; } |
2053 | detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; } |
2054 | template <typename T> |
2055 | void append(T &&val) /* py-non-const */ { |
2056 | if (PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) != 0) { |
2057 | throw error_already_set(); |
2058 | } |
2059 | } |
2060 | template <typename IdxType, |
2061 | typename ValType, |
2062 | detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> |
2063 | void insert(const IdxType &index, ValType &&val) /* py-non-const */ { |
2064 | if (PyList_Insert(m_ptr, |
2065 | ssize_t_cast(index), |
2066 | detail::object_or_cast(std::forward<ValType>(val)).ptr()) |
2067 | != 0) { |
2068 | throw error_already_set(); |
2069 | } |
2070 | } |
2071 | }; |
2072 | |
2073 | class args : public tuple { |
2074 | PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) |
2075 | }; |
2076 | class kwargs : public dict { |
2077 | PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check) |
2078 | }; |
2079 | |
2080 | class anyset : public object { |
2081 | public: |
2082 | PYBIND11_OBJECT(anyset, object, PyAnySet_Check) |
2083 | size_t size() const { return static_cast<size_t>(PySet_Size(m_ptr)); } |
2084 | bool empty() const { return size() == 0; } |
2085 | template <typename T> |
2086 | bool contains(T &&val) const { |
2087 | auto result = PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()); |
2088 | if (result == -1) { |
2089 | throw error_already_set(); |
2090 | } |
2091 | return result == 1; |
2092 | } |
2093 | }; |
2094 | |
2095 | class set : public anyset { |
2096 | public: |
2097 | PYBIND11_OBJECT_CVT(set, anyset, PySet_Check, PySet_New) |
2098 | set() : anyset(PySet_New(nullptr), stolen_t{}) { |
2099 | if (!m_ptr) { |
2100 | pybind11_fail("Could not allocate set object!" ); |
2101 | } |
2102 | } |
2103 | template <typename T> |
2104 | bool add(T &&val) /* py-non-const */ { |
2105 | return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0; |
2106 | } |
2107 | void clear() /* py-non-const */ { PySet_Clear(m_ptr); } |
2108 | }; |
2109 | |
2110 | class frozenset : public anyset { |
2111 | public: |
2112 | PYBIND11_OBJECT_CVT(frozenset, anyset, PyFrozenSet_Check, PyFrozenSet_New) |
2113 | }; |
2114 | |
2115 | class function : public object { |
2116 | public: |
2117 | PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check) |
2118 | handle cpp_function() const { |
2119 | handle fun = detail::get_function(m_ptr); |
2120 | if (fun && PyCFunction_Check(fun.ptr())) { |
2121 | return fun; |
2122 | } |
2123 | return handle(); |
2124 | } |
2125 | bool is_cpp_function() const { return (bool) cpp_function(); } |
2126 | }; |
2127 | |
2128 | class staticmethod : public object { |
2129 | public: |
2130 | PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New) |
2131 | }; |
2132 | |
2133 | class buffer : public object { |
2134 | public: |
2135 | PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer) |
2136 | |
2137 | buffer_info request(bool writable = false) const { |
2138 | int flags = PyBUF_STRIDES | PyBUF_FORMAT; |
2139 | if (writable) { |
2140 | flags |= PyBUF_WRITABLE; |
2141 | } |
2142 | auto *view = new Py_buffer(); |
2143 | if (PyObject_GetBuffer(m_ptr, view, flags) != 0) { |
2144 | delete view; |
2145 | throw error_already_set(); |
2146 | } |
2147 | return buffer_info(view); |
2148 | } |
2149 | }; |
2150 | |
2151 | class memoryview : public object { |
2152 | public: |
2153 | PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject) |
2154 | |
2155 | /** \rst |
2156 | Creates ``memoryview`` from ``buffer_info``. |
2157 | |
2158 | ``buffer_info`` must be created from ``buffer::request()``. Otherwise |
2159 | throws an exception. |
2160 | |
2161 | For creating a ``memoryview`` from objects that support buffer protocol, |
2162 | use ``memoryview(const object& obj)`` instead of this constructor. |
2163 | \endrst */ |
2164 | explicit memoryview(const buffer_info &info) { |
2165 | if (!info.view()) { |
2166 | pybind11_fail("Prohibited to create memoryview without Py_buffer" ); |
2167 | } |
2168 | // Note: PyMemoryView_FromBuffer never increments obj reference. |
2169 | m_ptr = (info.view()->obj) ? PyMemoryView_FromObject(info.view()->obj) |
2170 | : PyMemoryView_FromBuffer(info.view()); |
2171 | if (!m_ptr) { |
2172 | pybind11_fail("Unable to create memoryview from buffer descriptor" ); |
2173 | } |
2174 | } |
2175 | |
2176 | /** \rst |
2177 | Creates ``memoryview`` from static buffer. |
2178 | |
2179 | This method is meant for providing a ``memoryview`` for C/C++ buffer not |
2180 | managed by Python. The caller is responsible for managing the lifetime |
2181 | of ``ptr`` and ``format``, which MUST outlive the memoryview constructed |
2182 | here. |
2183 | |
2184 | See also: Python C API documentation for `PyMemoryView_FromBuffer`_. |
2185 | |
2186 | .. _PyMemoryView_FromBuffer: |
2187 | https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer |
2188 | |
2189 | :param ptr: Pointer to the buffer. |
2190 | :param itemsize: Byte size of an element. |
2191 | :param format: Pointer to the null-terminated format string. For |
2192 | homogeneous Buffers, this should be set to |
2193 | ``format_descriptor<T>::value``. |
2194 | :param shape: Shape of the tensor (1 entry per dimension). |
2195 | :param strides: Number of bytes between adjacent entries (for each |
2196 | per dimension). |
2197 | :param readonly: Flag to indicate if the underlying storage may be |
2198 | written to. |
2199 | \endrst */ |
2200 | static memoryview from_buffer(void *ptr, |
2201 | ssize_t itemsize, |
2202 | const char *format, |
2203 | detail::any_container<ssize_t> shape, |
2204 | detail::any_container<ssize_t> strides, |
2205 | bool readonly = false); |
2206 | |
2207 | static memoryview from_buffer(const void *ptr, |
2208 | ssize_t itemsize, |
2209 | const char *format, |
2210 | detail::any_container<ssize_t> shape, |
2211 | detail::any_container<ssize_t> strides) { |
2212 | return memoryview::from_buffer( |
2213 | const_cast<void *>(ptr), itemsize, format, std::move(shape), std::move(strides), true); |
2214 | } |
2215 | |
2216 | template <typename T> |
2217 | static memoryview from_buffer(T *ptr, |
2218 | detail::any_container<ssize_t> shape, |
2219 | detail::any_container<ssize_t> strides, |
2220 | bool readonly = false) { |
2221 | return memoryview::from_buffer(reinterpret_cast<void *>(ptr), |
2222 | sizeof(T), |
2223 | format_descriptor<T>::value, |
2224 | std::move(shape), |
2225 | std::move(strides), |
2226 | readonly); |
2227 | } |
2228 | |
2229 | template <typename T> |
2230 | static memoryview from_buffer(const T *ptr, |
2231 | detail::any_container<ssize_t> shape, |
2232 | detail::any_container<ssize_t> strides) { |
2233 | return memoryview::from_buffer( |
2234 | const_cast<T *>(ptr), std::move(shape), std::move(strides), true); |
2235 | } |
2236 | |
2237 | /** \rst |
2238 | Creates ``memoryview`` from static memory. |
2239 | |
2240 | This method is meant for providing a ``memoryview`` for C/C++ buffer not |
2241 | managed by Python. The caller is responsible for managing the lifetime |
2242 | of ``mem``, which MUST outlive the memoryview constructed here. |
2243 | |
2244 | See also: Python C API documentation for `PyMemoryView_FromBuffer`_. |
2245 | |
2246 | .. _PyMemoryView_FromMemory: |
2247 | https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory |
2248 | \endrst */ |
2249 | static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) { |
2250 | PyObject *ptr = PyMemoryView_FromMemory( |
2251 | reinterpret_cast<char *>(mem), size, (readonly) ? PyBUF_READ : PyBUF_WRITE); |
2252 | if (!ptr) { |
2253 | pybind11_fail("Could not allocate memoryview object!" ); |
2254 | } |
2255 | return memoryview(object(ptr, stolen_t{})); |
2256 | } |
2257 | |
2258 | static memoryview from_memory(const void *mem, ssize_t size) { |
2259 | return memoryview::from_memory(const_cast<void *>(mem), size, true); |
2260 | } |
2261 | |
2262 | #ifdef PYBIND11_HAS_STRING_VIEW |
2263 | static memoryview from_memory(std::string_view mem) { |
2264 | return from_memory(const_cast<char *>(mem.data()), static_cast<ssize_t>(mem.size()), true); |
2265 | } |
2266 | #endif |
2267 | }; |
2268 | |
2269 | /// @cond DUPLICATE |
2270 | inline memoryview memoryview::from_buffer(void *ptr, |
2271 | ssize_t itemsize, |
2272 | const char *format, |
2273 | detail::any_container<ssize_t> shape, |
2274 | detail::any_container<ssize_t> strides, |
2275 | bool readonly) { |
2276 | size_t ndim = shape->size(); |
2277 | if (ndim != strides->size()) { |
2278 | pybind11_fail("memoryview: shape length doesn't match strides length" ); |
2279 | } |
2280 | ssize_t size = ndim != 0u ? 1 : 0; |
2281 | for (size_t i = 0; i < ndim; ++i) { |
2282 | size *= (*shape)[i]; |
2283 | } |
2284 | Py_buffer view; |
2285 | view.buf = ptr; |
2286 | view.obj = nullptr; |
2287 | view.len = size * itemsize; |
2288 | view.readonly = static_cast<int>(readonly); |
2289 | view.itemsize = itemsize; |
2290 | view.format = const_cast<char *>(format); |
2291 | view.ndim = static_cast<int>(ndim); |
2292 | view.shape = shape->data(); |
2293 | view.strides = strides->data(); |
2294 | view.suboffsets = nullptr; |
2295 | view.internal = nullptr; |
2296 | PyObject *obj = PyMemoryView_FromBuffer(&view); |
2297 | if (!obj) { |
2298 | throw error_already_set(); |
2299 | } |
2300 | return memoryview(object(obj, stolen_t{})); |
2301 | } |
2302 | /// @endcond |
2303 | /// @} pytypes |
2304 | |
2305 | /// \addtogroup python_builtins |
2306 | /// @{ |
2307 | |
2308 | /// Get the length of a Python object. |
2309 | inline size_t len(handle h) { |
2310 | ssize_t result = PyObject_Length(h.ptr()); |
2311 | if (result < 0) { |
2312 | throw error_already_set(); |
2313 | } |
2314 | return (size_t) result; |
2315 | } |
2316 | |
2317 | /// Get the length hint of a Python object. |
2318 | /// Returns 0 when this cannot be determined. |
2319 | inline size_t len_hint(handle h) { |
2320 | ssize_t result = PyObject_LengthHint(h.ptr(), 0); |
2321 | if (result < 0) { |
2322 | // Sometimes a length can't be determined at all (eg generators) |
2323 | // In which case simply return 0 |
2324 | PyErr_Clear(); |
2325 | return 0; |
2326 | } |
2327 | return (size_t) result; |
2328 | } |
2329 | |
2330 | inline str repr(handle h) { |
2331 | PyObject *str_value = PyObject_Repr(h.ptr()); |
2332 | if (!str_value) { |
2333 | throw error_already_set(); |
2334 | } |
2335 | return reinterpret_steal<str>(str_value); |
2336 | } |
2337 | |
2338 | inline iterator iter(handle obj) { |
2339 | PyObject *result = PyObject_GetIter(obj.ptr()); |
2340 | if (!result) { |
2341 | throw error_already_set(); |
2342 | } |
2343 | return reinterpret_steal<iterator>(result); |
2344 | } |
2345 | /// @} python_builtins |
2346 | |
2347 | PYBIND11_NAMESPACE_BEGIN(detail) |
2348 | template <typename D> |
2349 | iterator object_api<D>::begin() const { |
2350 | return iter(derived()); |
2351 | } |
2352 | template <typename D> |
2353 | iterator object_api<D>::end() const { |
2354 | return iterator::sentinel(); |
2355 | } |
2356 | template <typename D> |
2357 | item_accessor object_api<D>::operator[](handle key) const { |
2358 | return {derived(), reinterpret_borrow<object>(key)}; |
2359 | } |
2360 | template <typename D> |
2361 | item_accessor object_api<D>::operator[](object &&key) const { |
2362 | return {derived(), std::move(key)}; |
2363 | } |
2364 | template <typename D> |
2365 | item_accessor object_api<D>::operator[](const char *key) const { |
2366 | return {derived(), pybind11::str(key)}; |
2367 | } |
2368 | template <typename D> |
2369 | obj_attr_accessor object_api<D>::attr(handle key) const { |
2370 | return {derived(), reinterpret_borrow<object>(key)}; |
2371 | } |
2372 | template <typename D> |
2373 | obj_attr_accessor object_api<D>::attr(object &&key) const { |
2374 | return {derived(), std::move(key)}; |
2375 | } |
2376 | template <typename D> |
2377 | str_attr_accessor object_api<D>::attr(const char *key) const { |
2378 | return {derived(), key}; |
2379 | } |
2380 | template <typename D> |
2381 | args_proxy object_api<D>::operator*() const { |
2382 | return args_proxy(derived().ptr()); |
2383 | } |
2384 | template <typename D> |
2385 | template <typename T> |
2386 | bool object_api<D>::contains(T &&item) const { |
2387 | return attr("__contains__" )(std::forward<T>(item)).template cast<bool>(); |
2388 | } |
2389 | |
2390 | template <typename D> |
2391 | pybind11::str object_api<D>::str() const { |
2392 | return pybind11::str(derived()); |
2393 | } |
2394 | |
2395 | template <typename D> |
2396 | str_attr_accessor object_api<D>::doc() const { |
2397 | return attr("__doc__" ); |
2398 | } |
2399 | |
2400 | template <typename D> |
2401 | handle object_api<D>::get_type() const { |
2402 | return type::handle_of(derived()); |
2403 | } |
2404 | |
2405 | template <typename D> |
2406 | bool object_api<D>::rich_compare(object_api const &other, int value) const { |
2407 | int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value); |
2408 | if (rv == -1) { |
2409 | throw error_already_set(); |
2410 | } |
2411 | return rv == 1; |
2412 | } |
2413 | |
2414 | #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \ |
2415 | template <typename D> \ |
2416 | object object_api<D>::op() const { \ |
2417 | object result = reinterpret_steal<object>(fn(derived().ptr())); \ |
2418 | if (!result.ptr()) \ |
2419 | throw error_already_set(); \ |
2420 | return result; \ |
2421 | } |
2422 | |
2423 | #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \ |
2424 | template <typename D> \ |
2425 | object object_api<D>::op(object_api const &other) const { \ |
2426 | object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \ |
2427 | if (!result.ptr()) \ |
2428 | throw error_already_set(); \ |
2429 | return result; \ |
2430 | } |
2431 | |
2432 | #define PYBIND11_MATH_OPERATOR_BINARY_INPLACE(iop, fn) \ |
2433 | template <typename D> \ |
2434 | object object_api<D>::iop(object_api const &other) { \ |
2435 | object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \ |
2436 | if (!result.ptr()) \ |
2437 | throw error_already_set(); \ |
2438 | return result; \ |
2439 | } |
2440 | |
2441 | PYBIND11_MATH_OPERATOR_UNARY(operator~, PyNumber_Invert) |
2442 | PYBIND11_MATH_OPERATOR_UNARY(operator-, PyNumber_Negative) |
2443 | PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add) |
2444 | PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator+=, PyNumber_InPlaceAdd) |
2445 | PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract) |
2446 | PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator-=, PyNumber_InPlaceSubtract) |
2447 | PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply) |
2448 | PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator*=, PyNumber_InPlaceMultiply) |
2449 | PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide) |
2450 | PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator/=, PyNumber_InPlaceTrueDivide) |
2451 | PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or) |
2452 | PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator|=, PyNumber_InPlaceOr) |
2453 | PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And) |
2454 | PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator&=, PyNumber_InPlaceAnd) |
2455 | PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor) |
2456 | PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator^=, PyNumber_InPlaceXor) |
2457 | PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift) |
2458 | PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator<<=, PyNumber_InPlaceLshift) |
2459 | PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift) |
2460 | PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator>>=, PyNumber_InPlaceRshift) |
2461 | |
2462 | #undef PYBIND11_MATH_OPERATOR_UNARY |
2463 | #undef PYBIND11_MATH_OPERATOR_BINARY |
2464 | #undef PYBIND11_MATH_OPERATOR_BINARY_INPLACE |
2465 | |
2466 | PYBIND11_NAMESPACE_END(detail) |
2467 | PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) |
2468 | |