Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-08-14 09:22:48

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