File indexing completed on 2025-02-16 05:12:19
0001 /* 0002 pybind11/pytypes.h: Convenience wrapper classes for basic Python types 0003 0004 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 0005 0006 All rights reserved. Use of this source code is governed by a 0007 BSD-style license that can be found in the LICENSE file. 0008 */ 0009 0010 #pragma once 0011 0012 #include "detail/common.h" 0013 #include "buffer_info.h" 0014 #include <utility> 0015 #include <type_traits> 0016 0017 #if defined(PYBIND11_HAS_OPTIONAL) 0018 # include <optional> 0019 #endif 0020 0021 #ifdef PYBIND11_HAS_STRING_VIEW 0022 # include <string_view> 0023 #endif 0024 0025 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 0026 0027 /* A few forward declarations */ 0028 class handle; class object; 0029 class str; class iterator; 0030 class type; 0031 struct arg; struct arg_v; 0032 0033 PYBIND11_NAMESPACE_BEGIN(detail) 0034 class args_proxy; 0035 bool isinstance_generic(handle obj, const std::type_info &tp); 0036 0037 // Accessor forward declarations 0038 template <typename Policy> class accessor; 0039 namespace accessor_policies { 0040 struct obj_attr; 0041 struct str_attr; 0042 struct generic_item; 0043 struct sequence_item; 0044 struct list_item; 0045 struct tuple_item; 0046 } // namespace accessor_policies 0047 using obj_attr_accessor = accessor<accessor_policies::obj_attr>; 0048 using str_attr_accessor = accessor<accessor_policies::str_attr>; 0049 using item_accessor = accessor<accessor_policies::generic_item>; 0050 using sequence_accessor = accessor<accessor_policies::sequence_item>; 0051 using list_accessor = accessor<accessor_policies::list_item>; 0052 using tuple_accessor = accessor<accessor_policies::tuple_item>; 0053 0054 /// Tag and check to identify a class which implements the Python object API 0055 class pyobject_tag { }; 0056 template <typename T> using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>; 0057 0058 /** \rst 0059 A mixin class which adds common functions to `handle`, `object` and various accessors. 0060 The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``. 0061 \endrst */ 0062 template <typename Derived> 0063 class object_api : public pyobject_tag { 0064 const Derived &derived() const { return static_cast<const Derived &>(*this); } 0065 0066 public: 0067 /** \rst 0068 Return an iterator equivalent to calling ``iter()`` in Python. The object 0069 must be a collection which supports the iteration protocol. 0070 \endrst */ 0071 iterator begin() const; 0072 /// Return a sentinel which ends iteration. 0073 iterator end() const; 0074 0075 /** \rst 0076 Return an internal functor to invoke the object's sequence protocol. Casting 0077 the returned ``detail::item_accessor`` instance to a `handle` or `object` 0078 subclass causes a corresponding call to ``__getitem__``. Assigning a `handle` 0079 or `object` subclass causes a call to ``__setitem__``. 0080 \endrst */ 0081 item_accessor operator[](handle key) const; 0082 /// See above (the only difference is that they key is provided as a string literal) 0083 item_accessor operator[](const char *key) const; 0084 0085 /** \rst 0086 Return an internal functor to access the object's attributes. Casting the 0087 returned ``detail::obj_attr_accessor`` instance to a `handle` or `object` 0088 subclass causes a corresponding call to ``getattr``. Assigning a `handle` 0089 or `object` subclass causes a call to ``setattr``. 0090 \endrst */ 0091 obj_attr_accessor attr(handle key) const; 0092 /// See above (the only difference is that they key is provided as a string literal) 0093 str_attr_accessor attr(const char *key) const; 0094 0095 /** \rst 0096 Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple`` 0097 or ``list`` for a function call. Applying another * to the result yields 0098 ** unpacking, e.g. to unpack a dict as function keyword arguments. 0099 See :ref:`calling_python_functions`. 0100 \endrst */ 0101 args_proxy operator*() const; 0102 0103 /// Check if the given item is contained within this object, i.e. ``item in obj``. 0104 template <typename T> bool contains(T &&item) const; 0105 0106 /** \rst 0107 Assuming the Python object is a function or implements the ``__call__`` 0108 protocol, ``operator()`` invokes the underlying function, passing an 0109 arbitrary set of parameters. The result is returned as a `object` and 0110 may need to be converted back into a Python object using `handle::cast()`. 0111 0112 When some of the arguments cannot be converted to Python objects, the 0113 function will throw a `cast_error` exception. When the Python function 0114 call fails, a `error_already_set` exception is thrown. 0115 \endrst */ 0116 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> 0117 object operator()(Args &&...args) const; 0118 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> 0119 PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)") 0120 object call(Args&&... args) const; 0121 0122 /// Equivalent to ``obj is other`` in Python. 0123 bool is(object_api const& other) const { return derived().ptr() == other.derived().ptr(); } 0124 /// Equivalent to ``obj is None`` in Python. 0125 bool is_none() const { return derived().ptr() == Py_None; } 0126 /// Equivalent to obj == other in Python 0127 bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); } 0128 bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); } 0129 bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); } 0130 bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); } 0131 bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); } 0132 bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); } 0133 0134 object operator-() const; 0135 object operator~() const; 0136 object operator+(object_api const &other) const; 0137 object operator+=(object_api const &other) const; 0138 object operator-(object_api const &other) const; 0139 object operator-=(object_api const &other) const; 0140 object operator*(object_api const &other) const; 0141 object operator*=(object_api const &other) const; 0142 object operator/(object_api const &other) const; 0143 object operator/=(object_api const &other) const; 0144 object operator|(object_api const &other) const; 0145 object operator|=(object_api const &other) const; 0146 object operator&(object_api const &other) const; 0147 object operator&=(object_api const &other) const; 0148 object operator^(object_api const &other) const; 0149 object operator^=(object_api const &other) const; 0150 object operator<<(object_api const &other) const; 0151 object operator<<=(object_api const &other) const; 0152 object operator>>(object_api const &other) const; 0153 object operator>>=(object_api const &other) const; 0154 0155 PYBIND11_DEPRECATED("Use py::str(obj) instead") 0156 pybind11::str str() const; 0157 0158 /// Get or set the object's docstring, i.e. ``obj.__doc__``. 0159 str_attr_accessor doc() const; 0160 0161 /// Return the object's current reference count 0162 int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); } 0163 0164 // TODO PYBIND11_DEPRECATED("Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()") 0165 handle get_type() const; 0166 0167 private: 0168 bool rich_compare(object_api const &other, int value) const; 0169 }; 0170 0171 PYBIND11_NAMESPACE_END(detail) 0172 0173 /** \rst 0174 Holds a reference to a Python object (no reference counting) 0175 0176 The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a 0177 ``PyObject *`` in Python's C API). It does not perform any automatic reference 0178 counting and merely provides a basic C++ interface to various Python API functions. 0179 0180 .. seealso:: 0181 The `object` class inherits from `handle` and adds automatic reference 0182 counting features. 0183 \endrst */ 0184 class handle : public detail::object_api<handle> { 0185 public: 0186 /// The default constructor creates a handle with a ``nullptr``-valued pointer 0187 handle() = default; 0188 /// Creates a ``handle`` from the given raw Python object pointer 0189 // NOLINTNEXTLINE(google-explicit-constructor) 0190 handle(PyObject *ptr) : m_ptr(ptr) { } // Allow implicit conversion from PyObject* 0191 0192 /// Return the underlying ``PyObject *`` pointer 0193 PyObject *ptr() const { return m_ptr; } 0194 PyObject *&ptr() { return m_ptr; } 0195 0196 /** \rst 0197 Manually increase the reference count of the Python object. Usually, it is 0198 preferable to use the `object` class which derives from `handle` and calls 0199 this function automatically. Returns a reference to itself. 0200 \endrst */ 0201 const handle& inc_ref() const & { Py_XINCREF(m_ptr); return *this; } 0202 0203 /** \rst 0204 Manually decrease the reference count of the Python object. Usually, it is 0205 preferable to use the `object` class which derives from `handle` and calls 0206 this function automatically. Returns a reference to itself. 0207 \endrst */ 0208 const handle& dec_ref() const & { Py_XDECREF(m_ptr); return *this; } 0209 0210 /** \rst 0211 Attempt to cast the Python object into the given C++ type. A `cast_error` 0212 will be throw upon failure. 0213 \endrst */ 0214 template <typename T> T cast() const; 0215 /// Return ``true`` when the `handle` wraps a valid Python object 0216 explicit operator bool() const { return m_ptr != nullptr; } 0217 /** \rst 0218 Deprecated: Check that the underlying pointers are the same. 0219 Equivalent to ``obj1 is obj2`` in Python. 0220 \endrst */ 0221 PYBIND11_DEPRECATED("Use obj1.is(obj2) instead") 0222 bool operator==(const handle &h) const { return m_ptr == h.m_ptr; } 0223 PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead") 0224 bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; } 0225 PYBIND11_DEPRECATED("Use handle::operator bool() instead") 0226 bool check() const { return m_ptr != nullptr; } 0227 protected: 0228 PyObject *m_ptr = nullptr; 0229 }; 0230 0231 /** \rst 0232 Holds a reference to a Python object (with reference counting) 0233 0234 Like `handle`, the `object` class is a thin wrapper around an arbitrary Python 0235 object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it 0236 optionally increases the object's reference count upon construction, and it 0237 *always* decreases the reference count when the `object` instance goes out of 0238 scope and is destructed. When using `object` instances consistently, it is much 0239 easier to get reference counting right at the first attempt. 0240 \endrst */ 0241 class object : public handle { 0242 public: 0243 object() = default; 0244 PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()") 0245 object(handle h, bool is_borrowed) : handle(h) { if (is_borrowed) inc_ref(); } 0246 /// Copy constructor; always increases the reference count 0247 object(const object &o) : handle(o) { inc_ref(); } 0248 /// Move constructor; steals the object from ``other`` and preserves its reference count 0249 object(object &&other) noexcept { m_ptr = other.m_ptr; other.m_ptr = nullptr; } 0250 /// Destructor; automatically calls `handle::dec_ref()` 0251 ~object() { dec_ref(); } 0252 0253 /** \rst 0254 Resets the internal pointer to ``nullptr`` without decreasing the 0255 object's reference count. The function returns a raw handle to the original 0256 Python object. 0257 \endrst */ 0258 handle release() { 0259 PyObject *tmp = m_ptr; 0260 m_ptr = nullptr; 0261 return handle(tmp); 0262 } 0263 0264 object& operator=(const object &other) { 0265 other.inc_ref(); 0266 // Use temporary variable to ensure `*this` remains valid while 0267 // `Py_XDECREF` executes, in case `*this` is accessible from Python. 0268 handle temp(m_ptr); 0269 m_ptr = other.m_ptr; 0270 temp.dec_ref(); 0271 return *this; 0272 } 0273 0274 object& operator=(object &&other) noexcept { 0275 if (this != &other) { 0276 handle temp(m_ptr); 0277 m_ptr = other.m_ptr; 0278 other.m_ptr = nullptr; 0279 temp.dec_ref(); 0280 } 0281 return *this; 0282 } 0283 0284 // Calling cast() on an object lvalue just copies (via handle::cast) 0285 template <typename T> T cast() const &; 0286 // Calling on an object rvalue does a move, if needed and/or possible 0287 template <typename T> T cast() &&; 0288 0289 protected: 0290 // Tags for choosing constructors from raw PyObject * 0291 struct borrowed_t { }; 0292 struct stolen_t { }; 0293 0294 /// @cond BROKEN 0295 template <typename T> friend T reinterpret_borrow(handle); 0296 template <typename T> friend T reinterpret_steal(handle); 0297 /// @endcond 0298 0299 public: 0300 // Only accessible from derived classes and the reinterpret_* functions 0301 object(handle h, borrowed_t) : handle(h) { inc_ref(); } 0302 object(handle h, stolen_t) : handle(h) { } 0303 }; 0304 0305 /** \rst 0306 Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference. 0307 The target type ``T`` must be `object` or one of its derived classes. The function 0308 doesn't do any conversions or checks. It's up to the user to make sure that the 0309 target type is correct. 0310 0311 .. code-block:: cpp 0312 0313 PyObject *p = PyList_GetItem(obj, index); 0314 py::object o = reinterpret_borrow<py::object>(p); 0315 // or 0316 py::tuple t = reinterpret_borrow<py::tuple>(p); // <-- `p` must be already be a `tuple` 0317 \endrst */ 0318 template <typename T> T reinterpret_borrow(handle h) { return {h, object::borrowed_t{}}; } 0319 0320 /** \rst 0321 Like `reinterpret_borrow`, but steals the reference. 0322 0323 .. code-block:: cpp 0324 0325 PyObject *p = PyObject_Str(obj); 0326 py::str s = reinterpret_steal<py::str>(p); // <-- `p` must be already be a `str` 0327 \endrst */ 0328 template <typename T> T reinterpret_steal(handle h) { return {h, object::stolen_t{}}; } 0329 0330 PYBIND11_NAMESPACE_BEGIN(detail) 0331 std::string error_string(); 0332 PYBIND11_NAMESPACE_END(detail) 0333 0334 #if defined(_MSC_VER) 0335 # pragma warning(push) 0336 # pragma warning(disable: 4275 4251) // warning C4275: An exported class was derived from a class that wasn't exported. Can be ignored when derived from a STL class. 0337 #endif 0338 /// Fetch and hold an error which was already set in Python. An instance of this is typically 0339 /// thrown to propagate python-side errors back through C++ which can either be caught manually or 0340 /// else falls back to the function dispatcher (which then raises the captured error back to 0341 /// python). 0342 class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::runtime_error { 0343 public: 0344 /// Constructs a new exception from the current Python error indicator, if any. The current 0345 /// Python error indicator will be cleared. 0346 error_already_set() : std::runtime_error(detail::error_string()) { 0347 PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr()); 0348 } 0349 0350 error_already_set(const error_already_set &) = default; 0351 error_already_set(error_already_set &&) = default; 0352 0353 inline ~error_already_set() override; 0354 0355 /// Give the currently-held error back to Python, if any. If there is currently a Python error 0356 /// already set it is cleared first. After this call, the current object no longer stores the 0357 /// error variables (but the `.what()` string is still available). 0358 void restore() { PyErr_Restore(m_type.release().ptr(), m_value.release().ptr(), m_trace.release().ptr()); } 0359 0360 /// If it is impossible to raise the currently-held error, such as in a destructor, we can write 0361 /// it out using Python's unraisable hook (`sys.unraisablehook`). The error context should be 0362 /// some object whose `repr()` helps identify the location of the error. Python already knows the 0363 /// type and value of the error, so there is no need to repeat that. After this call, the current 0364 /// object no longer stores the error variables, and neither does Python. 0365 void discard_as_unraisable(object err_context) { 0366 restore(); 0367 PyErr_WriteUnraisable(err_context.ptr()); 0368 } 0369 /// An alternate version of `discard_as_unraisable()`, where a string provides information on the 0370 /// location of the error. For example, `__func__` could be helpful. 0371 void discard_as_unraisable(const char *err_context) { 0372 discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context))); 0373 } 0374 0375 // Does nothing; provided for backwards compatibility. 0376 PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated") 0377 void clear() {} 0378 0379 /// Check if the currently trapped error type matches the given Python exception class (or a 0380 /// subclass thereof). May also be passed a tuple to search for any exception class matches in 0381 /// the given tuple. 0382 bool matches(handle exc) const { 0383 return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0); 0384 } 0385 0386 const object& type() const { return m_type; } 0387 const object& value() const { return m_value; } 0388 const object& trace() const { return m_trace; } 0389 0390 private: 0391 object m_type, m_value, m_trace; 0392 }; 0393 #if defined(_MSC_VER) 0394 # pragma warning(pop) 0395 #endif 0396 0397 #if PY_VERSION_HEX >= 0x03030000 0398 0399 /// Replaces the current Python error indicator with the chosen error, performing a 0400 /// 'raise from' to indicate that the chosen error was caused by the original error. 0401 inline void raise_from(PyObject *type, const char *message) { 0402 // Based on _PyErr_FormatVFromCause: 0403 // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405 0404 // See https://github.com/pybind/pybind11/pull/2112 for details. 0405 PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr; 0406 0407 assert(PyErr_Occurred()); 0408 PyErr_Fetch(&exc, &val, &tb); 0409 PyErr_NormalizeException(&exc, &val, &tb); 0410 if (tb != nullptr) { 0411 PyException_SetTraceback(val, tb); 0412 Py_DECREF(tb); 0413 } 0414 Py_DECREF(exc); 0415 assert(!PyErr_Occurred()); 0416 0417 PyErr_SetString(type, message); 0418 0419 PyErr_Fetch(&exc, &val2, &tb); 0420 PyErr_NormalizeException(&exc, &val2, &tb); 0421 Py_INCREF(val); 0422 PyException_SetCause(val2, val); 0423 PyException_SetContext(val2, val); 0424 PyErr_Restore(exc, val2, tb); 0425 } 0426 0427 /// Sets the current Python error indicator with the chosen error, performing a 'raise from' 0428 /// from the error contained in error_already_set to indicate that the chosen error was 0429 /// caused by the original error. After this function is called error_already_set will 0430 /// no longer contain an error. 0431 inline void raise_from(error_already_set& err, PyObject *type, const char *message) { 0432 err.restore(); 0433 raise_from(type, message); 0434 } 0435 0436 #endif 0437 0438 /** \defgroup python_builtins const_name 0439 Unless stated otherwise, the following C++ functions behave the same 0440 as their Python counterparts. 0441 */ 0442 0443 /** \ingroup python_builtins 0444 \rst 0445 Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of 0446 `object` or a class which was exposed to Python as ``py::class_<T>``. 0447 \endrst */ 0448 template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0> 0449 bool isinstance(handle obj) { return T::check_(obj); } 0450 0451 template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0> 0452 bool isinstance(handle obj) { return detail::isinstance_generic(obj, typeid(T)); } 0453 0454 template <> inline bool isinstance<handle>(handle) = delete; 0455 template <> inline bool isinstance<object>(handle obj) { return obj.ptr() != nullptr; } 0456 0457 /// \ingroup python_builtins 0458 /// Return true if ``obj`` is an instance of the ``type``. 0459 inline bool isinstance(handle obj, handle type) { 0460 const auto result = PyObject_IsInstance(obj.ptr(), type.ptr()); 0461 if (result == -1) 0462 throw error_already_set(); 0463 return result != 0; 0464 } 0465 0466 /// \addtogroup python_builtins 0467 /// @{ 0468 inline bool hasattr(handle obj, handle name) { 0469 return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1; 0470 } 0471 0472 inline bool hasattr(handle obj, const char *name) { 0473 return PyObject_HasAttrString(obj.ptr(), name) == 1; 0474 } 0475 0476 inline void delattr(handle obj, handle name) { 0477 if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) { throw error_already_set(); } 0478 } 0479 0480 inline void delattr(handle obj, const char *name) { 0481 if (PyObject_DelAttrString(obj.ptr(), name) != 0) { throw error_already_set(); } 0482 } 0483 0484 inline object getattr(handle obj, handle name) { 0485 PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr()); 0486 if (!result) { throw error_already_set(); } 0487 return reinterpret_steal<object>(result); 0488 } 0489 0490 inline object getattr(handle obj, const char *name) { 0491 PyObject *result = PyObject_GetAttrString(obj.ptr(), name); 0492 if (!result) { throw error_already_set(); } 0493 return reinterpret_steal<object>(result); 0494 } 0495 0496 inline object getattr(handle obj, handle name, handle default_) { 0497 if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) { 0498 return reinterpret_steal<object>(result); 0499 } 0500 PyErr_Clear(); 0501 return reinterpret_borrow<object>(default_); 0502 } 0503 0504 inline object getattr(handle obj, const char *name, handle default_) { 0505 if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) { 0506 return reinterpret_steal<object>(result); 0507 } 0508 PyErr_Clear(); 0509 return reinterpret_borrow<object>(default_); 0510 } 0511 0512 inline void setattr(handle obj, handle name, handle value) { 0513 if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) { throw error_already_set(); } 0514 } 0515 0516 inline void setattr(handle obj, const char *name, handle value) { 0517 if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { throw error_already_set(); } 0518 } 0519 0520 inline ssize_t hash(handle obj) { 0521 auto h = PyObject_Hash(obj.ptr()); 0522 if (h == -1) { throw error_already_set(); } 0523 return h; 0524 } 0525 0526 /// @} python_builtins 0527 0528 PYBIND11_NAMESPACE_BEGIN(detail) 0529 inline handle get_function(handle value) { 0530 if (value) { 0531 #if PY_MAJOR_VERSION >= 3 0532 if (PyInstanceMethod_Check(value.ptr())) 0533 value = PyInstanceMethod_GET_FUNCTION(value.ptr()); 0534 else 0535 #endif 0536 if (PyMethod_Check(value.ptr())) 0537 value = PyMethod_GET_FUNCTION(value.ptr()); 0538 } 0539 return value; 0540 } 0541 0542 // Reimplementation of python's dict helper functions to ensure that exceptions 0543 // aren't swallowed (see #2862) 0544 0545 // copied from cpython _PyDict_GetItemStringWithError 0546 inline PyObject * dict_getitemstring(PyObject *v, const char *key) 0547 { 0548 #if PY_MAJOR_VERSION >= 3 0549 PyObject *kv = nullptr, *rv = nullptr; 0550 kv = PyUnicode_FromString(key); 0551 if (kv == NULL) { 0552 throw error_already_set(); 0553 } 0554 0555 rv = PyDict_GetItemWithError(v, kv); 0556 Py_DECREF(kv); 0557 if (rv == NULL && PyErr_Occurred()) { 0558 throw error_already_set(); 0559 } 0560 return rv; 0561 #else 0562 return PyDict_GetItemString(v, key); 0563 #endif 0564 } 0565 0566 inline PyObject * dict_getitem(PyObject *v, PyObject *key) 0567 { 0568 #if PY_MAJOR_VERSION >= 3 0569 PyObject *rv = PyDict_GetItemWithError(v, key); 0570 if (rv == NULL && PyErr_Occurred()) { 0571 throw error_already_set(); 0572 } 0573 return rv; 0574 #else 0575 return PyDict_GetItem(v, key); 0576 #endif 0577 } 0578 0579 // Helper aliases/functions to support implicit casting of values given to python accessors/methods. 0580 // When given a pyobject, this simply returns the pyobject as-is; for other C++ type, the value goes 0581 // through pybind11::cast(obj) to convert it to an `object`. 0582 template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0> 0583 auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) { return std::forward<T>(o); } 0584 // The following casting version is implemented in cast.h: 0585 template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0> 0586 object object_or_cast(T &&o); 0587 // Match a PyObject*, which we want to convert directly to handle via its converting constructor 0588 inline handle object_or_cast(PyObject *ptr) { return ptr; } 0589 0590 #if defined(_MSC_VER) && _MSC_VER < 1920 0591 # pragma warning(push) 0592 # pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified 0593 #endif 0594 template <typename Policy> 0595 class accessor : public object_api<accessor<Policy>> { 0596 using key_type = typename Policy::key_type; 0597 0598 public: 0599 accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) { } 0600 accessor(const accessor &) = default; 0601 accessor(accessor &&) noexcept = default; 0602 0603 // accessor overload required to override default assignment operator (templates are not allowed 0604 // to replace default compiler-generated assignments). 0605 void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); } 0606 void operator=(const accessor &a) & { operator=(handle(a)); } 0607 0608 template <typename T> void operator=(T &&value) && { 0609 Policy::set(obj, key, object_or_cast(std::forward<T>(value))); 0610 } 0611 template <typename T> void operator=(T &&value) & { 0612 get_cache() = reinterpret_borrow<object>(object_or_cast(std::forward<T>(value))); 0613 } 0614 0615 template <typename T = Policy> 0616 PYBIND11_DEPRECATED("Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)") 0617 explicit operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value || 0618 std::is_same<T, accessor_policies::obj_attr>::value, bool>() const { 0619 return hasattr(obj, key); 0620 } 0621 template <typename T = Policy> 0622 PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)") 0623 explicit operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const { 0624 return obj.contains(key); 0625 } 0626 0627 // NOLINTNEXTLINE(google-explicit-constructor) 0628 operator object() const { return get_cache(); } 0629 PyObject *ptr() const { return get_cache().ptr(); } 0630 template <typename T> T cast() const { return get_cache().template cast<T>(); } 0631 0632 private: 0633 object &get_cache() const { 0634 if (!cache) { cache = Policy::get(obj, key); } 0635 return cache; 0636 } 0637 0638 private: 0639 handle obj; 0640 key_type key; 0641 mutable object cache; 0642 }; 0643 #if defined(_MSC_VER) && _MSC_VER < 1920 0644 # pragma warning(pop) 0645 #endif 0646 0647 PYBIND11_NAMESPACE_BEGIN(accessor_policies) 0648 struct obj_attr { 0649 using key_type = object; 0650 static object get(handle obj, handle key) { return getattr(obj, key); } 0651 static void set(handle obj, handle key, handle val) { setattr(obj, key, val); } 0652 }; 0653 0654 struct str_attr { 0655 using key_type = const char *; 0656 static object get(handle obj, const char *key) { return getattr(obj, key); } 0657 static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); } 0658 }; 0659 0660 struct generic_item { 0661 using key_type = object; 0662 0663 static object get(handle obj, handle key) { 0664 PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr()); 0665 if (!result) { throw error_already_set(); } 0666 return reinterpret_steal<object>(result); 0667 } 0668 0669 static void set(handle obj, handle key, handle val) { 0670 if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) { throw error_already_set(); } 0671 } 0672 }; 0673 0674 struct sequence_item { 0675 using key_type = size_t; 0676 0677 template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> 0678 static object get(handle obj, const IdxType &index) { 0679 PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index)); 0680 if (!result) { throw error_already_set(); } 0681 return reinterpret_steal<object>(result); 0682 } 0683 0684 template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> 0685 static void set(handle obj, const IdxType &index, handle val) { 0686 // PySequence_SetItem does not steal a reference to 'val' 0687 if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) { 0688 throw error_already_set(); 0689 } 0690 } 0691 }; 0692 0693 struct list_item { 0694 using key_type = size_t; 0695 0696 template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> 0697 static object get(handle obj, const IdxType &index) { 0698 PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index)); 0699 if (!result) { throw error_already_set(); } 0700 return reinterpret_borrow<object>(result); 0701 } 0702 0703 template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> 0704 static void set(handle obj, const IdxType &index, handle val) { 0705 // PyList_SetItem steals a reference to 'val' 0706 if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) { 0707 throw error_already_set(); 0708 } 0709 } 0710 }; 0711 0712 struct tuple_item { 0713 using key_type = size_t; 0714 0715 template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> 0716 static object get(handle obj, const IdxType &index) { 0717 PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index)); 0718 if (!result) { throw error_already_set(); } 0719 return reinterpret_borrow<object>(result); 0720 } 0721 0722 template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> 0723 static void set(handle obj, const IdxType &index, handle val) { 0724 // PyTuple_SetItem steals a reference to 'val' 0725 if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) { 0726 throw error_already_set(); 0727 } 0728 } 0729 }; 0730 PYBIND11_NAMESPACE_END(accessor_policies) 0731 0732 /// STL iterator template used for tuple, list, sequence and dict 0733 template <typename Policy> 0734 class generic_iterator : public Policy { 0735 using It = generic_iterator; 0736 0737 public: 0738 using difference_type = ssize_t; 0739 using iterator_category = typename Policy::iterator_category; 0740 using value_type = typename Policy::value_type; 0741 using reference = typename Policy::reference; 0742 using pointer = typename Policy::pointer; 0743 0744 generic_iterator() = default; 0745 generic_iterator(handle seq, ssize_t index) : Policy(seq, index) { } 0746 0747 // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 0748 reference operator*() const { return Policy::dereference(); } 0749 // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 0750 reference operator[](difference_type n) const { return *(*this + n); } 0751 pointer operator->() const { return **this; } 0752 0753 It &operator++() { Policy::increment(); return *this; } 0754 It operator++(int) { auto copy = *this; Policy::increment(); return copy; } 0755 It &operator--() { Policy::decrement(); return *this; } 0756 It operator--(int) { auto copy = *this; Policy::decrement(); return copy; } 0757 It &operator+=(difference_type n) { Policy::advance(n); return *this; } 0758 It &operator-=(difference_type n) { Policy::advance(-n); return *this; } 0759 0760 friend It operator+(const It &a, difference_type n) { auto copy = a; return copy += n; } 0761 friend It operator+(difference_type n, const It &b) { return b + n; } 0762 friend It operator-(const It &a, difference_type n) { auto copy = a; return copy -= n; } 0763 friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); } 0764 0765 friend bool operator==(const It &a, const It &b) { return a.equal(b); } 0766 friend bool operator!=(const It &a, const It &b) { return !(a == b); } 0767 friend bool operator< (const It &a, const It &b) { return b - a > 0; } 0768 friend bool operator> (const It &a, const It &b) { return b < a; } 0769 friend bool operator>=(const It &a, const It &b) { return !(a < b); } 0770 friend bool operator<=(const It &a, const It &b) { return !(a > b); } 0771 }; 0772 0773 PYBIND11_NAMESPACE_BEGIN(iterator_policies) 0774 /// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers 0775 template <typename T> 0776 struct arrow_proxy { 0777 T value; 0778 0779 // NOLINTNEXTLINE(google-explicit-constructor) 0780 arrow_proxy(T &&value) noexcept : value(std::move(value)) { } 0781 T *operator->() const { return &value; } 0782 }; 0783 0784 /// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS`` 0785 class sequence_fast_readonly { 0786 protected: 0787 using iterator_category = std::random_access_iterator_tag; 0788 using value_type = handle; 0789 using reference = const handle; // PR #3263 0790 using pointer = arrow_proxy<const handle>; 0791 0792 sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) { } 0793 0794 // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 0795 reference dereference() const { return *ptr; } 0796 void increment() { ++ptr; } 0797 void decrement() { --ptr; } 0798 void advance(ssize_t n) { ptr += n; } 0799 bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; } 0800 ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; } 0801 0802 private: 0803 PyObject **ptr; 0804 }; 0805 0806 /// Full read and write access using the sequence protocol: see ``detail::sequence_accessor`` 0807 class sequence_slow_readwrite { 0808 protected: 0809 using iterator_category = std::random_access_iterator_tag; 0810 using value_type = object; 0811 using reference = sequence_accessor; 0812 using pointer = arrow_proxy<const sequence_accessor>; 0813 0814 sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) { } 0815 0816 reference dereference() const { return {obj, static_cast<size_t>(index)}; } 0817 void increment() { ++index; } 0818 void decrement() { --index; } 0819 void advance(ssize_t n) { index += n; } 0820 bool equal(const sequence_slow_readwrite &b) const { return index == b.index; } 0821 ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; } 0822 0823 private: 0824 handle obj; 0825 ssize_t index; 0826 }; 0827 0828 /// Python's dictionary protocol permits this to be a forward iterator 0829 class dict_readonly { 0830 protected: 0831 using iterator_category = std::forward_iterator_tag; 0832 using value_type = std::pair<handle, handle>; 0833 using reference = const value_type; // PR #3263 0834 using pointer = arrow_proxy<const value_type>; 0835 0836 dict_readonly() = default; 0837 dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); } 0838 0839 // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 0840 reference dereference() const { return {key, value}; } 0841 void increment() { 0842 if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) { 0843 pos = -1; 0844 } 0845 } 0846 bool equal(const dict_readonly &b) const { return pos == b.pos; } 0847 0848 private: 0849 handle obj; 0850 PyObject *key = nullptr, *value = nullptr; 0851 ssize_t pos = -1; 0852 }; 0853 PYBIND11_NAMESPACE_END(iterator_policies) 0854 0855 #if !defined(PYPY_VERSION) 0856 using tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>; 0857 using list_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>; 0858 #else 0859 using tuple_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>; 0860 using list_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>; 0861 #endif 0862 0863 using sequence_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>; 0864 using dict_iterator = generic_iterator<iterator_policies::dict_readonly>; 0865 0866 inline bool PyIterable_Check(PyObject *obj) { 0867 PyObject *iter = PyObject_GetIter(obj); 0868 if (iter) { 0869 Py_DECREF(iter); 0870 return true; 0871 } 0872 PyErr_Clear(); 0873 return false; 0874 } 0875 0876 inline bool PyNone_Check(PyObject *o) { return o == Py_None; } 0877 inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; } 0878 0879 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE 0880 inline bool PyUnicode_Check_Permissive(PyObject *o) { return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); } 0881 #define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive 0882 #else 0883 #define PYBIND11_STR_CHECK_FUN PyUnicode_Check 0884 #endif 0885 0886 inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; } 0887 0888 class kwargs_proxy : public handle { 0889 public: 0890 explicit kwargs_proxy(handle h) : handle(h) { } 0891 }; 0892 0893 class args_proxy : public handle { 0894 public: 0895 explicit args_proxy(handle h) : handle(h) { } 0896 kwargs_proxy operator*() const { return kwargs_proxy(*this); } 0897 }; 0898 0899 /// Python argument categories (using PEP 448 terms) 0900 template <typename T> using is_keyword = std::is_base_of<arg, T>; 0901 template <typename T> using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking 0902 template <typename T> using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking 0903 template <typename T> using is_positional = satisfies_none_of<T, 0904 is_keyword, is_s_unpacking, is_ds_unpacking 0905 >; 0906 template <typename T> using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>; 0907 0908 // Call argument collector forward declarations 0909 template <return_value_policy policy = return_value_policy::automatic_reference> 0910 class simple_collector; 0911 template <return_value_policy policy = return_value_policy::automatic_reference> 0912 class unpacking_collector; 0913 0914 PYBIND11_NAMESPACE_END(detail) 0915 0916 // TODO: After the deprecated constructors are removed, this macro can be simplified by 0917 // inheriting ctors: `using Parent::Parent`. It's not an option right now because 0918 // the `using` statement triggers the parent deprecation warning even if the ctor 0919 // isn't even used. 0920 #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ 0921 public: \ 0922 PYBIND11_DEPRECATED("Use reinterpret_borrow<"#Name">() or reinterpret_steal<"#Name">()") \ 0923 Name(handle h, bool is_borrowed) : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) { } \ 0924 Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) { } \ 0925 Name(handle h, stolen_t) : Parent(h, stolen_t{}) { } \ 0926 PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \ 0927 bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \ 0928 static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \ 0929 template <typename Policy_> \ 0930 /* NOLINTNEXTLINE(google-explicit-constructor) */ \ 0931 Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) { } 0932 0933 #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \ 0934 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ 0935 /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ 0936 /* NOLINTNEXTLINE(google-explicit-constructor) */ \ 0937 Name(const object &o) \ 0938 : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) \ 0939 { if (!m_ptr) throw error_already_set(); } \ 0940 /* NOLINTNEXTLINE(google-explicit-constructor) */ \ 0941 Name(object &&o) \ 0942 : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) \ 0943 { if (!m_ptr) throw error_already_set(); } 0944 0945 #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \ 0946 PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \ 0947 Name() : Parent() { } 0948 0949 #define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \ 0950 ::pybind11::type_error("Object of type '" + \ 0951 ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) + \ 0952 "' is not an instance of '" #Name "'") 0953 0954 #define PYBIND11_OBJECT(Name, Parent, CheckFun) \ 0955 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ 0956 /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ 0957 /* NOLINTNEXTLINE(google-explicit-constructor) */ \ 0958 Name(const object &o) : Parent(o) \ 0959 { if (m_ptr && !check_(m_ptr)) throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); } \ 0960 /* NOLINTNEXTLINE(google-explicit-constructor) */ \ 0961 Name(object &&o) : Parent(std::move(o)) \ 0962 { if (m_ptr && !check_(m_ptr)) throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); } 0963 0964 #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \ 0965 PYBIND11_OBJECT(Name, Parent, CheckFun) \ 0966 Name() : Parent() { } 0967 0968 /// \addtogroup pytypes 0969 /// @{ 0970 0971 /** \rst 0972 Wraps a Python iterator so that it can also be used as a C++ input iterator 0973 0974 Caveat: copying an iterator does not (and cannot) clone the internal 0975 state of the Python iterable. This also applies to the post-increment 0976 operator. This iterator should only be used to retrieve the current 0977 value using ``operator*()``. 0978 \endrst */ 0979 class iterator : public object { 0980 public: 0981 using iterator_category = std::input_iterator_tag; 0982 using difference_type = ssize_t; 0983 using value_type = handle; 0984 using reference = const handle; // PR #3263 0985 using pointer = const handle *; 0986 0987 PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check) 0988 0989 iterator& operator++() { 0990 advance(); 0991 return *this; 0992 } 0993 0994 iterator operator++(int) { 0995 auto rv = *this; 0996 advance(); 0997 return rv; 0998 } 0999 1000 // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 1001 reference operator*() const { 1002 if (m_ptr && !value.ptr()) { 1003 auto& self = const_cast<iterator &>(*this); 1004 self.advance(); 1005 } 1006 return value; 1007 } 1008 1009 pointer operator->() const { operator*(); return &value; } 1010 1011 /** \rst 1012 The value which marks the end of the iteration. ``it == iterator::sentinel()`` 1013 is equivalent to catching ``StopIteration`` in Python. 1014 1015 .. code-block:: cpp 1016 1017 void foo(py::iterator it) { 1018 while (it != py::iterator::sentinel()) { 1019 // use `*it` 1020 ++it; 1021 } 1022 } 1023 \endrst */ 1024 static iterator sentinel() { return {}; } 1025 1026 friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); } 1027 friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); } 1028 1029 private: 1030 void advance() { 1031 value = reinterpret_steal<object>(PyIter_Next(m_ptr)); 1032 if (PyErr_Occurred()) { throw error_already_set(); } 1033 } 1034 1035 private: 1036 object value = {}; 1037 }; 1038 1039 1040 1041 class type : public object { 1042 public: 1043 PYBIND11_OBJECT(type, object, PyType_Check) 1044 1045 /// Return a type handle from a handle or an object 1046 static handle handle_of(handle h) { return handle((PyObject*) Py_TYPE(h.ptr())); } 1047 1048 /// Return a type object from a handle or an object 1049 static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); } 1050 1051 // Defined in pybind11/cast.h 1052 /// Convert C++ type to handle if previously registered. Does not convert 1053 /// standard types, like int, float. etc. yet. 1054 /// See https://github.com/pybind/pybind11/issues/2486 1055 template<typename T> 1056 static handle handle_of(); 1057 1058 /// Convert C++ type to type if previously registered. Does not convert 1059 /// standard types, like int, float. etc. yet. 1060 /// See https://github.com/pybind/pybind11/issues/2486 1061 template<typename T> 1062 static type of() {return type(type::handle_of<T>(), borrowed_t{}); } 1063 }; 1064 1065 class iterable : public object { 1066 public: 1067 PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check) 1068 }; 1069 1070 class bytes; 1071 1072 class str : public object { 1073 public: 1074 PYBIND11_OBJECT_CVT(str, object, PYBIND11_STR_CHECK_FUN, raw_str) 1075 1076 template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> 1077 str(const char *c, const SzType &n) 1078 : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) { 1079 if (!m_ptr) pybind11_fail("Could not allocate string object!"); 1080 } 1081 1082 // 'explicit' is explicitly omitted from the following constructors to allow implicit conversion to py::str from C++ string-like objects 1083 // NOLINTNEXTLINE(google-explicit-constructor) 1084 str(const char *c = "") 1085 : object(PyUnicode_FromString(c), stolen_t{}) { 1086 if (!m_ptr) pybind11_fail("Could not allocate string object!"); 1087 } 1088 1089 // NOLINTNEXTLINE(google-explicit-constructor) 1090 str(const std::string &s) : str(s.data(), s.size()) { } 1091 1092 #ifdef PYBIND11_HAS_STRING_VIEW 1093 // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521). 1094 template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0> 1095 // NOLINTNEXTLINE(google-explicit-constructor) 1096 str(T s) : str(s.data(), s.size()) { } 1097 1098 # ifdef PYBIND11_HAS_U8STRING 1099 // reinterpret_cast here is safe (C++20 guarantees char8_t has the same size/alignment as char) 1100 // NOLINTNEXTLINE(google-explicit-constructor) 1101 str(std::u8string_view s) : str(reinterpret_cast<const char*>(s.data()), s.size()) { } 1102 # endif 1103 1104 #endif 1105 1106 explicit str(const bytes &b); 1107 1108 /** \rst 1109 Return a string representation of the object. This is analogous to 1110 the ``str()`` function in Python. 1111 \endrst */ 1112 explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { if (!m_ptr) throw error_already_set(); } 1113 1114 // NOLINTNEXTLINE(google-explicit-constructor) 1115 operator std::string() const { 1116 object temp = *this; 1117 if (PyUnicode_Check(m_ptr)) { 1118 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr)); 1119 if (!temp) 1120 throw error_already_set(); 1121 } 1122 char *buffer = nullptr; 1123 ssize_t length = 0; 1124 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length)) 1125 pybind11_fail("Unable to extract string contents! (invalid type)"); 1126 return std::string(buffer, (size_t) length); 1127 } 1128 1129 template <typename... Args> 1130 str format(Args &&...args) const { 1131 return attr("format")(std::forward<Args>(args)...); 1132 } 1133 1134 private: 1135 /// Return string representation -- always returns a new reference, even if already a str 1136 static PyObject *raw_str(PyObject *op) { 1137 PyObject *str_value = PyObject_Str(op); 1138 #if PY_MAJOR_VERSION < 3 1139 if (!str_value) throw error_already_set(); 1140 PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr); 1141 Py_XDECREF(str_value); str_value = unicode; 1142 #endif 1143 return str_value; 1144 } 1145 }; 1146 /// @} pytypes 1147 1148 inline namespace literals { 1149 /** \rst 1150 String literal version of `str` 1151 \endrst */ 1152 inline str operator"" _s(const char *s, size_t size) { return {s, size}; } 1153 } // namespace literals 1154 1155 /// \addtogroup pytypes 1156 /// @{ 1157 class bytes : public object { 1158 public: 1159 PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK) 1160 1161 // Allow implicit conversion: 1162 // NOLINTNEXTLINE(google-explicit-constructor) 1163 bytes(const char *c = "") 1164 : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) { 1165 if (!m_ptr) pybind11_fail("Could not allocate bytes object!"); 1166 } 1167 1168 template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> 1169 bytes(const char *c, const SzType &n) 1170 : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, ssize_t_cast(n)), stolen_t{}) { 1171 if (!m_ptr) pybind11_fail("Could not allocate bytes object!"); 1172 } 1173 1174 // Allow implicit conversion: 1175 // NOLINTNEXTLINE(google-explicit-constructor) 1176 bytes(const std::string &s) : bytes(s.data(), s.size()) { } 1177 1178 explicit bytes(const pybind11::str &s); 1179 1180 // NOLINTNEXTLINE(google-explicit-constructor) 1181 operator std::string() const { 1182 char *buffer = nullptr; 1183 ssize_t length = 0; 1184 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length)) 1185 pybind11_fail("Unable to extract bytes contents!"); 1186 return std::string(buffer, (size_t) length); 1187 } 1188 1189 #ifdef PYBIND11_HAS_STRING_VIEW 1190 // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521). 1191 template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0> 1192 // NOLINTNEXTLINE(google-explicit-constructor) 1193 bytes(T s) : bytes(s.data(), s.size()) { } 1194 1195 // Obtain a string view that views the current `bytes` buffer value. Note that this is only 1196 // valid so long as the `bytes` instance remains alive and so generally should not outlive the 1197 // lifetime of the `bytes` instance. 1198 // NOLINTNEXTLINE(google-explicit-constructor) 1199 operator std::string_view() const { 1200 char *buffer = nullptr; 1201 ssize_t length = 0; 1202 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length)) 1203 pybind11_fail("Unable to extract bytes contents!"); 1204 return {buffer, static_cast<size_t>(length)}; 1205 } 1206 #endif 1207 1208 }; 1209 // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors 1210 // are included in the doxygen group; close here and reopen after as a workaround 1211 /// @} pytypes 1212 1213 inline bytes::bytes(const pybind11::str &s) { 1214 object temp = s; 1215 if (PyUnicode_Check(s.ptr())) { 1216 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr())); 1217 if (!temp) 1218 pybind11_fail("Unable to extract string contents! (encoding issue)"); 1219 } 1220 char *buffer = nullptr; 1221 ssize_t length = 0; 1222 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length)) 1223 pybind11_fail("Unable to extract string contents! (invalid type)"); 1224 auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length)); 1225 if (!obj) 1226 pybind11_fail("Could not allocate bytes object!"); 1227 m_ptr = obj.release().ptr(); 1228 } 1229 1230 inline str::str(const bytes& b) { 1231 char *buffer = nullptr; 1232 ssize_t length = 0; 1233 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(b.ptr(), &buffer, &length)) 1234 pybind11_fail("Unable to extract bytes contents!"); 1235 auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, length)); 1236 if (!obj) 1237 pybind11_fail("Could not allocate string object!"); 1238 m_ptr = obj.release().ptr(); 1239 } 1240 1241 /// \addtogroup pytypes 1242 /// @{ 1243 class bytearray : public object { 1244 public: 1245 PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject) 1246 1247 template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> 1248 bytearray(const char *c, const SzType &n) 1249 : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) { 1250 if (!m_ptr) pybind11_fail("Could not allocate bytearray object!"); 1251 } 1252 1253 bytearray() 1254 : bytearray("", 0) {} 1255 1256 explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) { } 1257 1258 size_t size() const { return static_cast<size_t>(PyByteArray_Size(m_ptr)); } 1259 1260 explicit operator std::string() const { 1261 char *buffer = PyByteArray_AS_STRING(m_ptr); 1262 ssize_t size = PyByteArray_GET_SIZE(m_ptr); 1263 return std::string(buffer, static_cast<size_t>(size)); 1264 } 1265 }; 1266 // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors 1267 // are included in the doxygen group; close here and reopen after as a workaround 1268 /// @} pytypes 1269 1270 /// \addtogroup pytypes 1271 /// @{ 1272 class none : public object { 1273 public: 1274 PYBIND11_OBJECT(none, object, detail::PyNone_Check) 1275 none() : object(Py_None, borrowed_t{}) { } 1276 }; 1277 1278 class ellipsis : public object { 1279 public: 1280 PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check) 1281 ellipsis() : object(Py_Ellipsis, borrowed_t{}) { } 1282 }; 1283 1284 class bool_ : public object { 1285 public: 1286 PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool) 1287 bool_() : object(Py_False, borrowed_t{}) { } 1288 // Allow implicit conversion from and to `bool`: 1289 // NOLINTNEXTLINE(google-explicit-constructor) 1290 bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) { } 1291 // NOLINTNEXTLINE(google-explicit-constructor) 1292 operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; } 1293 1294 private: 1295 /// Return the truth value of an object -- always returns a new reference 1296 static PyObject *raw_bool(PyObject *op) { 1297 const auto value = PyObject_IsTrue(op); 1298 if (value == -1) return nullptr; 1299 return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr(); 1300 } 1301 }; 1302 1303 PYBIND11_NAMESPACE_BEGIN(detail) 1304 // Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1; 1305 // otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned). 1306 // (The distinction is critically important when casting a returned -1 error value to some other 1307 // unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes). 1308 template <typename Unsigned> 1309 Unsigned as_unsigned(PyObject *o) { 1310 if (PYBIND11_SILENCE_MSVC_C4127(sizeof(Unsigned) <= sizeof(unsigned long)) 1311 #if PY_VERSION_HEX < 0x03000000 1312 || PyInt_Check(o) 1313 #endif 1314 ) { 1315 unsigned long v = PyLong_AsUnsignedLong(o); 1316 return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v; 1317 } 1318 unsigned long long v = PyLong_AsUnsignedLongLong(o); 1319 return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v; 1320 } 1321 PYBIND11_NAMESPACE_END(detail) 1322 1323 class int_ : public object { 1324 public: 1325 PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long) 1326 int_() : object(PyLong_FromLong(0), stolen_t{}) { } 1327 // Allow implicit conversion from C++ integral types: 1328 template <typename T, 1329 detail::enable_if_t<std::is_integral<T>::value, int> = 0> 1330 // NOLINTNEXTLINE(google-explicit-constructor) 1331 int_(T value) { 1332 if (PYBIND11_SILENCE_MSVC_C4127(sizeof(T) <= sizeof(long))) { 1333 if (std::is_signed<T>::value) 1334 m_ptr = PyLong_FromLong((long) value); 1335 else 1336 m_ptr = PyLong_FromUnsignedLong((unsigned long) value); 1337 } else { 1338 if (std::is_signed<T>::value) 1339 m_ptr = PyLong_FromLongLong((long long) value); 1340 else 1341 m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value); 1342 } 1343 if (!m_ptr) pybind11_fail("Could not allocate int object!"); 1344 } 1345 1346 template <typename T, 1347 detail::enable_if_t<std::is_integral<T>::value, int> = 0> 1348 // NOLINTNEXTLINE(google-explicit-constructor) 1349 operator T() const { 1350 return std::is_unsigned<T>::value 1351 ? detail::as_unsigned<T>(m_ptr) 1352 : sizeof(T) <= sizeof(long) 1353 ? (T) PyLong_AsLong(m_ptr) 1354 : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr); 1355 } 1356 }; 1357 1358 class float_ : public object { 1359 public: 1360 PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float) 1361 // Allow implicit conversion from float/double: 1362 // NOLINTNEXTLINE(google-explicit-constructor) 1363 float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) { 1364 if (!m_ptr) pybind11_fail("Could not allocate float object!"); 1365 } 1366 // NOLINTNEXTLINE(google-explicit-constructor) 1367 float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) { 1368 if (!m_ptr) pybind11_fail("Could not allocate float object!"); 1369 } 1370 // NOLINTNEXTLINE(google-explicit-constructor) 1371 operator float() const { return (float) PyFloat_AsDouble(m_ptr); } 1372 // NOLINTNEXTLINE(google-explicit-constructor) 1373 operator double() const { return (double) PyFloat_AsDouble(m_ptr); } 1374 }; 1375 1376 class weakref : public object { 1377 public: 1378 PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref) 1379 explicit weakref(handle obj, handle callback = {}) 1380 : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) { 1381 if (!m_ptr) pybind11_fail("Could not allocate weak reference!"); 1382 } 1383 1384 private: 1385 static PyObject *raw_weakref(PyObject *o) { 1386 return PyWeakref_NewRef(o, nullptr); 1387 } 1388 }; 1389 1390 class slice : public object { 1391 public: 1392 PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check) 1393 slice(handle start, handle stop, handle step) { 1394 m_ptr = PySlice_New(start.ptr(), stop.ptr(), step.ptr()); 1395 if (!m_ptr) 1396 pybind11_fail("Could not allocate slice object!"); 1397 } 1398 1399 #ifdef PYBIND11_HAS_OPTIONAL 1400 slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t> step) 1401 : slice(index_to_object(start), index_to_object(stop), index_to_object(step)) {} 1402 #else 1403 slice(ssize_t start_, ssize_t stop_, ssize_t step_) 1404 : slice(int_(start_), int_(stop_), int_(step_)) {} 1405 #endif 1406 1407 bool compute(size_t length, size_t *start, size_t *stop, size_t *step, 1408 size_t *slicelength) const { 1409 return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr, 1410 (ssize_t) length, (ssize_t *) start, 1411 (ssize_t *) stop, (ssize_t *) step, 1412 (ssize_t *) slicelength) == 0; 1413 } 1414 bool compute(ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, 1415 ssize_t *slicelength) const { 1416 return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr, 1417 length, start, 1418 stop, step, 1419 slicelength) == 0; 1420 } 1421 1422 private: 1423 template <typename T> 1424 static object index_to_object(T index) { 1425 return index ? object(int_(*index)) : object(none()); 1426 } 1427 }; 1428 1429 class capsule : public object { 1430 public: 1431 PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact) 1432 PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()") 1433 capsule(PyObject *ptr, bool is_borrowed) : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) { } 1434 1435 explicit capsule(const void *value, const char *name = nullptr, void (*destructor)(PyObject *) = nullptr) 1436 : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) { 1437 if (!m_ptr) 1438 pybind11_fail("Could not allocate capsule object!"); 1439 } 1440 1441 PYBIND11_DEPRECATED("Please pass a destructor that takes a void pointer as input") 1442 capsule(const void *value, void (*destruct)(PyObject *)) 1443 : object(PyCapsule_New(const_cast<void*>(value), nullptr, destruct), stolen_t{}) { 1444 if (!m_ptr) 1445 pybind11_fail("Could not allocate capsule object!"); 1446 } 1447 1448 capsule(const void *value, void (*destructor)(void *)) { 1449 m_ptr = PyCapsule_New(const_cast<void *>(value), nullptr, [](PyObject *o) { 1450 auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o)); 1451 void *ptr = PyCapsule_GetPointer(o, nullptr); 1452 destructor(ptr); 1453 }); 1454 1455 if (!m_ptr) 1456 pybind11_fail("Could not allocate capsule object!"); 1457 1458 if (PyCapsule_SetContext(m_ptr, (void *) destructor) != 0) 1459 pybind11_fail("Could not set capsule context!"); 1460 } 1461 1462 explicit capsule(void (*destructor)()) { 1463 m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) { 1464 auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, nullptr)); 1465 destructor(); 1466 }); 1467 1468 if (!m_ptr) 1469 pybind11_fail("Could not allocate capsule object!"); 1470 } 1471 1472 // NOLINTNEXTLINE(google-explicit-constructor) 1473 template <typename T> operator T *() const { 1474 return get_pointer<T>(); 1475 } 1476 1477 /// Get the pointer the capsule holds. 1478 template<typename T = void> 1479 T* get_pointer() const { 1480 auto name = this->name(); 1481 T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name)); 1482 if (!result) { 1483 PyErr_Clear(); 1484 pybind11_fail("Unable to extract capsule contents!"); 1485 } 1486 return result; 1487 } 1488 1489 /// Replaces a capsule's pointer *without* calling the destructor on the existing one. 1490 void set_pointer(const void *value) { 1491 if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0) { 1492 PyErr_Clear(); 1493 pybind11_fail("Could not set capsule pointer"); 1494 } 1495 } 1496 1497 const char *name() const { return PyCapsule_GetName(m_ptr); } 1498 }; 1499 1500 class tuple : public object { 1501 public: 1502 PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple) 1503 template <typename SzType = ssize_t, 1504 detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> 1505 // Some compilers generate link errors when using `const SzType &` here: 1506 explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) { 1507 if (!m_ptr) pybind11_fail("Could not allocate tuple object!"); 1508 } 1509 size_t size() const { return (size_t) PyTuple_Size(m_ptr); } 1510 bool empty() const { return size() == 0; } 1511 detail::tuple_accessor operator[](size_t index) const { return {*this, index}; } 1512 detail::item_accessor operator[](handle h) const { return object::operator[](h); } 1513 detail::tuple_iterator begin() const { return {*this, 0}; } 1514 detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; } 1515 }; 1516 1517 // We need to put this into a separate function because the Intel compiler 1518 // fails to compile enable_if_t<all_of<is_keyword_or_ds<Args>...>::value> part below 1519 // (tested with ICC 2021.1 Beta 20200827). 1520 template <typename... Args> 1521 constexpr bool args_are_all_keyword_or_ds() 1522 { 1523 return detail::all_of<detail::is_keyword_or_ds<Args>...>::value; 1524 } 1525 1526 class dict : public object { 1527 public: 1528 PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict) 1529 dict() : object(PyDict_New(), stolen_t{}) { 1530 if (!m_ptr) pybind11_fail("Could not allocate dict object!"); 1531 } 1532 template <typename... Args, 1533 typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>, 1534 // MSVC workaround: it can't compile an out-of-line definition, so defer the collector 1535 typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>> 1536 explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) { } 1537 1538 size_t size() const { return (size_t) PyDict_Size(m_ptr); } 1539 bool empty() const { return size() == 0; } 1540 detail::dict_iterator begin() const { return {*this, 0}; } 1541 detail::dict_iterator end() const { return {}; } 1542 void clear() /* py-non-const */ { PyDict_Clear(ptr()); } 1543 template <typename T> bool contains(T &&key) const { 1544 return PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr()) == 1; 1545 } 1546 1547 private: 1548 /// Call the `dict` Python type -- always returns a new reference 1549 static PyObject *raw_dict(PyObject *op) { 1550 if (PyDict_Check(op)) 1551 return handle(op).inc_ref().ptr(); 1552 return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr); 1553 } 1554 }; 1555 1556 class sequence : public object { 1557 public: 1558 PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check) 1559 size_t size() const { 1560 ssize_t result = PySequence_Size(m_ptr); 1561 if (result == -1) 1562 throw error_already_set(); 1563 return (size_t) result; 1564 } 1565 bool empty() const { return size() == 0; } 1566 detail::sequence_accessor operator[](size_t index) const { return {*this, index}; } 1567 detail::item_accessor operator[](handle h) const { return object::operator[](h); } 1568 detail::sequence_iterator begin() const { return {*this, 0}; } 1569 detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; } 1570 }; 1571 1572 class list : public object { 1573 public: 1574 PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List) 1575 template <typename SzType = ssize_t, 1576 detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> 1577 // Some compilers generate link errors when using `const SzType &` here: 1578 explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) { 1579 if (!m_ptr) pybind11_fail("Could not allocate list object!"); 1580 } 1581 size_t size() const { return (size_t) PyList_Size(m_ptr); } 1582 bool empty() const { return size() == 0; } 1583 detail::list_accessor operator[](size_t index) const { return {*this, index}; } 1584 detail::item_accessor operator[](handle h) const { return object::operator[](h); } 1585 detail::list_iterator begin() const { return {*this, 0}; } 1586 detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; } 1587 template <typename T> void append(T &&val) /* py-non-const */ { 1588 PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()); 1589 } 1590 template <typename IdxType, 1591 typename ValType, 1592 detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> 1593 void insert(const IdxType &index, ValType &&val) /* py-non-const */ { 1594 PyList_Insert( 1595 m_ptr, ssize_t_cast(index), detail::object_or_cast(std::forward<ValType>(val)).ptr()); 1596 } 1597 }; 1598 1599 class args : public tuple { PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) }; 1600 class kwargs : public dict { PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check) }; 1601 1602 class set : public object { 1603 public: 1604 PYBIND11_OBJECT_CVT(set, object, PySet_Check, PySet_New) 1605 set() : object(PySet_New(nullptr), stolen_t{}) { 1606 if (!m_ptr) pybind11_fail("Could not allocate set object!"); 1607 } 1608 size_t size() const { return (size_t) PySet_Size(m_ptr); } 1609 bool empty() const { return size() == 0; } 1610 template <typename T> bool add(T &&val) /* py-non-const */ { 1611 return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0; 1612 } 1613 void clear() /* py-non-const */ { PySet_Clear(m_ptr); } 1614 template <typename T> bool contains(T &&val) const { 1615 return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1; 1616 } 1617 }; 1618 1619 class function : public object { 1620 public: 1621 PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check) 1622 handle cpp_function() const { 1623 handle fun = detail::get_function(m_ptr); 1624 if (fun && PyCFunction_Check(fun.ptr())) 1625 return fun; 1626 return handle(); 1627 } 1628 bool is_cpp_function() const { return (bool) cpp_function(); } 1629 }; 1630 1631 class staticmethod : public object { 1632 public: 1633 PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New) 1634 }; 1635 1636 class buffer : public object { 1637 public: 1638 PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer) 1639 1640 buffer_info request(bool writable = false) const { 1641 int flags = PyBUF_STRIDES | PyBUF_FORMAT; 1642 if (writable) flags |= PyBUF_WRITABLE; 1643 auto *view = new Py_buffer(); 1644 if (PyObject_GetBuffer(m_ptr, view, flags) != 0) { 1645 delete view; 1646 throw error_already_set(); 1647 } 1648 return buffer_info(view); 1649 } 1650 }; 1651 1652 class memoryview : public object { 1653 public: 1654 PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject) 1655 1656 /** \rst 1657 Creates ``memoryview`` from ``buffer_info``. 1658 1659 ``buffer_info`` must be created from ``buffer::request()``. Otherwise 1660 throws an exception. 1661 1662 For creating a ``memoryview`` from objects that support buffer protocol, 1663 use ``memoryview(const object& obj)`` instead of this constructor. 1664 \endrst */ 1665 explicit memoryview(const buffer_info& info) { 1666 if (!info.view()) 1667 pybind11_fail("Prohibited to create memoryview without Py_buffer"); 1668 // Note: PyMemoryView_FromBuffer never increments obj reference. 1669 m_ptr = (info.view()->obj) ? 1670 PyMemoryView_FromObject(info.view()->obj) : 1671 PyMemoryView_FromBuffer(info.view()); 1672 if (!m_ptr) 1673 pybind11_fail("Unable to create memoryview from buffer descriptor"); 1674 } 1675 1676 /** \rst 1677 Creates ``memoryview`` from static buffer. 1678 1679 This method is meant for providing a ``memoryview`` for C/C++ buffer not 1680 managed by Python. The caller is responsible for managing the lifetime 1681 of ``ptr`` and ``format``, which MUST outlive the memoryview constructed 1682 here. 1683 1684 See also: Python C API documentation for `PyMemoryView_FromBuffer`_. 1685 1686 .. _PyMemoryView_FromBuffer: https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer 1687 1688 :param ptr: Pointer to the buffer. 1689 :param itemsize: Byte size of an element. 1690 :param format: Pointer to the null-terminated format string. For 1691 homogeneous Buffers, this should be set to 1692 ``format_descriptor<T>::value``. 1693 :param shape: Shape of the tensor (1 entry per dimension). 1694 :param strides: Number of bytes between adjacent entries (for each 1695 per dimension). 1696 :param readonly: Flag to indicate if the underlying storage may be 1697 written to. 1698 \endrst */ 1699 static memoryview from_buffer( 1700 void *ptr, ssize_t itemsize, const char *format, 1701 detail::any_container<ssize_t> shape, 1702 detail::any_container<ssize_t> strides, bool readonly = false); 1703 1704 static memoryview from_buffer( 1705 const void *ptr, ssize_t itemsize, const char *format, 1706 detail::any_container<ssize_t> shape, 1707 detail::any_container<ssize_t> strides) { 1708 return memoryview::from_buffer( 1709 const_cast<void *>(ptr), itemsize, format, std::move(shape), std::move(strides), true); 1710 } 1711 1712 template<typename T> 1713 static memoryview from_buffer( 1714 T *ptr, detail::any_container<ssize_t> shape, 1715 detail::any_container<ssize_t> strides, bool readonly = false) { 1716 return memoryview::from_buffer( 1717 reinterpret_cast<void*>(ptr), sizeof(T), 1718 format_descriptor<T>::value, shape, strides, readonly); 1719 } 1720 1721 template<typename T> 1722 static memoryview from_buffer( 1723 const T *ptr, detail::any_container<ssize_t> shape, 1724 detail::any_container<ssize_t> strides) { 1725 return memoryview::from_buffer( 1726 const_cast<T*>(ptr), shape, strides, true); 1727 } 1728 1729 #if PY_MAJOR_VERSION >= 3 1730 /** \rst 1731 Creates ``memoryview`` from static memory. 1732 1733 This method is meant for providing a ``memoryview`` for C/C++ buffer not 1734 managed by Python. The caller is responsible for managing the lifetime 1735 of ``mem``, which MUST outlive the memoryview constructed here. 1736 1737 This method is not available in Python 2. 1738 1739 See also: Python C API documentation for `PyMemoryView_FromBuffer`_. 1740 1741 .. _PyMemoryView_FromMemory: https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory 1742 \endrst */ 1743 static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) { 1744 PyObject* ptr = PyMemoryView_FromMemory( 1745 reinterpret_cast<char*>(mem), size, 1746 (readonly) ? PyBUF_READ : PyBUF_WRITE); 1747 if (!ptr) 1748 pybind11_fail("Could not allocate memoryview object!"); 1749 return memoryview(object(ptr, stolen_t{})); 1750 } 1751 1752 static memoryview from_memory(const void *mem, ssize_t size) { 1753 return memoryview::from_memory(const_cast<void*>(mem), size, true); 1754 } 1755 1756 #ifdef PYBIND11_HAS_STRING_VIEW 1757 static memoryview from_memory(std::string_view mem) { 1758 return from_memory(const_cast<char*>(mem.data()), static_cast<ssize_t>(mem.size()), true); 1759 } 1760 #endif 1761 1762 #endif 1763 }; 1764 1765 /// @cond DUPLICATE 1766 inline memoryview memoryview::from_buffer( 1767 void *ptr, ssize_t itemsize, const char* format, 1768 detail::any_container<ssize_t> shape, 1769 detail::any_container<ssize_t> strides, bool readonly) { 1770 size_t ndim = shape->size(); 1771 if (ndim != strides->size()) 1772 pybind11_fail("memoryview: shape length doesn't match strides length"); 1773 ssize_t size = ndim != 0u ? 1 : 0; 1774 for (size_t i = 0; i < ndim; ++i) 1775 size *= (*shape)[i]; 1776 Py_buffer view; 1777 view.buf = ptr; 1778 view.obj = nullptr; 1779 view.len = size * itemsize; 1780 view.readonly = static_cast<int>(readonly); 1781 view.itemsize = itemsize; 1782 view.format = const_cast<char*>(format); 1783 view.ndim = static_cast<int>(ndim); 1784 view.shape = shape->data(); 1785 view.strides = strides->data(); 1786 view.suboffsets = nullptr; 1787 view.internal = nullptr; 1788 PyObject* obj = PyMemoryView_FromBuffer(&view); 1789 if (!obj) 1790 throw error_already_set(); 1791 return memoryview(object(obj, stolen_t{})); 1792 } 1793 /// @endcond 1794 /// @} pytypes 1795 1796 /// \addtogroup python_builtins 1797 /// @{ 1798 1799 /// Get the length of a Python object. 1800 inline size_t len(handle h) { 1801 ssize_t result = PyObject_Length(h.ptr()); 1802 if (result < 0) 1803 throw error_already_set(); 1804 return (size_t) result; 1805 } 1806 1807 /// Get the length hint of a Python object. 1808 /// Returns 0 when this cannot be determined. 1809 inline size_t len_hint(handle h) { 1810 #if PY_VERSION_HEX >= 0x03040000 1811 ssize_t result = PyObject_LengthHint(h.ptr(), 0); 1812 #else 1813 ssize_t result = PyObject_Length(h.ptr()); 1814 #endif 1815 if (result < 0) { 1816 // Sometimes a length can't be determined at all (eg generators) 1817 // In which case simply return 0 1818 PyErr_Clear(); 1819 return 0; 1820 } 1821 return (size_t) result; 1822 } 1823 1824 inline str repr(handle h) { 1825 PyObject *str_value = PyObject_Repr(h.ptr()); 1826 if (!str_value) throw error_already_set(); 1827 #if PY_MAJOR_VERSION < 3 1828 PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr); 1829 Py_XDECREF(str_value); str_value = unicode; 1830 if (!str_value) throw error_already_set(); 1831 #endif 1832 return reinterpret_steal<str>(str_value); 1833 } 1834 1835 inline iterator iter(handle obj) { 1836 PyObject *result = PyObject_GetIter(obj.ptr()); 1837 if (!result) { throw error_already_set(); } 1838 return reinterpret_steal<iterator>(result); 1839 } 1840 /// @} python_builtins 1841 1842 PYBIND11_NAMESPACE_BEGIN(detail) 1843 template <typename D> iterator object_api<D>::begin() const { return iter(derived()); } 1844 template <typename D> iterator object_api<D>::end() const { return iterator::sentinel(); } 1845 template <typename D> item_accessor object_api<D>::operator[](handle key) const { 1846 return {derived(), reinterpret_borrow<object>(key)}; 1847 } 1848 template <typename D> item_accessor object_api<D>::operator[](const char *key) const { 1849 return {derived(), pybind11::str(key)}; 1850 } 1851 template <typename D> obj_attr_accessor object_api<D>::attr(handle key) const { 1852 return {derived(), reinterpret_borrow<object>(key)}; 1853 } 1854 template <typename D> str_attr_accessor object_api<D>::attr(const char *key) const { 1855 return {derived(), key}; 1856 } 1857 template <typename D> args_proxy object_api<D>::operator*() const { 1858 return args_proxy(derived().ptr()); 1859 } 1860 template <typename D> template <typename T> bool object_api<D>::contains(T &&item) const { 1861 return attr("__contains__")(std::forward<T>(item)).template cast<bool>(); 1862 } 1863 1864 template <typename D> 1865 pybind11::str object_api<D>::str() const { return pybind11::str(derived()); } 1866 1867 template <typename D> 1868 str_attr_accessor object_api<D>::doc() const { return attr("__doc__"); } 1869 1870 template <typename D> 1871 handle object_api<D>::get_type() const { return type::handle_of(derived()); } 1872 1873 template <typename D> 1874 bool object_api<D>::rich_compare(object_api const &other, int value) const { 1875 int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value); 1876 if (rv == -1) 1877 throw error_already_set(); 1878 return rv == 1; 1879 } 1880 1881 #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \ 1882 template <typename D> object object_api<D>::op() const { \ 1883 object result = reinterpret_steal<object>(fn(derived().ptr())); \ 1884 if (!result.ptr()) \ 1885 throw error_already_set(); \ 1886 return result; \ 1887 } 1888 1889 #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \ 1890 template <typename D> \ 1891 object object_api<D>::op(object_api const &other) const { \ 1892 object result = reinterpret_steal<object>( \ 1893 fn(derived().ptr(), other.derived().ptr())); \ 1894 if (!result.ptr()) \ 1895 throw error_already_set(); \ 1896 return result; \ 1897 } 1898 1899 PYBIND11_MATH_OPERATOR_UNARY (operator~, PyNumber_Invert) 1900 PYBIND11_MATH_OPERATOR_UNARY (operator-, PyNumber_Negative) 1901 PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add) 1902 PYBIND11_MATH_OPERATOR_BINARY(operator+=, PyNumber_InPlaceAdd) 1903 PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract) 1904 PYBIND11_MATH_OPERATOR_BINARY(operator-=, PyNumber_InPlaceSubtract) 1905 PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply) 1906 PYBIND11_MATH_OPERATOR_BINARY(operator*=, PyNumber_InPlaceMultiply) 1907 PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide) 1908 PYBIND11_MATH_OPERATOR_BINARY(operator/=, PyNumber_InPlaceTrueDivide) 1909 PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or) 1910 PYBIND11_MATH_OPERATOR_BINARY(operator|=, PyNumber_InPlaceOr) 1911 PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And) 1912 PYBIND11_MATH_OPERATOR_BINARY(operator&=, PyNumber_InPlaceAnd) 1913 PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor) 1914 PYBIND11_MATH_OPERATOR_BINARY(operator^=, PyNumber_InPlaceXor) 1915 PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift) 1916 PYBIND11_MATH_OPERATOR_BINARY(operator<<=, PyNumber_InPlaceLshift) 1917 PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift) 1918 PYBIND11_MATH_OPERATOR_BINARY(operator>>=, PyNumber_InPlaceRshift) 1919 1920 #undef PYBIND11_MATH_OPERATOR_UNARY 1921 #undef PYBIND11_MATH_OPERATOR_BINARY 1922 1923 PYBIND11_NAMESPACE_END(detail) 1924 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)