Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 10:06:17

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