Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-03-28 08:27:06

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 
0015 #include <assert.h>
0016 #include <cstddef>
0017 #include <exception>
0018 #include <frameobject.h>
0019 #include <iterator>
0020 #include <memory>
0021 #include <string>
0022 #include <type_traits>
0023 #include <typeinfo>
0024 #include <utility>
0025 
0026 #if defined(PYBIND11_HAS_OPTIONAL)
0027 #    include <optional>
0028 #endif
0029 
0030 #ifdef PYBIND11_HAS_STRING_VIEW
0031 #    include <string_view>
0032 #endif
0033 
0034 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0035 
0036 PYBIND11_WARNING_DISABLE_MSVC(4127)
0037 
0038 /* A few forward declarations */
0039 class handle;
0040 class object;
0041 class str;
0042 class iterator;
0043 class type;
0044 struct arg;
0045 struct arg_v;
0046 
0047 PYBIND11_NAMESPACE_BEGIN(detail)
0048 class args_proxy;
0049 bool isinstance_generic(handle obj, const std::type_info &tp);
0050 
0051 template <typename T>
0052 bool isinstance_native_enum(handle obj, const std::type_info &tp);
0053 
0054 // Accessor forward declarations
0055 template <typename Policy>
0056 class accessor;
0057 namespace accessor_policies {
0058 struct obj_attr;
0059 struct str_attr;
0060 struct generic_item;
0061 struct sequence_item;
0062 struct list_item;
0063 struct tuple_item;
0064 } // namespace accessor_policies
0065 // PLEASE KEEP handle_type_name SPECIALIZATIONS IN SYNC.
0066 using obj_attr_accessor = accessor<accessor_policies::obj_attr>;
0067 using str_attr_accessor = accessor<accessor_policies::str_attr>;
0068 using item_accessor = accessor<accessor_policies::generic_item>;
0069 using sequence_accessor = accessor<accessor_policies::sequence_item>;
0070 using list_accessor = accessor<accessor_policies::list_item>;
0071 using tuple_accessor = accessor<accessor_policies::tuple_item>;
0072 
0073 /// Tag and check to identify a class which implements the Python object API
0074 class pyobject_tag {};
0075 template <typename T>
0076 using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
0077 
0078 /** \rst
0079     A mixin class which adds common functions to `handle`, `object` and various accessors.
0080     The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``.
0081 \endrst */
0082 template <typename Derived>
0083 class object_api : public pyobject_tag {
0084     object_api() = default;
0085     const Derived &derived() const { return static_cast<const Derived &>(*this); }
0086     friend Derived;
0087 
0088 public:
0089     /** \rst
0090         Return an iterator equivalent to calling ``iter()`` in Python. The object
0091         must be a collection which supports the iteration protocol.
0092     \endrst */
0093     iterator begin() const;
0094     /// Return a sentinel which ends iteration.
0095     iterator end() const;
0096 
0097     /** \rst
0098         Return an internal functor to invoke the object's sequence protocol. Casting
0099         the returned ``detail::item_accessor`` instance to a `handle` or `object`
0100         subclass causes a corresponding call to ``__getitem__``. Assigning a `handle`
0101         or `object` subclass causes a call to ``__setitem__``.
0102     \endrst */
0103     item_accessor operator[](handle key) const;
0104     /// See above (the only difference is that the key's reference is stolen)
0105     item_accessor operator[](object &&key) const;
0106     /// See above (the only difference is that the key is provided as a string literal)
0107     item_accessor operator[](const char *key) const;
0108 
0109     /** \rst
0110         Return an internal functor to access the object's attributes. Casting the
0111         returned ``detail::obj_attr_accessor`` instance to a `handle` or `object`
0112         subclass causes a corresponding call to ``getattr``. Assigning a `handle`
0113         or `object` subclass causes a call to ``setattr``.
0114     \endrst */
0115     obj_attr_accessor attr(handle key) const;
0116     /// See above (the only difference is that the key's reference is stolen)
0117     obj_attr_accessor attr(object &&key) const;
0118     /// See above (the only difference is that the key is provided as a string literal)
0119     str_attr_accessor attr(const char *key) const;
0120 
0121     /** \rst
0122          Similar to the above attr functions with the difference that the templated Type
0123          is used to set the `__annotations__` dict value to the corresponding key. Worth noting
0124          that attr_with_type_hint is implemented in cast.h.
0125     \endrst */
0126     template <typename T>
0127     obj_attr_accessor attr_with_type_hint(handle key) const;
0128     /// See above (the only difference is that the key is provided as a string literal)
0129     template <typename T>
0130     str_attr_accessor attr_with_type_hint(const char *key) const;
0131 
0132     /** \rst
0133         Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple``
0134         or ``list`` for a function call. Applying another * to the result yields
0135         ** unpacking, e.g. to unpack a dict as function keyword arguments.
0136         See :ref:`calling_python_functions`.
0137     \endrst */
0138     args_proxy operator*() const;
0139 
0140     /// Check if the given item is contained within this object, i.e. ``item in obj``.
0141     template <typename T>
0142     bool contains(T &&item) const;
0143 
0144     /** \rst
0145         Assuming the Python object is a function or implements the ``__call__``
0146         protocol, ``operator()`` invokes the underlying function, passing an
0147         arbitrary set of parameters. The result is returned as a `object` and
0148         may need to be converted back into a Python object using `handle::cast()`.
0149 
0150         When some of the arguments cannot be converted to Python objects, the
0151         function will throw a `cast_error` exception. When the Python function
0152         call fails, a `error_already_set` exception is thrown.
0153     \endrst */
0154     template <return_value_policy policy = return_value_policy::automatic_reference,
0155               typename... Args>
0156     object operator()(Args &&...args) const;
0157     template <return_value_policy policy = return_value_policy::automatic_reference,
0158               typename... Args>
0159     PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)")
0160     object call(Args &&...args) const;
0161 
0162     /// Equivalent to ``obj is other`` in Python.
0163     bool is(object_api const &other) const { return derived().ptr() == other.derived().ptr(); }
0164     /// Equivalent to ``obj is None`` in Python.
0165     bool is_none() const { return derived().ptr() == Py_None; }
0166     /// Equivalent to obj == other in Python
0167     bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); }
0168     bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); }
0169     bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); }
0170     bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); }
0171     bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); }
0172     bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); }
0173 
0174     object operator-() const;
0175     object operator~() const;
0176     object operator+(object_api const &other) const;
0177     object operator+=(object_api const &other);
0178     object operator-(object_api const &other) const;
0179     object operator-=(object_api const &other);
0180     object operator*(object_api const &other) const;
0181     object operator*=(object_api const &other);
0182     object operator/(object_api const &other) const;
0183     object operator/=(object_api const &other);
0184     object operator|(object_api const &other) const;
0185     object operator|=(object_api const &other);
0186     object operator&(object_api const &other) const;
0187     object operator&=(object_api const &other);
0188     object operator^(object_api const &other) const;
0189     object operator^=(object_api const &other);
0190     object operator<<(object_api const &other) const;
0191     object operator<<=(object_api const &other);
0192     object operator>>(object_api const &other) const;
0193     object operator>>=(object_api const &other);
0194 
0195     PYBIND11_DEPRECATED("Use py::str(obj) instead")
0196     pybind11::str str() const;
0197 
0198     /// Get or set the object's docstring, i.e. ``obj.__doc__``.
0199     str_attr_accessor doc() const;
0200 
0201     /// Get or set the object's annotations, i.e. ``obj.__annotations__``.
0202     object annotations() const;
0203 
0204     /// Return the object's current reference count
0205     ssize_t ref_count() const {
0206 #ifdef PYPY_VERSION
0207         // PyPy uses the top few bits for REFCNT_FROM_PYPY & REFCNT_FROM_PYPY_LIGHT
0208         // Following pybind11 2.12.1 and older behavior and removing this part
0209         return static_cast<ssize_t>(static_cast<int>(Py_REFCNT(derived().ptr())));
0210 #else
0211         return Py_REFCNT(derived().ptr());
0212 #endif
0213     }
0214 
0215     PYBIND11_DEPRECATED("Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()")
0216     handle get_type() const;
0217 
0218 private:
0219     bool rich_compare(object_api const &other, int value) const;
0220 };
0221 
0222 template <typename T>
0223 using is_pyobj_ptr_or_nullptr_t = detail::any_of<std::is_same<T, PyObject *>,
0224                                                  std::is_same<T, PyObject *const>,
0225                                                  std::is_same<T, std::nullptr_t>>;
0226 
0227 PYBIND11_NAMESPACE_END(detail)
0228 
0229 #if !defined(PYBIND11_HANDLE_REF_DEBUG) && !defined(NDEBUG)
0230 #    define PYBIND11_HANDLE_REF_DEBUG
0231 #endif
0232 
0233 /** \rst
0234     Holds a reference to a Python object (no reference counting)
0235 
0236     The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a
0237     ``PyObject *`` in Python's C API). It does not perform any automatic reference
0238     counting and merely provides a basic C++ interface to various Python API functions.
0239 
0240     .. seealso::
0241         The `object` class inherits from `handle` and adds automatic reference
0242         counting features.
0243 \endrst */
0244 class handle : public detail::object_api<handle> {
0245 public:
0246     /// The default constructor creates a handle with a ``nullptr``-valued pointer
0247     handle() = default;
0248 
0249     /// Enable implicit conversion from ``PyObject *`` and ``nullptr``.
0250     /// Not using ``handle(PyObject *ptr)`` to avoid implicit conversion from ``0``.
0251     template <typename T,
0252               detail::enable_if_t<detail::is_pyobj_ptr_or_nullptr_t<T>::value, int> = 0>
0253     // NOLINTNEXTLINE(google-explicit-constructor)
0254     handle(T ptr) : m_ptr(ptr) {}
0255 
0256     /// Enable implicit conversion through ``T::operator PyObject *()``.
0257     template <
0258         typename T,
0259         detail::enable_if_t<detail::all_of<detail::none_of<std::is_base_of<handle, T>,
0260                                                            detail::is_pyobj_ptr_or_nullptr_t<T>>,
0261                                            std::is_convertible<T, PyObject *>>::value,
0262                             int>
0263         = 0>
0264     // NOLINTNEXTLINE(google-explicit-constructor)
0265     handle(T &obj) : m_ptr(obj) {}
0266 
0267     /// Return the underlying ``PyObject *`` pointer
0268     PyObject *ptr() const { return m_ptr; }
0269     PyObject *&ptr() { return m_ptr; }
0270 
0271     /** \rst
0272         Manually increase the reference count of the Python object. Usually, it is
0273         preferable to use the `object` class which derives from `handle` and calls
0274         this function automatically. Returns a reference to itself.
0275     \endrst */
0276     const handle &inc_ref() const & {
0277 #ifdef PYBIND11_HANDLE_REF_DEBUG
0278         inc_ref_counter(1);
0279 #endif
0280 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
0281         if (m_ptr != nullptr && PyGILState_Check() == 0) {
0282             throw_gilstate_error("pybind11::handle::inc_ref()");
0283         }
0284 #endif
0285         Py_XINCREF(m_ptr);
0286         return *this;
0287     }
0288 
0289     /** \rst
0290         Manually decrease the reference count of the Python object. Usually, it is
0291         preferable to use the `object` class which derives from `handle` and calls
0292         this function automatically. Returns a reference to itself.
0293     \endrst */
0294     const handle &dec_ref() const & {
0295 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
0296         if (m_ptr != nullptr && PyGILState_Check() == 0) {
0297             throw_gilstate_error("pybind11::handle::dec_ref()");
0298         }
0299 #endif
0300         Py_XDECREF(m_ptr);
0301         return *this;
0302     }
0303 
0304     /** \rst
0305         Attempt to cast the Python object into the given C++ type. A `cast_error`
0306         will be throw upon failure.
0307     \endrst */
0308     template <typename T>
0309     T cast() const;
0310     /// Return ``true`` when the `handle` wraps a valid Python object
0311     explicit operator bool() const { return m_ptr != nullptr; }
0312     /** \rst
0313         Deprecated: Check that the underlying pointers are the same.
0314         Equivalent to ``obj1 is obj2`` in Python.
0315     \endrst */
0316     PYBIND11_DEPRECATED("Use obj1.is(obj2) instead")
0317     bool operator==(const handle &h) const { return m_ptr == h.m_ptr; }
0318     PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead")
0319     bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }
0320     PYBIND11_DEPRECATED("Use handle::operator bool() instead")
0321     bool check() const { return m_ptr != nullptr; }
0322 
0323 protected:
0324     PyObject *m_ptr = nullptr;
0325 
0326 private:
0327 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
0328     void throw_gilstate_error(const std::string &function_name) const {
0329         fprintf(
0330             stderr,
0331             "%s is being called while the GIL is either not held or invalid. Please see "
0332             "https://pybind11.readthedocs.io/en/stable/advanced/"
0333             "misc.html#common-sources-of-global-interpreter-lock-errors for debugging advice.\n"
0334             "If you are convinced there is no bug in your code, you can #define "
0335             "PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF "
0336             "to disable this check. In that case you have to ensure this #define is consistently "
0337             "used for all translation units linked into a given pybind11 extension, otherwise "
0338             "there will be ODR violations.",
0339             function_name.c_str());
0340         if (Py_TYPE(m_ptr)->tp_name != nullptr) {
0341             fprintf(stderr,
0342                     " The failing %s call was triggered on a %s object.",
0343                     function_name.c_str(),
0344                     Py_TYPE(m_ptr)->tp_name);
0345         }
0346         fprintf(stderr, "\n");
0347         fflush(stderr);
0348         throw std::runtime_error(function_name + " PyGILState_Check() failure.");
0349     }
0350 #endif
0351 
0352 #ifdef PYBIND11_HANDLE_REF_DEBUG
0353     static std::size_t inc_ref_counter(std::size_t add) {
0354         thread_local std::size_t counter = 0;
0355         counter += add;
0356         return counter;
0357     }
0358 
0359 public:
0360     static std::size_t inc_ref_counter() { return inc_ref_counter(0); }
0361 #endif
0362 };
0363 
0364 inline void set_error(const handle &type, const char *message) {
0365     PyErr_SetString(type.ptr(), message);
0366 }
0367 
0368 inline void set_error(const handle &type, const handle &value) {
0369     PyErr_SetObject(type.ptr(), value.ptr());
0370 }
0371 
0372 /** \rst
0373     Holds a reference to a Python object (with reference counting)
0374 
0375     Like `handle`, the `object` class is a thin wrapper around an arbitrary Python
0376     object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it
0377     optionally increases the object's reference count upon construction, and it
0378     *always* decreases the reference count when the `object` instance goes out of
0379     scope and is destructed. When using `object` instances consistently, it is much
0380     easier to get reference counting right at the first attempt.
0381 \endrst */
0382 class object : public handle {
0383 public:
0384     object() = default;
0385     PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()")
0386     object(handle h, bool is_borrowed) : handle(h) {
0387         if (is_borrowed) {
0388             inc_ref();
0389         }
0390     }
0391     /// Copy constructor; always increases the reference count
0392     object(const object &o) : handle(o) { inc_ref(); }
0393     /// Move constructor; steals the object from ``other`` and preserves its reference count
0394     object(object &&other) noexcept : handle(other) { other.m_ptr = nullptr; }
0395     /// Destructor; automatically calls `handle::dec_ref()`
0396     ~object() { dec_ref(); }
0397 
0398     /** \rst
0399         Resets the internal pointer to ``nullptr`` without decreasing the
0400         object's reference count. The function returns a raw handle to the original
0401         Python object.
0402     \endrst */
0403     handle release() {
0404         PyObject *tmp = m_ptr;
0405         m_ptr = nullptr;
0406         return handle(tmp);
0407     }
0408 
0409     object &operator=(const object &other) {
0410         // Skip inc_ref and dec_ref if both objects are the same
0411         if (!this->is(other)) {
0412             other.inc_ref();
0413             // Use temporary variable to ensure `*this` remains valid while
0414             // `Py_XDECREF` executes, in case `*this` is accessible from Python.
0415             handle temp(m_ptr);
0416             m_ptr = other.m_ptr;
0417             temp.dec_ref();
0418         }
0419         return *this;
0420     }
0421 
0422     object &operator=(object &&other) noexcept {
0423         if (this != &other) {
0424             handle temp(m_ptr);
0425             m_ptr = other.m_ptr;
0426             other.m_ptr = nullptr;
0427             temp.dec_ref();
0428         }
0429         return *this;
0430     }
0431 
0432 #define PYBIND11_INPLACE_OP(iop)                                                                  \
0433     object iop(object_api const &other) { return operator=(handle::iop(other)); }
0434 
0435     PYBIND11_INPLACE_OP(operator+=)
0436     PYBIND11_INPLACE_OP(operator-=)
0437     PYBIND11_INPLACE_OP(operator*=)
0438     PYBIND11_INPLACE_OP(operator/=)
0439     PYBIND11_INPLACE_OP(operator|=)
0440     PYBIND11_INPLACE_OP(operator&=)
0441     PYBIND11_INPLACE_OP(operator^=)
0442     PYBIND11_INPLACE_OP(operator<<=)
0443     PYBIND11_INPLACE_OP(operator>>=)
0444 #undef PYBIND11_INPLACE_OP
0445 
0446     // Calling cast() on an object lvalue just copies (via handle::cast)
0447     template <typename T>
0448     T cast() const &;
0449     // Calling on an object rvalue does a move, if needed and/or possible
0450     template <typename T>
0451     T cast() &&;
0452 
0453 protected:
0454     // Tags for choosing constructors from raw PyObject *
0455     struct borrowed_t {};
0456     struct stolen_t {};
0457 
0458     /// @cond BROKEN
0459     template <typename T>
0460     friend T reinterpret_borrow(handle);
0461     template <typename T>
0462     friend T reinterpret_steal(handle);
0463     /// @endcond
0464 
0465 public:
0466     // Only accessible from derived classes and the reinterpret_* functions
0467     object(handle h, borrowed_t) : handle(h) { inc_ref(); }
0468     object(handle h, stolen_t) : handle(h) {}
0469 };
0470 
0471 /** \rst
0472     Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference.
0473     The target type ``T`` must be `object` or one of its derived classes. The function
0474     doesn't do any conversions or checks. It's up to the user to make sure that the
0475     target type is correct.
0476 
0477     .. code-block:: cpp
0478 
0479         PyObject *p = PyList_GetItem(obj, index);
0480         py::object o = reinterpret_borrow<py::object>(p);
0481         // or
0482         py::tuple t = reinterpret_borrow<py::tuple>(p); // <-- `p` must be already be a `tuple`
0483 \endrst */
0484 template <typename T>
0485 T reinterpret_borrow(handle h) {
0486     return {h, object::borrowed_t{}};
0487 }
0488 
0489 /** \rst
0490     Like `reinterpret_borrow`, but steals the reference.
0491 
0492      .. code-block:: cpp
0493 
0494         PyObject *p = PyObject_Str(obj);
0495         py::str s = reinterpret_steal<py::str>(p); // <-- `p` must be already be a `str`
0496 \endrst */
0497 template <typename T>
0498 T reinterpret_steal(handle h) {
0499     return {h, object::stolen_t{}};
0500 }
0501 
0502 PYBIND11_NAMESPACE_BEGIN(detail)
0503 
0504 // Equivalent to obj.__class__.__name__ (or obj.__name__ if obj is a class).
0505 inline const char *obj_class_name(PyObject *obj) {
0506     if (PyType_Check(obj)) {
0507         return reinterpret_cast<PyTypeObject *>(obj)->tp_name;
0508     }
0509     return Py_TYPE(obj)->tp_name;
0510 }
0511 
0512 std::string error_string();
0513 
0514 // The code in this struct is very unusual, to minimize the chances of
0515 // masking bugs (elsewhere) by errors during the error handling (here).
0516 // This is meant to be a lifeline for troubleshooting long-running processes
0517 // that crash under conditions that are virtually impossible to reproduce.
0518 // Low-level implementation alternatives are preferred to higher-level ones
0519 // that might raise cascading exceptions. Last-ditch-kind-of attempts are made
0520 // to report as much of the original error as possible, even if there are
0521 // secondary issues obtaining some of the details.
0522 struct error_fetch_and_normalize {
0523     // This comment only applies to Python <= 3.11:
0524     //     Immediate normalization is long-established behavior (starting with
0525     //     https://github.com/pybind/pybind11/commit/135ba8deafb8bf64a15b24d1513899eb600e2011
0526     //     from Sep 2016) and safest. Normalization could be deferred, but this could mask
0527     //     errors elsewhere, the performance gain is very minor in typical situations
0528     //     (usually the dominant bottleneck is EH unwinding), and the implementation here
0529     //     would be more complex.
0530     // Starting with Python 3.12, PyErr_Fetch() normalizes exceptions immediately.
0531     // Any errors during normalization are tracked under __notes__.
0532     explicit error_fetch_and_normalize(const char *called) {
0533         PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
0534         if (!m_type) {
0535             pybind11_fail("Internal error: " + std::string(called)
0536                           + " called while "
0537                             "Python error indicator not set.");
0538         }
0539         const char *exc_type_name_orig = detail::obj_class_name(m_type.ptr());
0540         if (exc_type_name_orig == nullptr) {
0541             pybind11_fail("Internal error: " + std::string(called)
0542                           + " failed to obtain the name "
0543                             "of the original active exception type.");
0544         }
0545         m_lazy_error_string = exc_type_name_orig;
0546 #if PY_VERSION_HEX >= 0x030C0000
0547         // The presence of __notes__ is likely due to exception normalization
0548         // errors, although that is not necessarily true, therefore insert a
0549         // hint only:
0550         if (PyObject_HasAttrString(m_value.ptr(), "__notes__")) {
0551             m_lazy_error_string += "[WITH __notes__]";
0552         }
0553 #else
0554         // PyErr_NormalizeException() may change the exception type if there are cascading
0555         // failures. This can potentially be extremely confusing.
0556         PyErr_NormalizeException(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
0557         if (m_type.ptr() == nullptr) {
0558             pybind11_fail("Internal error: " + std::string(called)
0559                           + " failed to normalize the "
0560                             "active exception.");
0561         }
0562         const char *exc_type_name_norm = detail::obj_class_name(m_type.ptr());
0563         if (exc_type_name_norm == nullptr) {
0564             pybind11_fail("Internal error: " + std::string(called)
0565                           + " failed to obtain the name "
0566                             "of the normalized active exception type.");
0567         }
0568         if (exc_type_name_norm != m_lazy_error_string) {
0569             std::string msg = std::string(called)
0570                               + ": MISMATCH of original and normalized "
0571                                 "active exception types: ";
0572             msg += "ORIGINAL ";
0573             msg += m_lazy_error_string;
0574             msg += " REPLACED BY ";
0575             msg += exc_type_name_norm;
0576             msg += ": " + format_value_and_trace();
0577             pybind11_fail(msg);
0578         }
0579 #endif
0580     }
0581 
0582     error_fetch_and_normalize(const error_fetch_and_normalize &) = delete;
0583     error_fetch_and_normalize(error_fetch_and_normalize &&) = delete;
0584 
0585     std::string format_value_and_trace() const {
0586         std::string result;
0587         std::string message_error_string;
0588         if (m_value) {
0589             auto value_str = reinterpret_steal<object>(PyObject_Str(m_value.ptr()));
0590             constexpr const char *message_unavailable_exc
0591                 = "<MESSAGE UNAVAILABLE DUE TO ANOTHER EXCEPTION>";
0592             if (!value_str) {
0593                 message_error_string = detail::error_string();
0594                 result = message_unavailable_exc;
0595             } else {
0596                 // Not using `value_str.cast<std::string>()`, to not potentially throw a secondary
0597                 // error_already_set that will then result in process termination (#4288).
0598                 auto value_bytes = reinterpret_steal<object>(
0599                     PyUnicode_AsEncodedString(value_str.ptr(), "utf-8", "backslashreplace"));
0600                 if (!value_bytes) {
0601                     message_error_string = detail::error_string();
0602                     result = message_unavailable_exc;
0603                 } else {
0604                     char *buffer = nullptr;
0605                     Py_ssize_t length = 0;
0606                     if (PyBytes_AsStringAndSize(value_bytes.ptr(), &buffer, &length) == -1) {
0607                         message_error_string = detail::error_string();
0608                         result = message_unavailable_exc;
0609                     } else {
0610                         result = std::string(buffer, static_cast<std::size_t>(length));
0611                     }
0612                 }
0613             }
0614 #if PY_VERSION_HEX >= 0x030B0000
0615             auto notes
0616                 = reinterpret_steal<object>(PyObject_GetAttrString(m_value.ptr(), "__notes__"));
0617             if (!notes) {
0618                 PyErr_Clear(); // No notes is good news.
0619             } else {
0620                 auto len_notes = PyList_Size(notes.ptr());
0621                 if (len_notes < 0) {
0622                     result += "\nFAILURE obtaining len(__notes__): " + detail::error_string();
0623                 } else {
0624                     result += "\n__notes__ (len=" + std::to_string(len_notes) + "):";
0625                     for (ssize_t i = 0; i < len_notes; i++) {
0626                         PyObject *note = PyList_GET_ITEM(notes.ptr(), i);
0627                         auto note_bytes = reinterpret_steal<object>(
0628                             PyUnicode_AsEncodedString(note, "utf-8", "backslashreplace"));
0629                         if (!note_bytes) {
0630                             result += "\nFAILURE obtaining __notes__[" + std::to_string(i)
0631                                       + "]: " + detail::error_string();
0632                         } else {
0633                             char *buffer = nullptr;
0634                             Py_ssize_t length = 0;
0635                             if (PyBytes_AsStringAndSize(note_bytes.ptr(), &buffer, &length)
0636                                 == -1) {
0637                                 result += "\nFAILURE formatting __notes__[" + std::to_string(i)
0638                                           + "]: " + detail::error_string();
0639                             } else {
0640                                 result += '\n';
0641                                 result += std::string(buffer, static_cast<std::size_t>(length));
0642                             }
0643                         }
0644                     }
0645                 }
0646             }
0647 #endif
0648         } else {
0649             result = "<MESSAGE UNAVAILABLE>";
0650         }
0651         if (result.empty()) {
0652             result = "<EMPTY MESSAGE>";
0653         }
0654 
0655         bool have_trace = false;
0656         if (m_trace) {
0657 #if !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON)
0658             auto *tb = reinterpret_cast<PyTracebackObject *>(m_trace.ptr());
0659 
0660             // Get the deepest trace possible.
0661             while (tb->tb_next) {
0662                 tb = tb->tb_next;
0663             }
0664 
0665             PyFrameObject *frame = tb->tb_frame;
0666             Py_XINCREF(frame);
0667             result += "\n\nAt:\n";
0668             while (frame) {
0669 #    if PY_VERSION_HEX >= 0x030900B1
0670                 PyCodeObject *f_code = PyFrame_GetCode(frame);
0671 #    else
0672                 PyCodeObject *f_code = frame->f_code;
0673                 Py_INCREF(f_code);
0674 #    endif
0675                 int lineno = PyFrame_GetLineNumber(frame);
0676                 result += "  ";
0677                 result += handle(f_code->co_filename).cast<std::string>();
0678                 result += '(';
0679                 result += std::to_string(lineno);
0680                 result += "): ";
0681                 result += handle(f_code->co_name).cast<std::string>();
0682                 result += '\n';
0683                 Py_DECREF(f_code);
0684 #    if PY_VERSION_HEX >= 0x030900B1
0685                 auto *b_frame = PyFrame_GetBack(frame);
0686 #    else
0687                 auto *b_frame = frame->f_back;
0688                 Py_XINCREF(b_frame);
0689 #    endif
0690                 Py_DECREF(frame);
0691                 frame = b_frame;
0692             }
0693 
0694             have_trace = true;
0695 #endif //! defined(PYPY_VERSION)
0696         }
0697 
0698         if (!message_error_string.empty()) {
0699             if (!have_trace) {
0700                 result += '\n';
0701             }
0702             result += "\nMESSAGE UNAVAILABLE DUE TO EXCEPTION: " + message_error_string;
0703         }
0704 
0705         return result;
0706     }
0707 
0708     std::string const &error_string() const {
0709         if (!m_lazy_error_string_completed) {
0710             m_lazy_error_string += ": " + format_value_and_trace();
0711             m_lazy_error_string_completed = true;
0712         }
0713         return m_lazy_error_string;
0714     }
0715 
0716     void restore() {
0717         if (m_restore_called) {
0718             pybind11_fail("Internal error: pybind11::detail::error_fetch_and_normalize::restore() "
0719                           "called a second time. ORIGINAL ERROR: "
0720                           + error_string());
0721         }
0722         PyErr_Restore(m_type.inc_ref().ptr(), m_value.inc_ref().ptr(), m_trace.inc_ref().ptr());
0723         m_restore_called = true;
0724     }
0725 
0726     bool matches(handle exc) const {
0727         return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0);
0728     }
0729 
0730     // Not protecting these for simplicity.
0731     object m_type, m_value, m_trace;
0732 
0733 private:
0734     // Only protecting invariants.
0735     mutable std::string m_lazy_error_string;
0736     mutable bool m_lazy_error_string_completed = false;
0737     mutable bool m_restore_called = false;
0738 };
0739 
0740 inline std::string error_string() {
0741     return error_fetch_and_normalize("pybind11::detail::error_string").error_string();
0742 }
0743 
0744 PYBIND11_NAMESPACE_END(detail)
0745 
0746 /// Fetch and hold an error which was already set in Python.  An instance of this is typically
0747 /// thrown to propagate python-side errors back through C++ which can either be caught manually or
0748 /// else falls back to the function dispatcher (which then raises the captured error back to
0749 /// python).
0750 class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::exception {
0751 public:
0752     /// Fetches the current Python exception (using PyErr_Fetch()), which will clear the
0753     /// current Python error indicator.
0754     error_already_set()
0755         : m_fetched_error{new detail::error_fetch_and_normalize("pybind11::error_already_set"),
0756                           m_fetched_error_deleter} {}
0757 
0758     /// The what() result is built lazily on demand.
0759     /// WARNING: This member function needs to acquire the Python GIL. This can lead to
0760     ///          crashes (undefined behavior) if the Python interpreter is finalizing.
0761     const char *what() const noexcept override;
0762 
0763     /// Restores the currently-held Python error (which will clear the Python error indicator first
0764     /// if already set).
0765     /// NOTE: This member function will always restore the normalized exception, which may or may
0766     ///       not be the original Python exception.
0767     /// WARNING: The GIL must be held when this member function is called!
0768     void restore() { m_fetched_error->restore(); }
0769 
0770     /// If it is impossible to raise the currently-held error, such as in a destructor, we can
0771     /// write it out using Python's unraisable hook (`sys.unraisablehook`). The error context
0772     /// should be some object whose `repr()` helps identify the location of the error. Python
0773     /// already knows the type and value of the error, so there is no need to repeat that.
0774     void discard_as_unraisable(object err_context) {
0775         restore();
0776         PyErr_WriteUnraisable(err_context.ptr());
0777     }
0778     /// An alternate version of `discard_as_unraisable()`, where a string provides information on
0779     /// the location of the error. For example, `__func__` could be helpful.
0780     /// WARNING: The GIL must be held when this member function is called!
0781     void discard_as_unraisable(const char *err_context) {
0782         discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context)));
0783     }
0784 
0785     // Does nothing; provided for backwards compatibility.
0786     PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated")
0787     void clear() {}
0788 
0789     /// Check if the currently trapped error type matches the given Python exception class (or a
0790     /// subclass thereof).  May also be passed a tuple to search for any exception class matches in
0791     /// the given tuple.
0792     bool matches(handle exc) const { return m_fetched_error->matches(exc); }
0793 
0794     const object &type() const { return m_fetched_error->m_type; }
0795     const object &value() const { return m_fetched_error->m_value; }
0796     const object &trace() const { return m_fetched_error->m_trace; }
0797 
0798 private:
0799     std::shared_ptr<detail::error_fetch_and_normalize> m_fetched_error;
0800 
0801     /// WARNING: This custom deleter needs to acquire the Python GIL. This can lead to
0802     ///          crashes (undefined behavior) if the Python interpreter is finalizing.
0803     static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr);
0804 };
0805 
0806 /// Replaces the current Python error indicator with the chosen error, performing a
0807 /// 'raise from' to indicate that the chosen error was caused by the original error.
0808 inline void raise_from(PyObject *type, const char *message) {
0809     // Based on _PyErr_FormatVFromCause:
0810     // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405
0811     // See https://github.com/pybind/pybind11/pull/2112 for details.
0812     PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr;
0813 
0814     assert(PyErr_Occurred());
0815     PyErr_Fetch(&exc, &val, &tb);
0816     PyErr_NormalizeException(&exc, &val, &tb);
0817     if (tb != nullptr) {
0818         PyException_SetTraceback(val, tb);
0819         Py_DECREF(tb);
0820     }
0821     Py_DECREF(exc);
0822     assert(!PyErr_Occurred());
0823 
0824     PyErr_SetString(type, message);
0825 
0826     PyErr_Fetch(&exc, &val2, &tb);
0827     PyErr_NormalizeException(&exc, &val2, &tb);
0828     Py_INCREF(val);
0829     PyException_SetCause(val2, val);
0830     PyException_SetContext(val2, val);
0831     PyErr_Restore(exc, val2, tb);
0832 }
0833 
0834 /// Sets the current Python error indicator with the chosen error, performing a 'raise from'
0835 /// from the error contained in error_already_set to indicate that the chosen error was
0836 /// caused by the original error.
0837 inline void raise_from(error_already_set &err, PyObject *type, const char *message) {
0838     err.restore();
0839     raise_from(type, message);
0840 }
0841 
0842 /** \defgroup python_builtins const_name
0843     Unless stated otherwise, the following C++ functions behave the same
0844     as their Python counterparts.
0845  */
0846 
0847 /** \ingroup python_builtins
0848     \rst
0849     Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of
0850     `object` or a class which was exposed to Python as ``py::class_<T>``.
0851 \endrst */
0852 template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0>
0853 bool isinstance(handle obj) {
0854     return T::check_(obj);
0855 }
0856 
0857 template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0>
0858 bool isinstance(handle obj) {
0859     return detail::isinstance_native_enum<T>(obj, typeid(T))
0860            || detail::isinstance_generic(obj, typeid(T));
0861 }
0862 
0863 template <>
0864 inline bool isinstance<handle>(handle) = delete;
0865 template <>
0866 inline bool isinstance<object>(handle obj) {
0867     return obj.ptr() != nullptr;
0868 }
0869 
0870 /// \ingroup python_builtins
0871 /// Return true if ``obj`` is an instance of the ``type``.
0872 inline bool isinstance(handle obj, handle type) {
0873     const auto result = PyObject_IsInstance(obj.ptr(), type.ptr());
0874     if (result == -1) {
0875         throw error_already_set();
0876     }
0877     return result != 0;
0878 }
0879 
0880 /// \addtogroup python_builtins
0881 /// @{
0882 inline bool hasattr(handle obj, handle name) {
0883     return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1;
0884 }
0885 
0886 inline bool hasattr(handle obj, const char *name) {
0887     return PyObject_HasAttrString(obj.ptr(), name) == 1;
0888 }
0889 
0890 inline void delattr(handle obj, handle name) {
0891     if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) {
0892         throw error_already_set();
0893     }
0894 }
0895 
0896 inline void delattr(handle obj, const char *name) {
0897     if (PyObject_DelAttrString(obj.ptr(), name) != 0) {
0898         throw error_already_set();
0899     }
0900 }
0901 
0902 inline object getattr(handle obj, handle name) {
0903     PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr());
0904     if (!result) {
0905         throw error_already_set();
0906     }
0907     return reinterpret_steal<object>(result);
0908 }
0909 
0910 inline object getattr(handle obj, const char *name) {
0911     PyObject *result = PyObject_GetAttrString(obj.ptr(), name);
0912     if (!result) {
0913         throw error_already_set();
0914     }
0915     return reinterpret_steal<object>(result);
0916 }
0917 
0918 inline object getattr(handle obj, handle name, handle default_) {
0919     if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) {
0920         return reinterpret_steal<object>(result);
0921     }
0922     PyErr_Clear();
0923     return reinterpret_borrow<object>(default_);
0924 }
0925 
0926 inline object getattr(handle obj, const char *name, handle default_) {
0927     if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) {
0928         return reinterpret_steal<object>(result);
0929     }
0930     PyErr_Clear();
0931     return reinterpret_borrow<object>(default_);
0932 }
0933 
0934 inline void setattr(handle obj, handle name, handle value) {
0935     if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) {
0936         throw error_already_set();
0937     }
0938 }
0939 
0940 inline void setattr(handle obj, const char *name, handle value) {
0941     if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) {
0942         throw error_already_set();
0943     }
0944 }
0945 
0946 inline ssize_t hash(handle obj) {
0947     auto h = PyObject_Hash(obj.ptr());
0948     if (h == -1) {
0949         throw error_already_set();
0950     }
0951     return h;
0952 }
0953 
0954 /// @} python_builtins
0955 
0956 PYBIND11_NAMESPACE_BEGIN(detail)
0957 inline handle get_function(handle value) {
0958     if (value) {
0959         if (PyInstanceMethod_Check(value.ptr())) {
0960             value = PyInstanceMethod_GET_FUNCTION(value.ptr());
0961         } else if (PyMethod_Check(value.ptr())) {
0962             value = PyMethod_GET_FUNCTION(value.ptr());
0963         }
0964     }
0965     return value;
0966 }
0967 
0968 // Reimplementation of python's dict helper functions to ensure that exceptions
0969 // aren't swallowed (see #2862)
0970 
0971 // copied from cpython _PyDict_GetItemStringWithError
0972 inline PyObject *dict_getitemstring(PyObject *v, const char *key) {
0973     PyObject *kv = nullptr, *rv = nullptr;
0974     kv = PyUnicode_FromString(key);
0975     if (kv == nullptr) {
0976         throw error_already_set();
0977     }
0978 
0979     rv = PyDict_GetItemWithError(v, kv);
0980     Py_DECREF(kv);
0981     if (rv == nullptr && PyErr_Occurred()) {
0982         throw error_already_set();
0983     }
0984     return rv;
0985 }
0986 
0987 inline PyObject *dict_getitem(PyObject *v, PyObject *key) {
0988     PyObject *rv = PyDict_GetItemWithError(v, key);
0989     if (rv == nullptr && PyErr_Occurred()) {
0990         throw error_already_set();
0991     }
0992     return rv;
0993 }
0994 
0995 inline PyObject *dict_getitemstringref(PyObject *v, const char *key) {
0996 #if PY_VERSION_HEX >= 0x030D0000
0997     PyObject *rv;
0998     if (PyDict_GetItemStringRef(v, key, &rv) < 0) {
0999         throw error_already_set();
1000     }
1001     return rv;
1002 #else
1003     PyObject *rv = dict_getitemstring(v, key);
1004     if (rv == nullptr && PyErr_Occurred()) {
1005         throw error_already_set();
1006     }
1007     Py_XINCREF(rv);
1008     return rv;
1009 #endif
1010 }
1011 
1012 // Helper aliases/functions to support implicit casting of values given to python
1013 // accessors/methods. When given a pyobject, this simply returns the pyobject as-is; for other C++
1014 // type, the value goes through pybind11::cast(obj) to convert it to an `object`.
1015 template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0>
1016 auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) {
1017     return std::forward<T>(o);
1018 }
1019 // The following casting version is implemented in cast.h:
1020 template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0>
1021 object object_or_cast(T &&o);
1022 // Match a PyObject*, which we want to convert directly to handle via its converting constructor
1023 inline handle object_or_cast(PyObject *ptr) { return ptr; }
1024 
1025 PYBIND11_WARNING_PUSH
1026 PYBIND11_WARNING_DISABLE_MSVC(4522) // warning C4522: multiple assignment operators specified
1027 template <typename Policy>
1028 class accessor : public object_api<accessor<Policy>> {
1029     using key_type = typename Policy::key_type;
1030 
1031 public:
1032     accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) {}
1033     accessor(const accessor &) = default;
1034     accessor(accessor &&) noexcept = default;
1035 
1036     // accessor overload required to override default assignment operator (templates are not
1037     // allowed to replace default compiler-generated assignments).
1038     void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); }
1039     void operator=(const accessor &a) & { operator=(handle(a)); }
1040 
1041     template <typename T>
1042     void operator=(T &&value) && {
1043         Policy::set(obj, key, object_or_cast(std::forward<T>(value)));
1044     }
1045     template <typename T>
1046     void operator=(T &&value) & {
1047         get_cache() = ensure_object(object_or_cast(std::forward<T>(value)));
1048     }
1049 
1050     template <typename T = Policy>
1051     PYBIND11_DEPRECATED(
1052         "Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
1053     explicit
1054     operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value
1055                              || std::is_same<T, accessor_policies::obj_attr>::value,
1056                          bool>() const {
1057         return hasattr(obj, key);
1058     }
1059     template <typename T = Policy>
1060     PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
1061     explicit
1062     operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const {
1063         return obj.contains(key);
1064     }
1065 
1066     // NOLINTNEXTLINE(google-explicit-constructor)
1067     operator object() const { return get_cache(); }
1068     PyObject *ptr() const { return get_cache().ptr(); }
1069     template <typename T>
1070     T cast() const {
1071         return get_cache().template cast<T>();
1072     }
1073 
1074 private:
1075     static object ensure_object(object &&o) { return std::move(o); }
1076     static object ensure_object(handle h) { return reinterpret_borrow<object>(h); }
1077 
1078     object &get_cache() const {
1079         if (!cache) {
1080             cache = Policy::get(obj, key);
1081         }
1082         return cache;
1083     }
1084 
1085 private:
1086     handle obj;
1087     key_type key;
1088     mutable object cache;
1089 };
1090 PYBIND11_WARNING_POP
1091 
1092 PYBIND11_NAMESPACE_BEGIN(accessor_policies)
1093 struct obj_attr {
1094     using key_type = object;
1095     static object get(handle obj, handle key) { return getattr(obj, key); }
1096     static void set(handle obj, handle key, handle val) { setattr(obj, key, val); }
1097 };
1098 
1099 struct str_attr {
1100     using key_type = const char *;
1101     static object get(handle obj, const char *key) { return getattr(obj, key); }
1102     static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); }
1103 };
1104 
1105 struct generic_item {
1106     using key_type = object;
1107 
1108     static object get(handle obj, handle key) {
1109         PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr());
1110         if (!result) {
1111             throw error_already_set();
1112         }
1113         return reinterpret_steal<object>(result);
1114     }
1115 
1116     static void set(handle obj, handle key, handle val) {
1117         if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) {
1118             throw error_already_set();
1119         }
1120     }
1121 };
1122 
1123 struct sequence_item {
1124     using key_type = size_t;
1125 
1126     template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1127     static object get(handle obj, const IdxType &index) {
1128         PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index));
1129         if (!result) {
1130             throw error_already_set();
1131         }
1132         return reinterpret_steal<object>(result);
1133     }
1134 
1135     template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1136     static void set(handle obj, const IdxType &index, handle val) {
1137         // PySequence_SetItem does not steal a reference to 'val'
1138         if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) {
1139             throw error_already_set();
1140         }
1141     }
1142 };
1143 
1144 struct list_item {
1145     using key_type = size_t;
1146 
1147     template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1148     static object get(handle obj, const IdxType &index) {
1149         PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index));
1150         if (!result) {
1151             throw error_already_set();
1152         }
1153         return reinterpret_borrow<object>(result);
1154     }
1155 
1156     template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1157     static void set(handle obj, const IdxType &index, handle val) {
1158         // PyList_SetItem steals a reference to 'val'
1159         if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
1160             throw error_already_set();
1161         }
1162     }
1163 };
1164 
1165 struct tuple_item {
1166     using key_type = size_t;
1167 
1168     template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1169     static object get(handle obj, const IdxType &index) {
1170         PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index));
1171         if (!result) {
1172             throw error_already_set();
1173         }
1174         return reinterpret_borrow<object>(result);
1175     }
1176 
1177     template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1178     static void set(handle obj, const IdxType &index, handle val) {
1179         // PyTuple_SetItem steals a reference to 'val'
1180         if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
1181             throw error_already_set();
1182         }
1183     }
1184 };
1185 PYBIND11_NAMESPACE_END(accessor_policies)
1186 
1187 /// STL iterator template used for tuple, list, sequence and dict
1188 template <typename Policy>
1189 class generic_iterator : public Policy {
1190     using It = generic_iterator;
1191 
1192 public:
1193     using difference_type = ssize_t;
1194     using iterator_category = typename Policy::iterator_category;
1195     using value_type = typename Policy::value_type;
1196     using reference = typename Policy::reference;
1197     using pointer = typename Policy::pointer;
1198 
1199     generic_iterator() = default;
1200     generic_iterator(handle seq, ssize_t index) : Policy(seq, index) {}
1201 
1202     // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1203     reference operator*() const { return Policy::dereference(); }
1204     // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1205     reference operator[](difference_type n) const { return *(*this + n); }
1206     pointer operator->() const { return **this; }
1207 
1208     It &operator++() {
1209         Policy::increment();
1210         return *this;
1211     }
1212     It operator++(int) {
1213         auto copy = *this;
1214         Policy::increment();
1215         return copy;
1216     }
1217     It &operator--() {
1218         Policy::decrement();
1219         return *this;
1220     }
1221     It operator--(int) {
1222         auto copy = *this;
1223         Policy::decrement();
1224         return copy;
1225     }
1226     It &operator+=(difference_type n) {
1227         Policy::advance(n);
1228         return *this;
1229     }
1230     It &operator-=(difference_type n) {
1231         Policy::advance(-n);
1232         return *this;
1233     }
1234 
1235     friend It operator+(const It &a, difference_type n) {
1236         auto copy = a;
1237         return copy += n;
1238     }
1239     friend It operator+(difference_type n, const It &b) { return b + n; }
1240     friend It operator-(const It &a, difference_type n) {
1241         auto copy = a;
1242         return copy -= n;
1243     }
1244     friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); }
1245 
1246     friend bool operator==(const It &a, const It &b) { return a.equal(b); }
1247     friend bool operator!=(const It &a, const It &b) { return !(a == b); }
1248     friend bool operator<(const It &a, const It &b) { return b - a > 0; }
1249     friend bool operator>(const It &a, const It &b) { return b < a; }
1250     friend bool operator>=(const It &a, const It &b) { return !(a < b); }
1251     friend bool operator<=(const It &a, const It &b) { return !(a > b); }
1252 };
1253 
1254 PYBIND11_NAMESPACE_BEGIN(iterator_policies)
1255 /// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers
1256 template <typename T>
1257 struct arrow_proxy {
1258     T value;
1259 
1260     // NOLINTNEXTLINE(google-explicit-constructor)
1261     arrow_proxy(T &&value) noexcept : value(std::move(value)) {}
1262     T *operator->() const { return &value; }
1263 };
1264 
1265 /// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS``
1266 class sequence_fast_readonly {
1267 protected:
1268     using iterator_category = std::random_access_iterator_tag;
1269     using value_type = handle;
1270     using reference = const handle; // PR #3263
1271     using pointer = arrow_proxy<const handle>;
1272 
1273     sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) {}
1274     sequence_fast_readonly() = default;
1275 
1276     // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1277     reference dereference() const { return *ptr; }
1278     void increment() { ++ptr; }
1279     void decrement() { --ptr; }
1280     void advance(ssize_t n) { ptr += n; }
1281     bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; }
1282     ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; }
1283 
1284 private:
1285     PyObject **ptr;
1286 };
1287 
1288 /// Full read and write access using the sequence protocol: see ``detail::sequence_accessor``
1289 class sequence_slow_readwrite {
1290 protected:
1291     using iterator_category = std::random_access_iterator_tag;
1292     using value_type = object;
1293     using reference = sequence_accessor;
1294     using pointer = arrow_proxy<const sequence_accessor>;
1295 
1296     sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) {}
1297     sequence_slow_readwrite() = default;
1298 
1299     reference dereference() const { return {obj, static_cast<size_t>(index)}; }
1300     void increment() { ++index; }
1301     void decrement() { --index; }
1302     void advance(ssize_t n) { index += n; }
1303     bool equal(const sequence_slow_readwrite &b) const { return index == b.index; }
1304     ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; }
1305 
1306 private:
1307     handle obj;
1308     ssize_t index;
1309 };
1310 
1311 /// Python's dictionary protocol permits this to be a forward iterator
1312 class dict_readonly {
1313 protected:
1314     using iterator_category = std::forward_iterator_tag;
1315     using value_type = std::pair<handle, handle>;
1316     using reference = const value_type; // PR #3263
1317     using pointer = arrow_proxy<const value_type>;
1318 
1319     dict_readonly() = default;
1320     dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }
1321 
1322     // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1323     reference dereference() const { return {key, value}; }
1324     void increment() {
1325         if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) {
1326             pos = -1;
1327         }
1328     }
1329     bool equal(const dict_readonly &b) const { return pos == b.pos; }
1330 
1331 private:
1332     handle obj;
1333     PyObject *key = nullptr, *value = nullptr;
1334     ssize_t pos = -1;
1335 };
1336 PYBIND11_NAMESPACE_END(iterator_policies)
1337 
1338 #if !defined(PYPY_VERSION)
1339 using tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
1340 using list_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
1341 #else
1342 using tuple_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
1343 using list_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
1344 #endif
1345 
1346 using sequence_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
1347 using dict_iterator = generic_iterator<iterator_policies::dict_readonly>;
1348 
1349 inline bool PyIterable_Check(PyObject *obj) {
1350     PyObject *iter = PyObject_GetIter(obj);
1351     if (iter) {
1352         Py_DECREF(iter);
1353         return true;
1354     }
1355     PyErr_Clear();
1356     return false;
1357 }
1358 
1359 inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
1360 inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }
1361 
1362 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
1363 inline bool PyUnicode_Check_Permissive(PyObject *o) {
1364     return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o);
1365 }
1366 #    define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive
1367 #else
1368 #    define PYBIND11_STR_CHECK_FUN PyUnicode_Check
1369 #endif
1370 
1371 inline bool PyStaticMethod_Check(PyObject *o) { return Py_TYPE(o) == &PyStaticMethod_Type; }
1372 
1373 class kwargs_proxy : public handle {
1374 public:
1375     explicit kwargs_proxy(handle h) : handle(h) {}
1376 };
1377 
1378 class args_proxy : public handle {
1379 public:
1380     explicit args_proxy(handle h) : handle(h) {}
1381     kwargs_proxy operator*() const { return kwargs_proxy(*this); }
1382 };
1383 
1384 /// Python argument categories (using PEP 448 terms)
1385 template <typename T>
1386 using is_keyword = std::is_base_of<arg, T>;
1387 template <typename T>
1388 using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking
1389 template <typename T>
1390 using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking
1391 template <typename T>
1392 using is_positional = satisfies_none_of<T, is_keyword, is_s_unpacking, is_ds_unpacking>;
1393 template <typename T>
1394 using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>;
1395 
1396 // Call argument collector forward declarations
1397 template <return_value_policy policy = return_value_policy::automatic_reference>
1398 class simple_collector;
1399 template <return_value_policy policy = return_value_policy::automatic_reference>
1400 class unpacking_collector;
1401 
1402 inline object get_scope_module(handle scope) {
1403     if (scope) {
1404         if (hasattr(scope, "__module__")) {
1405             return scope.attr("__module__");
1406         }
1407         if (hasattr(scope, "__name__")) {
1408             return scope.attr("__name__");
1409         }
1410     }
1411     return object();
1412 }
1413 
1414 PYBIND11_NAMESPACE_END(detail)
1415 
1416 // TODO: After the deprecated constructors are removed, this macro can be simplified by
1417 //       inheriting ctors: `using Parent::Parent`. It's not an option right now because
1418 //       the `using` statement triggers the parent deprecation warning even if the ctor
1419 //       isn't even used.
1420 #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun)                                            \
1421 public:                                                                                           \
1422     PYBIND11_DEPRECATED("Use reinterpret_borrow<" #Name ">() or reinterpret_steal<" #Name ">()")  \
1423     Name(handle h, bool is_borrowed)                                                              \
1424         : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {}                \
1425     Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {}                                       \
1426     Name(handle h, stolen_t) : Parent(h, stolen_t{}) {}                                           \
1427     PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead")                       \
1428     bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); }                     \
1429     static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); }              \
1430     template <typename Policy_> /* NOLINTNEXTLINE(google-explicit-constructor) */                 \
1431     Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) {}
1432 
1433 #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)                                   \
1434     PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun)                                                \
1435     /* This is deliberately not 'explicit' to allow implicit conversion from object: */           \
1436     /* NOLINTNEXTLINE(google-explicit-constructor) */                                             \
1437     Name(const object &o)                                                                         \
1438         : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) {               \
1439         if (!m_ptr)                                                                               \
1440             throw ::pybind11::error_already_set();                                                \
1441     }                                                                                             \
1442     /* NOLINTNEXTLINE(google-explicit-constructor) */                                             \
1443     Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) {  \
1444         if (!m_ptr)                                                                               \
1445             throw ::pybind11::error_already_set();                                                \
1446     }
1447 
1448 #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun)                           \
1449     PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)                                       \
1450     Name() = default;
1451 
1452 #define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr)                                                 \
1453     ::pybind11::type_error("Object of type '"                                                     \
1454                            + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr))      \
1455                            + "' is not an instance of '" #Name "'")
1456 
1457 #define PYBIND11_OBJECT(Name, Parent, CheckFun)                                                   \
1458     PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun)                                                \
1459     /* This is deliberately not 'explicit' to allow implicit conversion from object: */           \
1460     /* NOLINTNEXTLINE(google-explicit-constructor) */                                             \
1461     Name(const object &o) : Parent(o) {                                                           \
1462         if (m_ptr && !check_(m_ptr))                                                              \
1463             throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr);                                      \
1464     }                                                                                             \
1465     /* NOLINTNEXTLINE(google-explicit-constructor) */                                             \
1466     Name(object &&o) : Parent(std::move(o)) {                                                     \
1467         if (m_ptr && !check_(m_ptr))                                                              \
1468             throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr);                                      \
1469     }
1470 
1471 #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)                                           \
1472     PYBIND11_OBJECT(Name, Parent, CheckFun)                                                       \
1473     Name() = default;
1474 
1475 /// \addtogroup pytypes
1476 /// @{
1477 
1478 /** \rst
1479     Wraps a Python iterator so that it can also be used as a C++ input iterator
1480 
1481     Caveat: copying an iterator does not (and cannot) clone the internal
1482     state of the Python iterable. This also applies to the post-increment
1483     operator. This iterator should only be used to retrieve the current
1484     value using ``operator*()``.
1485 \endrst */
1486 class iterator : public object {
1487 public:
1488     using iterator_category = std::input_iterator_tag;
1489     using difference_type = ssize_t;
1490     using value_type = handle;
1491     using reference = const handle; // PR #3263
1492     using pointer = const handle *;
1493 
1494     PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)
1495 
1496     iterator &operator++() {
1497         init();
1498         advance();
1499         return *this;
1500     }
1501 
1502     iterator operator++(int) {
1503         // Note: We must call init() first so that rv.value is
1504         // the same as this->value just before calling advance().
1505         // Otherwise, dereferencing the returned iterator may call
1506         // advance() again and return the 3rd item instead of the 1st.
1507         init();
1508         auto rv = *this;
1509         advance();
1510         return rv;
1511     }
1512 
1513     // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1514     reference operator*() const {
1515         init();
1516         return value;
1517     }
1518 
1519     pointer operator->() const {
1520         init();
1521         return &value;
1522     }
1523 
1524     /** \rst
1525          The value which marks the end of the iteration. ``it == iterator::sentinel()``
1526          is equivalent to catching ``StopIteration`` in Python.
1527 
1528          .. code-block:: cpp
1529 
1530              void foo(py::iterator it) {
1531                  while (it != py::iterator::sentinel()) {
1532                     // use `*it`
1533                     ++it;
1534                  }
1535              }
1536     \endrst */
1537     static iterator sentinel() { return {}; }
1538 
1539     friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); }
1540     friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); }
1541 
1542 private:
1543     void init() const {
1544         if (m_ptr && !value.ptr()) {
1545             auto &self = const_cast<iterator &>(*this);
1546             self.advance();
1547         }
1548     }
1549 
1550     void advance() {
1551         value = reinterpret_steal<object>(PyIter_Next(m_ptr));
1552         if (value.ptr() == nullptr && PyErr_Occurred()) {
1553             throw error_already_set();
1554         }
1555     }
1556 
1557 private:
1558     object value = {};
1559 };
1560 
1561 class type : public object {
1562 public:
1563     PYBIND11_OBJECT(type, object, PyType_Check)
1564 
1565     /// Return a type handle from a handle or an object
1566     static handle handle_of(handle h) { return handle((PyObject *) Py_TYPE(h.ptr())); }
1567 
1568     /// Return a type object from a handle or an object
1569     static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); }
1570 
1571     // Defined in pybind11/cast.h
1572     /// Convert C++ type to handle if previously registered. Does not convert
1573     /// standard types, like int, float. etc. yet.
1574     /// See https://github.com/pybind/pybind11/issues/2486
1575     template <typename T>
1576     static handle handle_of();
1577 
1578     /// Convert C++ type to type if previously registered. Does not convert
1579     /// standard types, like int, float. etc. yet.
1580     /// See https://github.com/pybind/pybind11/issues/2486
1581     template <typename T>
1582     static type of() {
1583         return type(type::handle_of<T>(), borrowed_t{});
1584     }
1585 };
1586 
1587 class iterable : public object {
1588 public:
1589     PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check)
1590 };
1591 
1592 class bytes;
1593 
1594 class str : public object {
1595 public:
1596     PYBIND11_OBJECT_CVT(str, object, PYBIND11_STR_CHECK_FUN, raw_str)
1597 
1598     template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1599     str(const char *c, const SzType &n)
1600         : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1601         if (!m_ptr) {
1602             if (PyErr_Occurred()) {
1603                 throw error_already_set();
1604             }
1605             pybind11_fail("Could not allocate string object!");
1606         }
1607     }
1608 
1609     // 'explicit' is explicitly omitted from the following constructors to allow implicit
1610     // conversion to py::str from C++ string-like objects
1611     // NOLINTNEXTLINE(google-explicit-constructor)
1612     str(const char *c = "") : object(PyUnicode_FromString(c), stolen_t{}) {
1613         if (!m_ptr) {
1614             if (PyErr_Occurred()) {
1615                 throw error_already_set();
1616             }
1617             pybind11_fail("Could not allocate string object!");
1618         }
1619     }
1620 
1621     // NOLINTNEXTLINE(google-explicit-constructor)
1622     str(const std::string &s) : str(s.data(), s.size()) {}
1623 
1624 #ifdef PYBIND11_HAS_STRING_VIEW
1625     // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
1626     template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>
1627     // NOLINTNEXTLINE(google-explicit-constructor)
1628     str(T s) : str(s.data(), s.size()) {}
1629 
1630 #    ifdef PYBIND11_HAS_U8STRING
1631     // reinterpret_cast here is safe (C++20 guarantees char8_t has the same size/alignment as char)
1632     // NOLINTNEXTLINE(google-explicit-constructor)
1633     str(std::u8string_view s) : str(reinterpret_cast<const char *>(s.data()), s.size()) {}
1634 #    endif
1635 
1636 #endif
1637 
1638     explicit str(const bytes &b);
1639 
1640     /** \rst
1641         Return a string representation of the object. This is analogous to
1642         the ``str()`` function in Python.
1643     \endrst */
1644     explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) {
1645         if (!m_ptr) {
1646             throw error_already_set();
1647         }
1648     }
1649 
1650     // NOLINTNEXTLINE(google-explicit-constructor)
1651     operator std::string() const {
1652         object temp = *this;
1653         if (PyUnicode_Check(m_ptr)) {
1654             temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
1655             if (!temp) {
1656                 throw error_already_set();
1657             }
1658         }
1659         char *buffer = nullptr;
1660         ssize_t length = 0;
1661         if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {
1662             throw error_already_set();
1663         }
1664         return std::string(buffer, (size_t) length);
1665     }
1666 
1667     template <typename... Args>
1668     str format(Args &&...args) const {
1669         return attr("format")(std::forward<Args>(args)...);
1670     }
1671 
1672 private:
1673     /// Return string representation -- always returns a new reference, even if already a str
1674     static PyObject *raw_str(PyObject *op) {
1675         PyObject *str_value = PyObject_Str(op);
1676         return str_value;
1677     }
1678 };
1679 /// @} pytypes
1680 
1681 inline namespace literals {
1682 /** \rst
1683     String literal version of `str`
1684  \endrst */
1685 inline str
1686 #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
1687 operator"" _s // gcc 4.8.5 insists on having a space (hard error).
1688 #else
1689 operator""_s // clang 17 generates a deprecation warning if there is a space.
1690 #endif
1691     (const char *s, size_t size) {
1692     return {s, size};
1693 }
1694 } // namespace literals
1695 
1696 /// \addtogroup pytypes
1697 /// @{
1698 class bytes : public object {
1699 public:
1700     PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK)
1701 
1702     // Allow implicit conversion:
1703     // NOLINTNEXTLINE(google-explicit-constructor)
1704     bytes(const char *c = "") : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) {
1705         if (!m_ptr) {
1706             pybind11_fail("Could not allocate bytes object!");
1707         }
1708     }
1709 
1710     template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1711     bytes(const char *c, const SzType &n)
1712         : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, ssize_t_cast(n)), stolen_t{}) {
1713         if (!m_ptr) {
1714             pybind11_fail("Could not allocate bytes object!");
1715         }
1716     }
1717 
1718     // Allow implicit conversion:
1719     // NOLINTNEXTLINE(google-explicit-constructor)
1720     bytes(const std::string &s) : bytes(s.data(), s.size()) {}
1721 
1722     explicit bytes(const pybind11::str &s);
1723 
1724     // NOLINTNEXTLINE(google-explicit-constructor)
1725     operator std::string() const { return string_op<std::string>(); }
1726 
1727 #ifdef PYBIND11_HAS_STRING_VIEW
1728     // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
1729     template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>
1730     // NOLINTNEXTLINE(google-explicit-constructor)
1731     bytes(T s) : bytes(s.data(), s.size()) {}
1732 
1733     // Obtain a string view that views the current `bytes` buffer value.  Note that this is only
1734     // valid so long as the `bytes` instance remains alive and so generally should not outlive the
1735     // lifetime of the `bytes` instance.
1736     // NOLINTNEXTLINE(google-explicit-constructor)
1737     operator std::string_view() const { return string_op<std::string_view>(); }
1738 #endif
1739 private:
1740     template <typename T>
1741     T string_op() const {
1742         char *buffer = nullptr;
1743         ssize_t length = 0;
1744         if (PyBytes_AsStringAndSize(m_ptr, &buffer, &length) != 0) {
1745             throw error_already_set();
1746         }
1747         return {buffer, static_cast<size_t>(length)};
1748     }
1749 };
1750 // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1751 // are included in the doxygen group; close here and reopen after as a workaround
1752 /// @} pytypes
1753 
1754 inline bytes::bytes(const pybind11::str &s) {
1755     object temp = s;
1756     if (PyUnicode_Check(s.ptr())) {
1757         temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));
1758         if (!temp) {
1759             throw error_already_set();
1760         }
1761     }
1762     char *buffer = nullptr;
1763     ssize_t length = 0;
1764     if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {
1765         throw error_already_set();
1766     }
1767     auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));
1768     if (!obj) {
1769         pybind11_fail("Could not allocate bytes object!");
1770     }
1771     m_ptr = obj.release().ptr();
1772 }
1773 
1774 inline str::str(const bytes &b) {
1775     char *buffer = nullptr;
1776     ssize_t length = 0;
1777     if (PyBytes_AsStringAndSize(b.ptr(), &buffer, &length) != 0) {
1778         throw error_already_set();
1779     }
1780     auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, length));
1781     if (!obj) {
1782         if (PyErr_Occurred()) {
1783             throw error_already_set();
1784         }
1785         pybind11_fail("Could not allocate string object!");
1786     }
1787     m_ptr = obj.release().ptr();
1788 }
1789 
1790 /// \addtogroup pytypes
1791 /// @{
1792 class bytearray : public object {
1793 public:
1794     PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject)
1795 
1796     template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1797     bytearray(const char *c, const SzType &n)
1798         : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1799         if (!m_ptr) {
1800             pybind11_fail("Could not allocate bytearray object!");
1801         }
1802     }
1803 
1804     bytearray() : bytearray("", 0) {}
1805 
1806     explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) {}
1807 
1808     size_t size() const { return static_cast<size_t>(PyByteArray_Size(m_ptr)); }
1809 
1810     explicit operator std::string() const {
1811         char *buffer = PyByteArray_AS_STRING(m_ptr);
1812         ssize_t size = PyByteArray_GET_SIZE(m_ptr);
1813         return std::string(buffer, static_cast<size_t>(size));
1814     }
1815 };
1816 // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1817 // are included in the doxygen group; close here and reopen after as a workaround
1818 /// @} pytypes
1819 
1820 /// \addtogroup pytypes
1821 /// @{
1822 class none : public object {
1823 public:
1824     PYBIND11_OBJECT(none, object, detail::PyNone_Check)
1825     none() : object(Py_None, borrowed_t{}) {}
1826 };
1827 
1828 class ellipsis : public object {
1829 public:
1830     PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check)
1831     ellipsis() : object(Py_Ellipsis, borrowed_t{}) {}
1832 };
1833 
1834 class bool_ : public object {
1835 public:
1836     PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool)
1837     bool_() : object(Py_False, borrowed_t{}) {}
1838     // Allow implicit conversion from and to `bool`:
1839     // NOLINTNEXTLINE(google-explicit-constructor)
1840     bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) {}
1841     // NOLINTNEXTLINE(google-explicit-constructor)
1842     operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; }
1843 
1844 private:
1845     /// Return the truth value of an object -- always returns a new reference
1846     static PyObject *raw_bool(PyObject *op) {
1847         const auto value = PyObject_IsTrue(op);
1848         if (value == -1) {
1849             return nullptr;
1850         }
1851         return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr();
1852     }
1853 };
1854 
1855 PYBIND11_NAMESPACE_BEGIN(detail)
1856 // Converts a value to the given unsigned type.  If an error occurs, you get back (Unsigned) -1;
1857 // otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned).
1858 // (The distinction is critically important when casting a returned -1 error value to some other
1859 // unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes).
1860 template <typename Unsigned>
1861 Unsigned as_unsigned(PyObject *o) {
1862     if (sizeof(Unsigned) <= sizeof(unsigned long)) {
1863         unsigned long v = PyLong_AsUnsignedLong(o);
1864         return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1865     }
1866     unsigned long long v = PyLong_AsUnsignedLongLong(o);
1867     return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1868 }
1869 PYBIND11_NAMESPACE_END(detail)
1870 
1871 class int_ : public object {
1872 public:
1873     PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long)
1874     int_() : object(PyLong_FromLong(0), stolen_t{}) {}
1875     // Allow implicit conversion from C++ integral types:
1876     template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1877     // NOLINTNEXTLINE(google-explicit-constructor)
1878     int_(T value) {
1879         if (sizeof(T) <= sizeof(long)) {
1880             if (std::is_signed<T>::value) {
1881                 m_ptr = PyLong_FromLong((long) value);
1882             } else {
1883                 m_ptr = PyLong_FromUnsignedLong((unsigned long) value);
1884             }
1885         } else {
1886             if (std::is_signed<T>::value) {
1887                 m_ptr = PyLong_FromLongLong((long long) value);
1888             } else {
1889                 m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value);
1890             }
1891         }
1892         if (!m_ptr) {
1893             pybind11_fail("Could not allocate int object!");
1894         }
1895     }
1896 
1897     template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1898     // NOLINTNEXTLINE(google-explicit-constructor)
1899     operator T() const {
1900         return std::is_unsigned<T>::value  ? detail::as_unsigned<T>(m_ptr)
1901                : sizeof(T) <= sizeof(long) ? (T) PyLong_AsLong(m_ptr)
1902                                            : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
1903     }
1904 };
1905 
1906 class float_ : public object {
1907 public:
1908     PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)
1909     // Allow implicit conversion from float/double:
1910     // NOLINTNEXTLINE(google-explicit-constructor)
1911     float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1912         if (!m_ptr) {
1913             pybind11_fail("Could not allocate float object!");
1914         }
1915     }
1916     // NOLINTNEXTLINE(google-explicit-constructor)
1917     float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1918         if (!m_ptr) {
1919             pybind11_fail("Could not allocate float object!");
1920         }
1921     }
1922     // NOLINTNEXTLINE(google-explicit-constructor)
1923     operator float() const { return (float) PyFloat_AsDouble(m_ptr); }
1924     // NOLINTNEXTLINE(google-explicit-constructor)
1925     operator double() const { return (double) PyFloat_AsDouble(m_ptr); }
1926 };
1927 
1928 class weakref : public object {
1929 public:
1930     PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref)
1931     explicit weakref(handle obj, handle callback = {})
1932         : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) {
1933         if (!m_ptr) {
1934             if (PyErr_Occurred()) {
1935                 throw error_already_set();
1936             }
1937             pybind11_fail("Could not allocate weak reference!");
1938         }
1939     }
1940 
1941 private:
1942     static PyObject *raw_weakref(PyObject *o) { return PyWeakref_NewRef(o, nullptr); }
1943 };
1944 
1945 class slice : public object {
1946 public:
1947     PYBIND11_OBJECT(slice, object, PySlice_Check)
1948     slice(handle start, handle stop, handle step)
1949         : object(PySlice_New(start.ptr(), stop.ptr(), step.ptr()), stolen_t{}) {
1950         if (!m_ptr) {
1951             pybind11_fail("Could not allocate slice object!");
1952         }
1953     }
1954     slice() : slice(none(), none(), none()) {}
1955 
1956 #ifdef PYBIND11_HAS_OPTIONAL
1957     slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t> step)
1958         : slice(index_to_object(start), index_to_object(stop), index_to_object(step)) {}
1959 #else
1960     slice(ssize_t start_, ssize_t stop_, ssize_t step_)
1961         : slice(int_(start_), int_(stop_), int_(step_)) {}
1962 #endif
1963 
1964     bool
1965     compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const {
1966         return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1967                                     (ssize_t) length,
1968                                     (ssize_t *) start,
1969                                     (ssize_t *) stop,
1970                                     (ssize_t *) step,
1971                                     (ssize_t *) slicelength)
1972                == 0;
1973     }
1974     bool compute(
1975         ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const {
1976         return PySlice_GetIndicesEx(
1977                    (PYBIND11_SLICE_OBJECT *) m_ptr, length, start, stop, step, slicelength)
1978                == 0;
1979     }
1980 
1981 private:
1982     template <typename T>
1983     static object index_to_object(T index) {
1984         return index ? object(int_(*index)) : object(none());
1985     }
1986 };
1987 
1988 class capsule : public object {
1989 public:
1990     PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact)
1991     PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()")
1992     capsule(PyObject *ptr, bool is_borrowed)
1993         : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) {}
1994 
1995     explicit capsule(const void *value,
1996                      const char *name = nullptr,
1997                      PyCapsule_Destructor destructor = nullptr)
1998         : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) {
1999         if (!m_ptr) {
2000             throw error_already_set();
2001         }
2002     }
2003 
2004     PYBIND11_DEPRECATED("Please use the ctor with value, name, destructor args")
2005     capsule(const void *value, PyCapsule_Destructor destructor)
2006         : object(PyCapsule_New(const_cast<void *>(value), nullptr, destructor), stolen_t{}) {
2007         if (!m_ptr) {
2008             throw error_already_set();
2009         }
2010     }
2011 
2012     /// Capsule name is nullptr.
2013     capsule(const void *value, void (*destructor)(void *)) {
2014         initialize_with_void_ptr_destructor(value, nullptr, destructor);
2015     }
2016 
2017     capsule(const void *value, const char *name, void (*destructor)(void *)) {
2018         initialize_with_void_ptr_destructor(value, name, destructor);
2019     }
2020 
2021     explicit capsule(void (*destructor)()) {
2022         m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) {
2023             const char *name = get_name_in_error_scope(o);
2024             auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, name));
2025             if (destructor == nullptr) {
2026                 throw error_already_set();
2027             }
2028             destructor();
2029         });
2030 
2031         if (!m_ptr) {
2032             throw error_already_set();
2033         }
2034     }
2035 
2036     template <typename T>
2037     operator T *() const { // NOLINT(google-explicit-constructor)
2038         return get_pointer<T>();
2039     }
2040 
2041     /// Get the pointer the capsule holds.
2042     template <typename T = void>
2043     T *get_pointer() const {
2044         const auto *name = this->name();
2045         T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));
2046         if (!result) {
2047             throw error_already_set();
2048         }
2049         return result;
2050     }
2051 
2052     /// Replaces a capsule's pointer *without* calling the destructor on the existing one.
2053     void set_pointer(const void *value) {
2054         if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0) {
2055             throw error_already_set();
2056         }
2057     }
2058 
2059     const char *name() const {
2060         const char *name = PyCapsule_GetName(m_ptr);
2061         if ((name == nullptr) && PyErr_Occurred()) {
2062             throw error_already_set();
2063         }
2064         return name;
2065     }
2066 
2067     /// Replaces a capsule's name *without* calling the destructor on the existing one.
2068     void set_name(const char *new_name) {
2069         if (PyCapsule_SetName(m_ptr, new_name) != 0) {
2070             throw error_already_set();
2071         }
2072     }
2073 
2074 private:
2075     static const char *get_name_in_error_scope(PyObject *o) {
2076         error_scope error_guard;
2077 
2078         const char *name = PyCapsule_GetName(o);
2079         if ((name == nullptr) && PyErr_Occurred()) {
2080             // write out and consume error raised by call to PyCapsule_GetName
2081             PyErr_WriteUnraisable(o);
2082         }
2083 
2084         return name;
2085     }
2086 
2087     void initialize_with_void_ptr_destructor(const void *value,
2088                                              const char *name,
2089                                              void (*destructor)(void *)) {
2090         m_ptr = PyCapsule_New(const_cast<void *>(value), name, [](PyObject *o) {
2091             // guard if destructor called while err indicator is set
2092             error_scope error_guard;
2093             auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o));
2094             if (destructor == nullptr && PyErr_Occurred()) {
2095                 throw error_already_set();
2096             }
2097             const char *name = get_name_in_error_scope(o);
2098             void *ptr = PyCapsule_GetPointer(o, name);
2099             if (ptr == nullptr) {
2100                 throw error_already_set();
2101             }
2102 
2103             if (destructor != nullptr) {
2104                 destructor(ptr);
2105             }
2106         });
2107 
2108         if (!m_ptr || PyCapsule_SetContext(m_ptr, reinterpret_cast<void *>(destructor)) != 0) {
2109             throw error_already_set();
2110         }
2111     }
2112 };
2113 
2114 class tuple : public object {
2115 public:
2116     PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple)
2117     template <typename SzType = ssize_t,
2118               detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
2119     // Some compilers generate link errors when using `const SzType &` here:
2120     explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) {
2121         if (!m_ptr) {
2122             pybind11_fail("Could not allocate tuple object!");
2123         }
2124     }
2125     size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
2126     bool empty() const { return size() == 0; }
2127     detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }
2128     template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
2129     detail::item_accessor operator[](T &&o) const {
2130         return object::operator[](std::forward<T>(o));
2131     }
2132     detail::tuple_iterator begin() const { return {*this, 0}; }
2133     detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }
2134 };
2135 
2136 // We need to put this into a separate function because the Intel compiler
2137 // fails to compile enable_if_t<all_of<is_keyword_or_ds<Args>...>::value> part below
2138 // (tested with ICC 2021.1 Beta 20200827).
2139 template <typename... Args>
2140 constexpr bool args_are_all_keyword_or_ds() {
2141     return detail::all_of<detail::is_keyword_or_ds<Args>...>::value;
2142 }
2143 
2144 class dict : public object {
2145 public:
2146     PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)
2147     dict() : object(PyDict_New(), stolen_t{}) {
2148         if (!m_ptr) {
2149             pybind11_fail("Could not allocate dict object!");
2150         }
2151     }
2152     template <typename... Args,
2153               typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>,
2154               // MSVC workaround: it can't compile an out-of-line definition, so defer the
2155               // collector
2156               typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
2157     explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) {}
2158 
2159     size_t size() const { return (size_t) PyDict_Size(m_ptr); }
2160     bool empty() const { return size() == 0; }
2161     detail::dict_iterator begin() const { return {*this, 0}; }
2162     detail::dict_iterator end() const { return {}; }
2163     void clear() /* py-non-const */ { PyDict_Clear(ptr()); }
2164     template <typename T>
2165     bool contains(T &&key) const {
2166         auto result = PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr());
2167         if (result == -1) {
2168             throw error_already_set();
2169         }
2170         return result == 1;
2171     }
2172 
2173 private:
2174     /// Call the `dict` Python type -- always returns a new reference
2175     static PyObject *raw_dict(PyObject *op) {
2176         if (PyDict_Check(op)) {
2177             return handle(op).inc_ref().ptr();
2178         }
2179         return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
2180     }
2181 };
2182 
2183 class sequence : public object {
2184 public:
2185     PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)
2186     size_t size() const {
2187         ssize_t result = PySequence_Size(m_ptr);
2188         if (result == -1) {
2189             throw error_already_set();
2190         }
2191         return (size_t) result;
2192     }
2193     bool empty() const { return size() == 0; }
2194     detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
2195     template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
2196     detail::item_accessor operator[](T &&o) const {
2197         return object::operator[](std::forward<T>(o));
2198     }
2199     detail::sequence_iterator begin() const { return {*this, 0}; }
2200     detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; }
2201 };
2202 
2203 class list : public object {
2204 public:
2205     PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
2206     template <typename SzType = ssize_t,
2207               detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
2208     // Some compilers generate link errors when using `const SzType &` here:
2209     explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) {
2210         if (!m_ptr) {
2211             pybind11_fail("Could not allocate list object!");
2212         }
2213     }
2214     size_t size() const { return (size_t) PyList_Size(m_ptr); }
2215     bool empty() const { return size() == 0; }
2216     detail::list_accessor operator[](size_t index) const { return {*this, index}; }
2217     template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
2218     detail::item_accessor operator[](T &&o) const {
2219         return object::operator[](std::forward<T>(o));
2220     }
2221     detail::list_iterator begin() const { return {*this, 0}; }
2222     detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
2223     template <typename T>
2224     void append(T &&val) /* py-non-const */ {
2225         if (PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) != 0) {
2226             throw error_already_set();
2227         }
2228     }
2229     template <typename IdxType,
2230               typename ValType,
2231               detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
2232     void insert(const IdxType &index, ValType &&val) /* py-non-const */ {
2233         if (PyList_Insert(m_ptr,
2234                           ssize_t_cast(index),
2235                           detail::object_or_cast(std::forward<ValType>(val)).ptr())
2236             != 0) {
2237             throw error_already_set();
2238         }
2239     }
2240     void clear() /* py-non-const */ {
2241         if (PyList_SetSlice(m_ptr, 0, PyList_Size(m_ptr), nullptr) == -1) {
2242             throw error_already_set();
2243         }
2244     }
2245 };
2246 
2247 class args : public tuple {
2248     PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check)
2249 };
2250 class kwargs : public dict {
2251     PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check)
2252 };
2253 
2254 // Subclasses of args and kwargs to support type hinting
2255 // as defined in PEP 484. See #5357 for more info.
2256 template <typename T>
2257 class Args : public args {
2258     using args::args;
2259 };
2260 
2261 template <typename T>
2262 class KWArgs : public kwargs {
2263     using kwargs::kwargs;
2264 };
2265 
2266 class anyset : public object {
2267 public:
2268     PYBIND11_OBJECT(anyset, object, PyAnySet_Check)
2269     size_t size() const { return static_cast<size_t>(PySet_Size(m_ptr)); }
2270     bool empty() const { return size() == 0; }
2271     template <typename T>
2272     bool contains(T &&val) const {
2273         auto result = PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
2274         if (result == -1) {
2275             throw error_already_set();
2276         }
2277         return result == 1;
2278     }
2279 };
2280 
2281 class set : public anyset {
2282 public:
2283     PYBIND11_OBJECT_CVT(set, anyset, PySet_Check, PySet_New)
2284     set() : anyset(PySet_New(nullptr), stolen_t{}) {
2285         if (!m_ptr) {
2286             pybind11_fail("Could not allocate set object!");
2287         }
2288     }
2289     template <typename T>
2290     bool add(T &&val) /* py-non-const */ {
2291         return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
2292     }
2293     void clear() /* py-non-const */ { PySet_Clear(m_ptr); }
2294 };
2295 
2296 class frozenset : public anyset {
2297 public:
2298     PYBIND11_OBJECT_CVT(frozenset, anyset, PyFrozenSet_Check, PyFrozenSet_New)
2299 };
2300 
2301 class function : public object {
2302 public:
2303     PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)
2304     handle cpp_function() const {
2305         handle fun = detail::get_function(m_ptr);
2306         if (fun && PyCFunction_Check(fun.ptr())) {
2307             return fun;
2308         }
2309         return handle();
2310     }
2311     bool is_cpp_function() const { return (bool) cpp_function(); }
2312 };
2313 
2314 class staticmethod : public object {
2315 public:
2316     PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)
2317 };
2318 
2319 class buffer : public object {
2320 public:
2321     PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)
2322 
2323     buffer_info request(bool writable = false) const {
2324         int flags = PyBUF_STRIDES | PyBUF_FORMAT;
2325         if (writable) {
2326             flags |= PyBUF_WRITABLE;
2327         }
2328         auto *view = new Py_buffer();
2329         if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
2330             delete view;
2331             throw error_already_set();
2332         }
2333         return buffer_info(view);
2334     }
2335 };
2336 
2337 class memoryview : public object {
2338 public:
2339     PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
2340 
2341     /** \rst
2342         Creates ``memoryview`` from ``buffer_info``.
2343 
2344         ``buffer_info`` must be created from ``buffer::request()``. Otherwise
2345         throws an exception.
2346 
2347         For creating a ``memoryview`` from objects that support buffer protocol,
2348         use ``memoryview(const object& obj)`` instead of this constructor.
2349      \endrst */
2350     explicit memoryview(const buffer_info &info) {
2351         if (!info.view()) {
2352             pybind11_fail("Prohibited to create memoryview without Py_buffer");
2353         }
2354         // Note: PyMemoryView_FromBuffer never increments obj reference.
2355         m_ptr = (info.view()->obj) ? PyMemoryView_FromObject(info.view()->obj)
2356                                    : PyMemoryView_FromBuffer(info.view());
2357         if (!m_ptr) {
2358             pybind11_fail("Unable to create memoryview from buffer descriptor");
2359         }
2360     }
2361 
2362     /** \rst
2363         Creates ``memoryview`` from static buffer.
2364 
2365         This method is meant for providing a ``memoryview`` for C/C++ buffer not
2366         managed by Python. The caller is responsible for managing the lifetime
2367         of ``ptr`` and ``format``, which MUST outlive the memoryview constructed
2368         here.
2369 
2370         See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
2371 
2372         .. _PyMemoryView_FromBuffer:
2373            https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer
2374 
2375         :param ptr: Pointer to the buffer.
2376         :param itemsize: Byte size of an element.
2377         :param format: Pointer to the null-terminated format string. For
2378             homogeneous Buffers, this should be set to
2379             ``format_descriptor<T>::value``.
2380         :param shape: Shape of the tensor (1 entry per dimension).
2381         :param strides: Number of bytes between adjacent entries (for each
2382             per dimension).
2383         :param readonly: Flag to indicate if the underlying storage may be
2384             written to.
2385      \endrst */
2386     static memoryview from_buffer(void *ptr,
2387                                   ssize_t itemsize,
2388                                   const char *format,
2389                                   detail::any_container<ssize_t> shape,
2390                                   detail::any_container<ssize_t> strides,
2391                                   bool readonly = false);
2392 
2393     static memoryview from_buffer(const void *ptr,
2394                                   ssize_t itemsize,
2395                                   const char *format,
2396                                   detail::any_container<ssize_t> shape,
2397                                   detail::any_container<ssize_t> strides) {
2398         return memoryview::from_buffer(
2399             const_cast<void *>(ptr), itemsize, format, std::move(shape), std::move(strides), true);
2400     }
2401 
2402     template <typename T>
2403     static memoryview from_buffer(T *ptr,
2404                                   detail::any_container<ssize_t> shape,
2405                                   detail::any_container<ssize_t> strides,
2406                                   bool readonly = false) {
2407         return memoryview::from_buffer(reinterpret_cast<void *>(ptr),
2408                                        sizeof(T),
2409                                        format_descriptor<T>::value,
2410                                        std::move(shape),
2411                                        std::move(strides),
2412                                        readonly);
2413     }
2414 
2415     template <typename T>
2416     static memoryview from_buffer(const T *ptr,
2417                                   detail::any_container<ssize_t> shape,
2418                                   detail::any_container<ssize_t> strides) {
2419         return memoryview::from_buffer(
2420             const_cast<T *>(ptr), std::move(shape), std::move(strides), true);
2421     }
2422 
2423     /** \rst
2424         Creates ``memoryview`` from static memory.
2425 
2426         This method is meant for providing a ``memoryview`` for C/C++ buffer not
2427         managed by Python. The caller is responsible for managing the lifetime
2428         of ``mem``, which MUST outlive the memoryview constructed here.
2429 
2430         See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
2431 
2432         .. _PyMemoryView_FromMemory:
2433            https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory
2434      \endrst */
2435     static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) {
2436         PyObject *ptr = PyMemoryView_FromMemory(
2437             reinterpret_cast<char *>(mem), size, (readonly) ? PyBUF_READ : PyBUF_WRITE);
2438         if (!ptr) {
2439             pybind11_fail("Could not allocate memoryview object!");
2440         }
2441         return memoryview(object(ptr, stolen_t{}));
2442     }
2443 
2444     static memoryview from_memory(const void *mem, ssize_t size) {
2445         return memoryview::from_memory(const_cast<void *>(mem), size, true);
2446     }
2447 
2448 #ifdef PYBIND11_HAS_STRING_VIEW
2449     static memoryview from_memory(std::string_view mem) {
2450         return from_memory(const_cast<char *>(mem.data()), static_cast<ssize_t>(mem.size()), true);
2451     }
2452 #endif
2453 };
2454 
2455 /// @cond DUPLICATE
2456 inline memoryview memoryview::from_buffer(void *ptr,
2457                                           ssize_t itemsize,
2458                                           const char *format,
2459                                           detail::any_container<ssize_t> shape,
2460                                           detail::any_container<ssize_t> strides,
2461                                           bool readonly) {
2462     size_t ndim = shape->size();
2463     if (ndim != strides->size()) {
2464         pybind11_fail("memoryview: shape length doesn't match strides length");
2465     }
2466     ssize_t size = ndim != 0u ? 1 : 0;
2467     for (size_t i = 0; i < ndim; ++i) {
2468         size *= (*shape)[i];
2469     }
2470     Py_buffer view;
2471     view.buf = ptr;
2472     view.obj = nullptr;
2473     view.len = size * itemsize;
2474     view.readonly = static_cast<int>(readonly);
2475     view.itemsize = itemsize;
2476     view.format = const_cast<char *>(format);
2477     view.ndim = static_cast<int>(ndim);
2478     view.shape = shape->data();
2479     view.strides = strides->data();
2480     view.suboffsets = nullptr;
2481     view.internal = nullptr;
2482     PyObject *obj = PyMemoryView_FromBuffer(&view);
2483     if (!obj) {
2484         throw error_already_set();
2485     }
2486     return memoryview(object(obj, stolen_t{}));
2487 }
2488 /// @endcond
2489 /// @} pytypes
2490 
2491 /// \addtogroup python_builtins
2492 /// @{
2493 
2494 /// Get the length of a Python object.
2495 inline size_t len(handle h) {
2496     ssize_t result = PyObject_Length(h.ptr());
2497     if (result < 0) {
2498         throw error_already_set();
2499     }
2500     return (size_t) result;
2501 }
2502 
2503 /// Get the length hint of a Python object.
2504 /// Returns 0 when this cannot be determined.
2505 inline size_t len_hint(handle h) {
2506     ssize_t result = PyObject_LengthHint(h.ptr(), 0);
2507     if (result < 0) {
2508         // Sometimes a length can't be determined at all (eg generators)
2509         // In which case simply return 0
2510         PyErr_Clear();
2511         return 0;
2512     }
2513     return (size_t) result;
2514 }
2515 
2516 inline str repr(handle h) {
2517     PyObject *str_value = PyObject_Repr(h.ptr());
2518     if (!str_value) {
2519         throw error_already_set();
2520     }
2521     return reinterpret_steal<str>(str_value);
2522 }
2523 
2524 inline iterator iter(handle obj) {
2525     PyObject *result = PyObject_GetIter(obj.ptr());
2526     if (!result) {
2527         throw error_already_set();
2528     }
2529     return reinterpret_steal<iterator>(result);
2530 }
2531 /// @} python_builtins
2532 
2533 PYBIND11_NAMESPACE_BEGIN(detail)
2534 template <typename D>
2535 iterator object_api<D>::begin() const {
2536     return iter(derived());
2537 }
2538 template <typename D>
2539 iterator object_api<D>::end() const {
2540     return iterator::sentinel();
2541 }
2542 template <typename D>
2543 item_accessor object_api<D>::operator[](handle key) const {
2544     return {derived(), reinterpret_borrow<object>(key)};
2545 }
2546 template <typename D>
2547 item_accessor object_api<D>::operator[](object &&key) const {
2548     return {derived(), std::move(key)};
2549 }
2550 template <typename D>
2551 item_accessor object_api<D>::operator[](const char *key) const {
2552     return {derived(), pybind11::str(key)};
2553 }
2554 template <typename D>
2555 obj_attr_accessor object_api<D>::attr(handle key) const {
2556     return {derived(), reinterpret_borrow<object>(key)};
2557 }
2558 template <typename D>
2559 obj_attr_accessor object_api<D>::attr(object &&key) const {
2560     return {derived(), std::move(key)};
2561 }
2562 template <typename D>
2563 str_attr_accessor object_api<D>::attr(const char *key) const {
2564     return {derived(), key};
2565 }
2566 template <typename D>
2567 args_proxy object_api<D>::operator*() const {
2568     return args_proxy(derived().ptr());
2569 }
2570 template <typename D>
2571 template <typename T>
2572 bool object_api<D>::contains(T &&item) const {
2573     return attr("__contains__")(std::forward<T>(item)).template cast<bool>();
2574 }
2575 
2576 template <typename D>
2577 pybind11::str object_api<D>::str() const {
2578     return pybind11::str(derived());
2579 }
2580 
2581 template <typename D>
2582 str_attr_accessor object_api<D>::doc() const {
2583     return attr("__doc__");
2584 }
2585 
2586 template <typename D>
2587 object object_api<D>::annotations() const {
2588 // This is needed again because of the lazy annotations added in 3.14+
2589 #if PY_VERSION_HEX < 0x030A0000 || PY_VERSION_HEX >= 0x030E0000
2590     // https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older
2591     if (!hasattr(derived(), "__annotations__")) {
2592         setattr(derived(), "__annotations__", dict());
2593     }
2594     return attr("__annotations__");
2595 #else
2596     return getattr(derived(), "__annotations__", dict());
2597 #endif
2598 }
2599 
2600 template <typename D>
2601 handle object_api<D>::get_type() const {
2602     return type::handle_of(derived());
2603 }
2604 
2605 template <typename D>
2606 bool object_api<D>::rich_compare(object_api const &other, int value) const {
2607     int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
2608     if (rv == -1) {
2609         throw error_already_set();
2610     }
2611     return rv == 1;
2612 }
2613 
2614 #define PYBIND11_MATH_OPERATOR_UNARY(op, fn)                                                      \
2615     template <typename D>                                                                         \
2616     object object_api<D>::op() const {                                                            \
2617         object result = reinterpret_steal<object>(fn(derived().ptr()));                           \
2618         if (!result.ptr())                                                                        \
2619             throw error_already_set();                                                            \
2620         return result;                                                                            \
2621     }
2622 
2623 #define PYBIND11_MATH_OPERATOR_BINARY(op, fn)                                                     \
2624     template <typename D>                                                                         \
2625     object object_api<D>::op(object_api const &other) const {                                     \
2626         object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr()));    \
2627         if (!result.ptr())                                                                        \
2628             throw error_already_set();                                                            \
2629         return result;                                                                            \
2630     }
2631 
2632 #define PYBIND11_MATH_OPERATOR_BINARY_INPLACE(iop, fn)                                            \
2633     template <typename D>                                                                         \
2634     object object_api<D>::iop(object_api const &other) {                                          \
2635         object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr()));    \
2636         if (!result.ptr())                                                                        \
2637             throw error_already_set();                                                            \
2638         return result;                                                                            \
2639     }
2640 
2641 PYBIND11_MATH_OPERATOR_UNARY(operator~, PyNumber_Invert)
2642 PYBIND11_MATH_OPERATOR_UNARY(operator-, PyNumber_Negative)
2643 PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)
2644 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator+=, PyNumber_InPlaceAdd)
2645 PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)
2646 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator-=, PyNumber_InPlaceSubtract)
2647 PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)
2648 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator*=, PyNumber_InPlaceMultiply)
2649 PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)
2650 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator/=, PyNumber_InPlaceTrueDivide)
2651 PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)
2652 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator|=, PyNumber_InPlaceOr)
2653 PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)
2654 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator&=, PyNumber_InPlaceAnd)
2655 PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)
2656 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator^=, PyNumber_InPlaceXor)
2657 PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)
2658 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator<<=, PyNumber_InPlaceLshift)
2659 PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)
2660 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator>>=, PyNumber_InPlaceRshift)
2661 
2662 #undef PYBIND11_MATH_OPERATOR_UNARY
2663 #undef PYBIND11_MATH_OPERATOR_BINARY
2664 #undef PYBIND11_MATH_OPERATOR_BINARY_INPLACE
2665 
2666 // Meant to return a Python str, but this is not checked.
2667 inline object get_module_name_if_available(handle scope) {
2668     if (scope) {
2669         if (hasattr(scope, "__module__")) {
2670             return scope.attr("__module__");
2671         }
2672         if (hasattr(scope, "__name__")) {
2673             return scope.attr("__name__");
2674         }
2675     }
2676     return object();
2677 }
2678 
2679 PYBIND11_NAMESPACE_END(detail)
2680 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)