Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-12 10:55:21

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