Blame external/pybind11/include/pybind11/pytypes.h

Packit 534379
/*
Packit 534379
    pybind11/pytypes.h: Convenience wrapper classes for basic Python types
Packit 534379
Packit 534379
    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Packit 534379
Packit 534379
    All rights reserved. Use of this source code is governed by a
Packit 534379
    BSD-style license that can be found in the LICENSE file.
Packit 534379
*/
Packit 534379
Packit 534379
#pragma once
Packit 534379
Packit 534379
#include "detail/common.h"
Packit 534379
#include "buffer_info.h"
Packit 534379
#include <utility>
Packit 534379
#include <type_traits>
Packit 534379
Packit 534379
NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
Packit 534379
Packit 534379
/* A few forward declarations */
Packit 534379
class handle; class object;
Packit 534379
class str; class iterator;
Packit 534379
struct arg; struct arg_v;
Packit 534379
Packit 534379
NAMESPACE_BEGIN(detail)
Packit 534379
class args_proxy;
Packit 534379
inline bool isinstance_generic(handle obj, const std::type_info &tp);
Packit 534379
Packit 534379
// Accessor forward declarations
Packit 534379
template <typename Policy> class accessor;
Packit 534379
namespace accessor_policies {
Packit 534379
    struct obj_attr;
Packit 534379
    struct str_attr;
Packit 534379
    struct generic_item;
Packit 534379
    struct sequence_item;
Packit 534379
    struct list_item;
Packit 534379
    struct tuple_item;
Packit 534379
}
Packit 534379
using obj_attr_accessor = accessor<accessor_policies::obj_attr>;
Packit 534379
using str_attr_accessor = accessor<accessor_policies::str_attr>;
Packit 534379
using item_accessor = accessor<accessor_policies::generic_item>;
Packit 534379
using sequence_accessor = accessor<accessor_policies::sequence_item>;
Packit 534379
using list_accessor = accessor<accessor_policies::list_item>;
Packit 534379
using tuple_accessor = accessor<accessor_policies::tuple_item>;
Packit 534379
Packit 534379
/// Tag and check to identify a class which implements the Python object API
Packit 534379
class pyobject_tag { };
Packit 534379
template <typename T> using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
Packit 534379
Packit 534379
/** \rst
Packit 534379
    A mixin class which adds common functions to `handle`, `object` and various accessors.
Packit 534379
    The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``.
Packit 534379
\endrst */
Packit 534379
template <typename Derived>
Packit 534379
class object_api : public pyobject_tag {
Packit 534379
    const Derived &derived() const { return static_cast<const Derived &>(*this); }
Packit 534379
Packit 534379
public:
Packit 534379
    /** \rst
Packit 534379
        Return an iterator equivalent to calling ``iter()`` in Python. The object
Packit 534379
        must be a collection which supports the iteration protocol.
Packit 534379
    \endrst */
Packit 534379
    iterator begin() const;
Packit 534379
    /// Return a sentinel which ends iteration.
Packit 534379
    iterator end() const;
Packit 534379
Packit 534379
    /** \rst
Packit 534379
        Return an internal functor to invoke the object's sequence protocol. Casting
Packit 534379
        the returned ``detail::item_accessor`` instance to a `handle` or `object`
Packit 534379
        subclass causes a corresponding call to ``__getitem__``. Assigning a `handle`
Packit 534379
        or `object` subclass causes a call to ``__setitem__``.
Packit 534379
    \endrst */
Packit 534379
    item_accessor operator[](handle key) const;
Packit 534379
    /// See above (the only difference is that they key is provided as a string literal)
Packit 534379
    item_accessor operator[](const char *key) const;
Packit 534379
Packit 534379
    /** \rst
Packit 534379
        Return an internal functor to access the object's attributes. Casting the
Packit 534379
        returned ``detail::obj_attr_accessor`` instance to a `handle` or `object`
Packit 534379
        subclass causes a corresponding call to ``getattr``. Assigning a `handle`
Packit 534379
        or `object` subclass causes a call to ``setattr``.
Packit 534379
    \endrst */
Packit 534379
    obj_attr_accessor attr(handle key) const;
Packit 534379
    /// See above (the only difference is that they key is provided as a string literal)
Packit 534379
    str_attr_accessor attr(const char *key) const;
Packit 534379
Packit 534379
    /** \rst
Packit 534379
        Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple``
Packit 534379
        or ``list`` for a function call. Applying another * to the result yields
Packit 534379
        ** unpacking, e.g. to unpack a dict as function keyword arguments.
Packit 534379
        See :ref:`calling_python_functions`.
Packit 534379
    \endrst */
Packit 534379
    args_proxy operator*() const;
Packit 534379
Packit 534379
    /// Check if the given item is contained within this object, i.e. ``item in obj``.
Packit 534379
    template <typename T> bool contains(T &&item) const;
Packit 534379
Packit 534379
    /** \rst
Packit 534379
        Assuming the Python object is a function or implements the ``__call__``
Packit 534379
        protocol, ``operator()`` invokes the underlying function, passing an
Packit 534379
        arbitrary set of parameters. The result is returned as a `object` and
Packit 534379
        may need to be converted back into a Python object using `handle::cast()`.
Packit 534379
Packit 534379
        When some of the arguments cannot be converted to Python objects, the
Packit 534379
        function will throw a `cast_error` exception. When the Python function
Packit 534379
        call fails, a `error_already_set` exception is thrown.
Packit 534379
    \endrst */
Packit 534379
    template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
Packit 534379
    object operator()(Args &&...args) const;
Packit 534379
    template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
Packit 534379
    PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)")
Packit 534379
        object call(Args&&... args) const;
Packit 534379
Packit 534379
    /// Equivalent to ``obj is other`` in Python.
Packit 534379
    bool is(object_api const& other) const { return derived().ptr() == other.derived().ptr(); }
Packit 534379
    /// Equivalent to ``obj is None`` in Python.
Packit 534379
    bool is_none() const { return derived().ptr() == Py_None; }
Packit 534379
    /// Equivalent to obj == other in Python
Packit 534379
    bool equal(object_api const &other) const      { return rich_compare(other, Py_EQ); }
Packit 534379
    bool not_equal(object_api const &other) const  { return rich_compare(other, Py_NE); }
Packit 534379
    bool operator<(object_api const &other) const  { return rich_compare(other, Py_LT); }
Packit 534379
    bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); }
Packit 534379
    bool operator>(object_api const &other) const  { return rich_compare(other, Py_GT); }
Packit 534379
    bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); }
Packit 534379
Packit 534379
    object operator-() const;
Packit 534379
    object operator~() const;
Packit 534379
    object operator+(object_api const &other) const;
Packit 534379
    object operator+=(object_api const &other) const;
Packit 534379
    object operator-(object_api const &other) const;
Packit 534379
    object operator-=(object_api const &other) const;
Packit 534379
    object operator*(object_api const &other) const;
Packit 534379
    object operator*=(object_api const &other) const;
Packit 534379
    object operator/(object_api const &other) const;
Packit 534379
    object operator/=(object_api const &other) const;
Packit 534379
    object operator|(object_api const &other) const;
Packit 534379
    object operator|=(object_api const &other) const;
Packit 534379
    object operator&(object_api const &other) const;
Packit 534379
    object operator&=(object_api const &other) const;
Packit 534379
    object operator^(object_api const &other) const;
Packit 534379
    object operator^=(object_api const &other) const;
Packit 534379
    object operator<<(object_api const &other) const;
Packit 534379
    object operator<<=(object_api const &other) const;
Packit 534379
    object operator>>(object_api const &other) const;
Packit 534379
    object operator>>=(object_api const &other) const;
Packit 534379
Packit 534379
    PYBIND11_DEPRECATED("Use py::str(obj) instead")
Packit 534379
    pybind11::str str() const;
Packit 534379
Packit 534379
    /// Get or set the object's docstring, i.e. ``obj.__doc__``.
Packit 534379
    str_attr_accessor doc() const;
Packit 534379
Packit 534379
    /// Return the object's current reference count
Packit 534379
    int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); }
Packit 534379
    /// Return a handle to the Python type object underlying the instance
Packit 534379
    handle get_type() const;
Packit 534379
Packit 534379
private:
Packit 534379
    bool rich_compare(object_api const &other, int value) const;
Packit 534379
};
Packit 534379
Packit 534379
NAMESPACE_END(detail)
Packit 534379
Packit 534379
/** \rst
Packit 534379
    Holds a reference to a Python object (no reference counting)
Packit 534379
Packit 534379
    The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a
Packit 534379
    ``PyObject *`` in Python's C API). It does not perform any automatic reference
Packit 534379
    counting and merely provides a basic C++ interface to various Python API functions.
Packit 534379
Packit 534379
    .. seealso::
Packit 534379
        The `object` class inherits from `handle` and adds automatic reference
Packit 534379
        counting features.
Packit 534379
\endrst */
Packit 534379
class handle : public detail::object_api<handle> {
Packit 534379
public:
Packit 534379
    /// The default constructor creates a handle with a ``nullptr``-valued pointer
Packit 534379
    handle() = default;
Packit 534379
    /// Creates a ``handle`` from the given raw Python object pointer
Packit 534379
    handle(PyObject *ptr) : m_ptr(ptr) { } // Allow implicit conversion from PyObject*
Packit 534379
Packit 534379
    /// Return the underlying ``PyObject *`` pointer
Packit 534379
    PyObject *ptr() const { return m_ptr; }
Packit 534379
    PyObject *&ptr() { return m_ptr; }
Packit 534379
Packit 534379
    /** \rst
Packit 534379
        Manually increase the reference count of the Python object. Usually, it is
Packit 534379
        preferable to use the `object` class which derives from `handle` and calls
Packit 534379
        this function automatically. Returns a reference to itself.
Packit 534379
    \endrst */
Packit 534379
    const handle& inc_ref() const & { Py_XINCREF(m_ptr); return *this; }
Packit 534379
Packit 534379
    /** \rst
Packit 534379
        Manually decrease the reference count of the Python object. Usually, it is
Packit 534379
        preferable to use the `object` class which derives from `handle` and calls
Packit 534379
        this function automatically. Returns a reference to itself.
Packit 534379
    \endrst */
Packit 534379
    const handle& dec_ref() const & { Py_XDECREF(m_ptr); return *this; }
Packit 534379
Packit 534379
    /** \rst
Packit 534379
        Attempt to cast the Python object into the given C++ type. A `cast_error`
Packit 534379
        will be throw upon failure.
Packit 534379
    \endrst */
Packit 534379
    template <typename T> T cast() const;
Packit 534379
    /// Return ``true`` when the `handle` wraps a valid Python object
Packit 534379
    explicit operator bool() const { return m_ptr != nullptr; }
Packit 534379
    /** \rst
Packit 534379
        Deprecated: Check that the underlying pointers are the same.
Packit 534379
        Equivalent to ``obj1 is obj2`` in Python.
Packit 534379
    \endrst */
Packit 534379
    PYBIND11_DEPRECATED("Use obj1.is(obj2) instead")
Packit 534379
    bool operator==(const handle &h) const { return m_ptr == h.m_ptr; }
Packit 534379
    PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead")
Packit 534379
    bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }
Packit 534379
    PYBIND11_DEPRECATED("Use handle::operator bool() instead")
Packit 534379
    bool check() const { return m_ptr != nullptr; }
Packit 534379
protected:
Packit 534379
    PyObject *m_ptr = nullptr;
Packit 534379
};
Packit 534379
Packit 534379
/** \rst
Packit 534379
    Holds a reference to a Python object (with reference counting)
Packit 534379
Packit 534379
    Like `handle`, the `object` class is a thin wrapper around an arbitrary Python
Packit 534379
    object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it
Packit 534379
    optionally increases the object's reference count upon construction, and it
Packit 534379
    *always* decreases the reference count when the `object` instance goes out of
Packit 534379
    scope and is destructed. When using `object` instances consistently, it is much
Packit 534379
    easier to get reference counting right at the first attempt.
Packit 534379
\endrst */
Packit 534379
class object : public handle {
Packit 534379
public:
Packit 534379
    object() = default;
Packit 534379
    PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()")
Packit 534379
    object(handle h, bool is_borrowed) : handle(h) { if (is_borrowed) inc_ref(); }
Packit 534379
    /// Copy constructor; always increases the reference count
Packit 534379
    object(const object &o) : handle(o) { inc_ref(); }
Packit 534379
    /// Move constructor; steals the object from ``other`` and preserves its reference count
Packit 534379
    object(object &&other) noexcept { m_ptr = other.m_ptr; other.m_ptr = nullptr; }
Packit 534379
    /// Destructor; automatically calls `handle::dec_ref()`
Packit 534379
    ~object() { dec_ref(); }
Packit 534379
Packit 534379
    /** \rst
Packit 534379
        Resets the internal pointer to ``nullptr`` without without decreasing the
Packit 534379
        object's reference count. The function returns a raw handle to the original
Packit 534379
        Python object.
Packit 534379
    \endrst */
Packit 534379
    handle release() {
Packit 534379
      PyObject *tmp = m_ptr;
Packit 534379
      m_ptr = nullptr;
Packit 534379
      return handle(tmp);
Packit 534379
    }
Packit 534379
Packit 534379
    object& operator=(const object &other) {
Packit 534379
        other.inc_ref();
Packit 534379
        dec_ref();
Packit 534379
        m_ptr = other.m_ptr;
Packit 534379
        return *this;
Packit 534379
    }
Packit 534379
Packit 534379
    object& operator=(object &&other) noexcept {
Packit 534379
        if (this != &other) {
Packit 534379
            handle temp(m_ptr);
Packit 534379
            m_ptr = other.m_ptr;
Packit 534379
            other.m_ptr = nullptr;
Packit 534379
            temp.dec_ref();
Packit 534379
        }
Packit 534379
        return *this;
Packit 534379
    }
Packit 534379
Packit 534379
    // Calling cast() on an object lvalue just copies (via handle::cast)
Packit 534379
    template <typename T> T cast() const &;
Packit 534379
    // Calling on an object rvalue does a move, if needed and/or possible
Packit 534379
    template <typename T> T cast() &&;
Packit 534379
Packit 534379
protected:
Packit 534379
    // Tags for choosing constructors from raw PyObject *
Packit 534379
    struct borrowed_t { };
Packit 534379
    struct stolen_t { };
Packit 534379
Packit 534379
    template <typename T> friend T reinterpret_borrow(handle);
Packit 534379
    template <typename T> friend T reinterpret_steal(handle);
Packit 534379
Packit 534379
public:
Packit 534379
    // Only accessible from derived classes and the reinterpret_* functions
Packit 534379
    object(handle h, borrowed_t) : handle(h) { inc_ref(); }
Packit 534379
    object(handle h, stolen_t) : handle(h) { }
Packit 534379
};
Packit 534379
Packit 534379
/** \rst
Packit 534379
    Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference.
Packit 534379
    The target type ``T`` must be `object` or one of its derived classes. The function
Packit 534379
    doesn't do any conversions or checks. It's up to the user to make sure that the
Packit 534379
    target type is correct.
Packit 534379
Packit 534379
    .. code-block:: cpp
Packit 534379
Packit 534379
        PyObject *p = PyList_GetItem(obj, index);
Packit 534379
        py::object o = reinterpret_borrow<py::object>(p);
Packit 534379
        // or
Packit 534379
        py::tuple t = reinterpret_borrow<py::tuple>(p); // <-- `p` must be already be a `tuple`
Packit 534379
\endrst */
Packit 534379
template <typename T> T reinterpret_borrow(handle h) { return {h, object::borrowed_t{}}; }
Packit 534379
Packit 534379
/** \rst
Packit 534379
    Like `reinterpret_borrow`, but steals the reference.
Packit 534379
Packit 534379
     .. code-block:: cpp
Packit 534379
Packit 534379
        PyObject *p = PyObject_Str(obj);
Packit 534379
        py::str s = reinterpret_steal<py::str>(p); // <-- `p` must be already be a `str`
Packit 534379
\endrst */
Packit 534379
template <typename T> T reinterpret_steal(handle h) { return {h, object::stolen_t{}}; }
Packit 534379
Packit 534379
NAMESPACE_BEGIN(detail)
Packit 534379
inline std::string error_string();
Packit 534379
NAMESPACE_END(detail)
Packit 534379
Packit 534379
/// Fetch and hold an error which was already set in Python.  An instance of this is typically
Packit 534379
/// thrown to propagate python-side errors back through C++ which can either be caught manually or
Packit 534379
/// else falls back to the function dispatcher (which then raises the captured error back to
Packit 534379
/// python).
Packit 534379
class error_already_set : public std::runtime_error {
Packit 534379
public:
Packit 534379
    /// Constructs a new exception from the current Python error indicator, if any.  The current
Packit 534379
    /// Python error indicator will be cleared.
Packit 534379
    error_already_set() : std::runtime_error(detail::error_string()) {
Packit 534379
        PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
Packit 534379
    }
Packit 534379
Packit 534379
    error_already_set(const error_already_set &) = default;
Packit 534379
    error_already_set(error_already_set &&) = default;
Packit 534379
Packit 534379
    inline ~error_already_set();
Packit 534379
Packit 534379
    /// Give the currently-held error back to Python, if any.  If there is currently a Python error
Packit 534379
    /// already set it is cleared first.  After this call, the current object no longer stores the
Packit 534379
    /// error variables (but the `.what()` string is still available).
Packit 534379
    void restore() { PyErr_Restore(m_type.release().ptr(), m_value.release().ptr(), m_trace.release().ptr()); }
Packit 534379
Packit 534379
    // Does nothing; provided for backwards compatibility.
Packit 534379
    PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated")
Packit 534379
    void clear() {}
Packit 534379
Packit 534379
    /// Check if the currently trapped error type matches the given Python exception class (or a
Packit 534379
    /// subclass thereof).  May also be passed a tuple to search for any exception class matches in
Packit 534379
    /// the given tuple.
Packit 534379
    bool matches(handle exc) const { return PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()); }
Packit 534379
Packit 534379
    const object& type() const { return m_type; }
Packit 534379
    const object& value() const { return m_value; }
Packit 534379
    const object& trace() const { return m_trace; }
Packit 534379
Packit 534379
private:
Packit 534379
    object m_type, m_value, m_trace;
Packit 534379
};
Packit 534379
Packit 534379
/** \defgroup python_builtins _
Packit 534379
    Unless stated otherwise, the following C++ functions behave the same
Packit 534379
    as their Python counterparts.
Packit 534379
 */
Packit 534379
Packit 534379
/** \ingroup python_builtins
Packit 534379
    \rst
Packit 534379
    Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of
Packit 534379
    `object` or a class which was exposed to Python as ``py::class_<T>``.
Packit 534379
\endrst */
Packit 534379
template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0>
Packit 534379
bool isinstance(handle obj) { return T::check_(obj); }
Packit 534379
Packit 534379
template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0>
Packit 534379
bool isinstance(handle obj) { return detail::isinstance_generic(obj, typeid(T)); }
Packit 534379
Packit 534379
template <> inline bool isinstance<handle>(handle obj) = delete;
Packit 534379
template <> inline bool isinstance<object>(handle obj) { return obj.ptr() != nullptr; }
Packit 534379
Packit 534379
/// \ingroup python_builtins
Packit 534379
/// Return true if ``obj`` is an instance of the ``type``.
Packit 534379
inline bool isinstance(handle obj, handle type) {
Packit 534379
    const auto result = PyObject_IsInstance(obj.ptr(), type.ptr());
Packit 534379
    if (result == -1)
Packit 534379
        throw error_already_set();
Packit 534379
    return result != 0;
Packit 534379
}
Packit 534379
Packit 534379
/// \addtogroup python_builtins
Packit 534379
/// @{
Packit 534379
inline bool hasattr(handle obj, handle name) {
Packit 534379
    return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1;
Packit 534379
}
Packit 534379
Packit 534379
inline bool hasattr(handle obj, const char *name) {
Packit 534379
    return PyObject_HasAttrString(obj.ptr(), name) == 1;
Packit 534379
}
Packit 534379
Packit 534379
inline void delattr(handle obj, handle name) {
Packit 534379
    if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) { throw error_already_set(); }
Packit 534379
}
Packit 534379
Packit 534379
inline void delattr(handle obj, const char *name) {
Packit 534379
    if (PyObject_DelAttrString(obj.ptr(), name) != 0) { throw error_already_set(); }
Packit 534379
}
Packit 534379
Packit 534379
inline object getattr(handle obj, handle name) {
Packit 534379
    PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr());
Packit 534379
    if (!result) { throw error_already_set(); }
Packit 534379
    return reinterpret_steal<object>(result);
Packit 534379
}
Packit 534379
Packit 534379
inline object getattr(handle obj, const char *name) {
Packit 534379
    PyObject *result = PyObject_GetAttrString(obj.ptr(), name);
Packit 534379
    if (!result) { throw error_already_set(); }
Packit 534379
    return reinterpret_steal<object>(result);
Packit 534379
}
Packit 534379
Packit 534379
inline object getattr(handle obj, handle name, handle default_) {
Packit 534379
    if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) {
Packit 534379
        return reinterpret_steal<object>(result);
Packit 534379
    } else {
Packit 534379
        PyErr_Clear();
Packit 534379
        return reinterpret_borrow<object>(default_);
Packit 534379
    }
Packit 534379
}
Packit 534379
Packit 534379
inline object getattr(handle obj, const char *name, handle default_) {
Packit 534379
    if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) {
Packit 534379
        return reinterpret_steal<object>(result);
Packit 534379
    } else {
Packit 534379
        PyErr_Clear();
Packit 534379
        return reinterpret_borrow<object>(default_);
Packit 534379
    }
Packit 534379
}
Packit 534379
Packit 534379
inline void setattr(handle obj, handle name, handle value) {
Packit 534379
    if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) { throw error_already_set(); }
Packit 534379
}
Packit 534379
Packit 534379
inline void setattr(handle obj, const char *name, handle value) {
Packit 534379
    if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { throw error_already_set(); }
Packit 534379
}
Packit 534379
Packit 534379
inline ssize_t hash(handle obj) {
Packit 534379
    auto h = PyObject_Hash(obj.ptr());
Packit 534379
    if (h == -1) { throw error_already_set(); }
Packit 534379
    return h;
Packit 534379
}
Packit 534379
Packit 534379
/// @} python_builtins
Packit 534379
Packit 534379
NAMESPACE_BEGIN(detail)
Packit 534379
inline handle get_function(handle value) {
Packit 534379
    if (value) {
Packit 534379
#if PY_MAJOR_VERSION >= 3
Packit 534379
        if (PyInstanceMethod_Check(value.ptr()))
Packit 534379
            value = PyInstanceMethod_GET_FUNCTION(value.ptr());
Packit 534379
        else
Packit 534379
#endif
Packit 534379
        if (PyMethod_Check(value.ptr()))
Packit 534379
            value = PyMethod_GET_FUNCTION(value.ptr());
Packit 534379
    }
Packit 534379
    return value;
Packit 534379
}
Packit 534379
Packit 534379
// Helper aliases/functions to support implicit casting of values given to python accessors/methods.
Packit 534379
// When given a pyobject, this simply returns the pyobject as-is; for other C++ type, the value goes
Packit 534379
// through pybind11::cast(obj) to convert it to an `object`.
Packit 534379
template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0>
Packit 534379
auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) { return std::forward<T>(o); }
Packit 534379
// The following casting version is implemented in cast.h:
Packit 534379
template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0>
Packit 534379
object object_or_cast(T &&o);
Packit 534379
// Match a PyObject*, which we want to convert directly to handle via its converting constructor
Packit 534379
inline handle object_or_cast(PyObject *ptr) { return ptr; }
Packit 534379
Packit 534379
template <typename Policy>
Packit 534379
class accessor : public object_api<accessor<Policy>> {
Packit 534379
    using key_type = typename Policy::key_type;
Packit 534379
Packit 534379
public:
Packit 534379
    accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) { }
Packit 534379
    accessor(const accessor &) = default;
Packit 534379
    accessor(accessor &&) = default;
Packit 534379
Packit 534379
    // accessor overload required to override default assignment operator (templates are not allowed
Packit 534379
    // to replace default compiler-generated assignments).
Packit 534379
    void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); }
Packit 534379
    void operator=(const accessor &a) & { operator=(handle(a)); }
Packit 534379
Packit 534379
    template <typename T> void operator=(T &&value) && {
Packit 534379
        Policy::set(obj, key, object_or_cast(std::forward<T>(value)));
Packit 534379
    }
Packit 534379
    template <typename T> void operator=(T &&value) & {
Packit 534379
        get_cache() = reinterpret_borrow<object>(object_or_cast(std::forward<T>(value)));
Packit 534379
    }
Packit 534379
Packit 534379
    template <typename T = Policy>
Packit 534379
    PYBIND11_DEPRECATED("Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
Packit 534379
    explicit operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value ||
Packit 534379
            std::is_same<T, accessor_policies::obj_attr>::value, bool>() const {
Packit 534379
        return hasattr(obj, key);
Packit 534379
    }
Packit 534379
    template <typename T = Policy>
Packit 534379
    PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
Packit 534379
    explicit operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const {
Packit 534379
        return obj.contains(key);
Packit 534379
    }
Packit 534379
Packit 534379
    operator object() const { return get_cache(); }
Packit 534379
    PyObject *ptr() const { return get_cache().ptr(); }
Packit 534379
    template <typename T> T cast() const { return get_cache().template cast<T>(); }
Packit 534379
Packit 534379
private:
Packit 534379
    object &get_cache() const {
Packit 534379
        if (!cache) { cache = Policy::get(obj, key); }
Packit 534379
        return cache;
Packit 534379
    }
Packit 534379
Packit 534379
private:
Packit 534379
    handle obj;
Packit 534379
    key_type key;
Packit 534379
    mutable object cache;
Packit 534379
};
Packit 534379
Packit 534379
NAMESPACE_BEGIN(accessor_policies)
Packit 534379
struct obj_attr {
Packit 534379
    using key_type = object;
Packit 534379
    static object get(handle obj, handle key) { return getattr(obj, key); }
Packit 534379
    static void set(handle obj, handle key, handle val) { setattr(obj, key, val); }
Packit 534379
};
Packit 534379
Packit 534379
struct str_attr {
Packit 534379
    using key_type = const char *;
Packit 534379
    static object get(handle obj, const char *key) { return getattr(obj, key); }
Packit 534379
    static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); }
Packit 534379
};
Packit 534379
Packit 534379
struct generic_item {
Packit 534379
    using key_type = object;
Packit 534379
Packit 534379
    static object get(handle obj, handle key) {
Packit 534379
        PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr());
Packit 534379
        if (!result) { throw error_already_set(); }
Packit 534379
        return reinterpret_steal<object>(result);
Packit 534379
    }
Packit 534379
Packit 534379
    static void set(handle obj, handle key, handle val) {
Packit 534379
        if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) { throw error_already_set(); }
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
struct sequence_item {
Packit 534379
    using key_type = size_t;
Packit 534379
Packit 534379
    static object get(handle obj, size_t index) {
Packit 534379
        PyObject *result = PySequence_GetItem(obj.ptr(), static_cast<ssize_t>(index));
Packit 534379
        if (!result) { throw error_already_set(); }
Packit 534379
        return reinterpret_steal<object>(result);
Packit 534379
    }
Packit 534379
Packit 534379
    static void set(handle obj, size_t index, handle val) {
Packit 534379
        // PySequence_SetItem does not steal a reference to 'val'
Packit 534379
        if (PySequence_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.ptr()) != 0) {
Packit 534379
            throw error_already_set();
Packit 534379
        }
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
struct list_item {
Packit 534379
    using key_type = size_t;
Packit 534379
Packit 534379
    static object get(handle obj, size_t index) {
Packit 534379
        PyObject *result = PyList_GetItem(obj.ptr(), static_cast<ssize_t>(index));
Packit 534379
        if (!result) { throw error_already_set(); }
Packit 534379
        return reinterpret_borrow<object>(result);
Packit 534379
    }
Packit 534379
Packit 534379
    static void set(handle obj, size_t index, handle val) {
Packit 534379
        // PyList_SetItem steals a reference to 'val'
Packit 534379
        if (PyList_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.inc_ref().ptr()) != 0) {
Packit 534379
            throw error_already_set();
Packit 534379
        }
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
struct tuple_item {
Packit 534379
    using key_type = size_t;
Packit 534379
Packit 534379
    static object get(handle obj, size_t index) {
Packit 534379
        PyObject *result = PyTuple_GetItem(obj.ptr(), static_cast<ssize_t>(index));
Packit 534379
        if (!result) { throw error_already_set(); }
Packit 534379
        return reinterpret_borrow<object>(result);
Packit 534379
    }
Packit 534379
Packit 534379
    static void set(handle obj, size_t index, handle val) {
Packit 534379
        // PyTuple_SetItem steals a reference to 'val'
Packit 534379
        if (PyTuple_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.inc_ref().ptr()) != 0) {
Packit 534379
            throw error_already_set();
Packit 534379
        }
Packit 534379
    }
Packit 534379
};
Packit 534379
NAMESPACE_END(accessor_policies)
Packit 534379
Packit 534379
/// STL iterator template used for tuple, list, sequence and dict
Packit 534379
template <typename Policy>
Packit 534379
class generic_iterator : public Policy {
Packit 534379
    using It = generic_iterator;
Packit 534379
Packit 534379
public:
Packit 534379
    using difference_type = ssize_t;
Packit 534379
    using iterator_category = typename Policy::iterator_category;
Packit 534379
    using value_type = typename Policy::value_type;
Packit 534379
    using reference = typename Policy::reference;
Packit 534379
    using pointer = typename Policy::pointer;
Packit 534379
Packit 534379
    generic_iterator() = default;
Packit 534379
    generic_iterator(handle seq, ssize_t index) : Policy(seq, index) { }
Packit 534379
Packit 534379
    reference operator*() const { return Policy::dereference(); }
Packit 534379
    reference operator[](difference_type n) const { return *(*this + n); }
Packit 534379
    pointer operator->() const { return **this; }
Packit 534379
Packit 534379
    It &operator++() { Policy::increment(); return *this; }
Packit 534379
    It operator++(int) { auto copy = *this; Policy::increment(); return copy; }
Packit 534379
    It &operator--() { Policy::decrement(); return *this; }
Packit 534379
    It operator--(int) { auto copy = *this; Policy::decrement(); return copy; }
Packit 534379
    It &operator+=(difference_type n) { Policy::advance(n); return *this; }
Packit 534379
    It &operator-=(difference_type n) { Policy::advance(-n); return *this; }
Packit 534379
Packit 534379
    friend It operator+(const It &a, difference_type n) { auto copy = a; return copy += n; }
Packit 534379
    friend It operator+(difference_type n, const It &b) { return b + n; }
Packit 534379
    friend It operator-(const It &a, difference_type n) { auto copy = a; return copy -= n; }
Packit 534379
    friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); }
Packit 534379
Packit 534379
    friend bool operator==(const It &a, const It &b) { return a.equal(b); }
Packit 534379
    friend bool operator!=(const It &a, const It &b) { return !(a == b); }
Packit 534379
    friend bool operator< (const It &a, const It &b) { return b - a > 0; }
Packit 534379
    friend bool operator> (const It &a, const It &b) { return b < a; }
Packit 534379
    friend bool operator>=(const It &a, const It &b) { return !(a < b); }
Packit 534379
    friend bool operator<=(const It &a, const It &b) { return !(a > b); }
Packit 534379
};
Packit 534379
Packit 534379
NAMESPACE_BEGIN(iterator_policies)
Packit 534379
/// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers
Packit 534379
template <typename T>
Packit 534379
struct arrow_proxy {
Packit 534379
    T value;
Packit 534379
Packit 534379
    arrow_proxy(T &&value) : value(std::move(value)) { }
Packit 534379
    T *operator->() const { return &value; }
Packit 534379
};
Packit 534379
Packit 534379
/// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS``
Packit 534379
class sequence_fast_readonly {
Packit 534379
protected:
Packit 534379
    using iterator_category = std::random_access_iterator_tag;
Packit 534379
    using value_type = handle;
Packit 534379
    using reference = const handle;
Packit 534379
    using pointer = arrow_proxy<const handle>;
Packit 534379
Packit 534379
    sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) { }
Packit 534379
Packit 534379
    reference dereference() const { return *ptr; }
Packit 534379
    void increment() { ++ptr; }
Packit 534379
    void decrement() { --ptr; }
Packit 534379
    void advance(ssize_t n) { ptr += n; }
Packit 534379
    bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; }
Packit 534379
    ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; }
Packit 534379
Packit 534379
private:
Packit 534379
    PyObject **ptr;
Packit 534379
};
Packit 534379
Packit 534379
/// Full read and write access using the sequence protocol: see ``detail::sequence_accessor``
Packit 534379
class sequence_slow_readwrite {
Packit 534379
protected:
Packit 534379
    using iterator_category = std::random_access_iterator_tag;
Packit 534379
    using value_type = object;
Packit 534379
    using reference = sequence_accessor;
Packit 534379
    using pointer = arrow_proxy<const sequence_accessor>;
Packit 534379
Packit 534379
    sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) { }
Packit 534379
Packit 534379
    reference dereference() const { return {obj, static_cast<size_t>(index)}; }
Packit 534379
    void increment() { ++index; }
Packit 534379
    void decrement() { --index; }
Packit 534379
    void advance(ssize_t n) { index += n; }
Packit 534379
    bool equal(const sequence_slow_readwrite &b) const { return index == b.index; }
Packit 534379
    ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; }
Packit 534379
Packit 534379
private:
Packit 534379
    handle obj;
Packit 534379
    ssize_t index;
Packit 534379
};
Packit 534379
Packit 534379
/// Python's dictionary protocol permits this to be a forward iterator
Packit 534379
class dict_readonly {
Packit 534379
protected:
Packit 534379
    using iterator_category = std::forward_iterator_tag;
Packit 534379
    using value_type = std::pair<handle, handle>;
Packit 534379
    using reference = const value_type;
Packit 534379
    using pointer = arrow_proxy<const value_type>;
Packit 534379
Packit 534379
    dict_readonly() = default;
Packit 534379
    dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }
Packit 534379
Packit 534379
    reference dereference() const { return {key, value}; }
Packit 534379
    void increment() { if (!PyDict_Next(obj.ptr(), &pos, &key, &value)) { pos = -1; } }
Packit 534379
    bool equal(const dict_readonly &b) const { return pos == b.pos; }
Packit 534379
Packit 534379
private:
Packit 534379
    handle obj;
Packit 534379
    PyObject *key = nullptr, *value = nullptr;
Packit 534379
    ssize_t pos = -1;
Packit 534379
};
Packit 534379
NAMESPACE_END(iterator_policies)
Packit 534379
Packit 534379
#if !defined(PYPY_VERSION)
Packit 534379
using tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
Packit 534379
using list_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
Packit 534379
#else
Packit 534379
using tuple_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
Packit 534379
using list_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
Packit 534379
#endif
Packit 534379
Packit 534379
using sequence_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
Packit 534379
using dict_iterator = generic_iterator<iterator_policies::dict_readonly>;
Packit 534379
Packit 534379
inline bool PyIterable_Check(PyObject *obj) {
Packit 534379
    PyObject *iter = PyObject_GetIter(obj);
Packit 534379
    if (iter) {
Packit 534379
        Py_DECREF(iter);
Packit 534379
        return true;
Packit 534379
    } else {
Packit 534379
        PyErr_Clear();
Packit 534379
        return false;
Packit 534379
    }
Packit 534379
}
Packit 534379
Packit 534379
inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
Packit 534379
#if PY_MAJOR_VERSION >= 3
Packit 534379
inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }
Packit 534379
#endif
Packit 534379
Packit 534379
inline bool PyUnicode_Check_Permissive(PyObject *o) { return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); }
Packit 534379
Packit 534379
inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; }
Packit 534379
Packit 534379
class kwargs_proxy : public handle {
Packit 534379
public:
Packit 534379
    explicit kwargs_proxy(handle h) : handle(h) { }
Packit 534379
};
Packit 534379
Packit 534379
class args_proxy : public handle {
Packit 534379
public:
Packit 534379
    explicit args_proxy(handle h) : handle(h) { }
Packit 534379
    kwargs_proxy operator*() const { return kwargs_proxy(*this); }
Packit 534379
};
Packit 534379
Packit 534379
/// Python argument categories (using PEP 448 terms)
Packit 534379
template <typename T> using is_keyword = std::is_base_of<arg, T>;
Packit 534379
template <typename T> using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking
Packit 534379
template <typename T> using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking
Packit 534379
template <typename T> using is_positional = satisfies_none_of
Packit 534379
    is_keyword, is_s_unpacking, is_ds_unpacking
Packit 534379
>;
Packit 534379
template <typename T> using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>;
Packit 534379
Packit 534379
// Call argument collector forward declarations
Packit 534379
template <return_value_policy policy = return_value_policy::automatic_reference>
Packit 534379
class simple_collector;
Packit 534379
template <return_value_policy policy = return_value_policy::automatic_reference>
Packit 534379
class unpacking_collector;
Packit 534379
Packit 534379
NAMESPACE_END(detail)
Packit 534379
Packit 534379
// TODO: After the deprecated constructors are removed, this macro can be simplified by
Packit 534379
//       inheriting ctors: `using Parent::Parent`. It's not an option right now because
Packit 534379
//       the `using` statement triggers the parent deprecation warning even if the ctor
Packit 534379
//       isn't even used.
Packit 534379
#define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
Packit 534379
    public: \
Packit 534379
        PYBIND11_DEPRECATED("Use reinterpret_borrow<"#Name">() or reinterpret_steal<"#Name">()") \
Packit 534379
        Name(handle h, bool is_borrowed) : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) { } \
Packit 534379
        Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) { } \
Packit 534379
        Name(handle h, stolen_t) : Parent(h, stolen_t{}) { } \
Packit 534379
        PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
Packit 534379
        bool check() const { return m_ptr != nullptr && (bool) CheckFun(m_ptr); } \
Packit 534379
        static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); }
Packit 534379
Packit 534379
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
Packit 534379
    PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
Packit 534379
    /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
Packit 534379
    Name(const object &o) \
Packit 534379
    : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) \
Packit 534379
    { if (!m_ptr) throw error_already_set(); } \
Packit 534379
    Name(object &&o) \
Packit 534379
    : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) \
Packit 534379
    { if (!m_ptr) throw error_already_set(); } \
Packit 534379
    template <typename Policy_> \
Packit 534379
    Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) { }
Packit 534379
Packit 534379
#define PYBIND11_OBJECT(Name, Parent, CheckFun) \
Packit 534379
    PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
Packit 534379
    /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
Packit 534379
    Name(const object &o) : Parent(o) { } \
Packit 534379
    Name(object &&o) : Parent(std::move(o)) { }
Packit 534379
Packit 534379
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
Packit 534379
    PYBIND11_OBJECT(Name, Parent, CheckFun) \
Packit 534379
    Name() : Parent() { }
Packit 534379
Packit 534379
/// \addtogroup pytypes
Packit 534379
/// @{
Packit 534379
Packit 534379
/** \rst
Packit 534379
    Wraps a Python iterator so that it can also be used as a C++ input iterator
Packit 534379
Packit 534379
    Caveat: copying an iterator does not (and cannot) clone the internal
Packit 534379
    state of the Python iterable. This also applies to the post-increment
Packit 534379
    operator. This iterator should only be used to retrieve the current
Packit 534379
    value using ``operator*()``.
Packit 534379
\endrst */
Packit 534379
class iterator : public object {
Packit 534379
public:
Packit 534379
    using iterator_category = std::input_iterator_tag;
Packit 534379
    using difference_type = ssize_t;
Packit 534379
    using value_type = handle;
Packit 534379
    using reference = const handle;
Packit 534379
    using pointer = const handle *;
Packit 534379
Packit 534379
    PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)
Packit 534379
Packit 534379
    iterator& operator++() {
Packit 534379
        advance();
Packit 534379
        return *this;
Packit 534379
    }
Packit 534379
Packit 534379
    iterator operator++(int) {
Packit 534379
        auto rv = *this;
Packit 534379
        advance();
Packit 534379
        return rv;
Packit 534379
    }
Packit 534379
Packit 534379
    reference operator*() const {
Packit 534379
        if (m_ptr && !value.ptr()) {
Packit 534379
            auto& self = const_cast<iterator &>(*this);
Packit 534379
            self.advance();
Packit 534379
        }
Packit 534379
        return value;
Packit 534379
    }
Packit 534379
Packit 534379
    pointer operator->() const { operator*(); return &value; }
Packit 534379
Packit 534379
    /** \rst
Packit 534379
         The value which marks the end of the iteration. ``it == iterator::sentinel()``
Packit 534379
         is equivalent to catching ``StopIteration`` in Python.
Packit 534379
Packit 534379
         .. code-block:: cpp
Packit 534379
Packit 534379
             void foo(py::iterator it) {
Packit 534379
                 while (it != py::iterator::sentinel()) {
Packit 534379
                    // use `*it`
Packit 534379
                    ++it;
Packit 534379
                 }
Packit 534379
             }
Packit 534379
    \endrst */
Packit 534379
    static iterator sentinel() { return {}; }
Packit 534379
Packit 534379
    friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); }
Packit 534379
    friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); }
Packit 534379
Packit 534379
private:
Packit 534379
    void advance() {
Packit 534379
        value = reinterpret_steal<object>(PyIter_Next(m_ptr));
Packit 534379
        if (PyErr_Occurred()) { throw error_already_set(); }
Packit 534379
    }
Packit 534379
Packit 534379
private:
Packit 534379
    object value = {};
Packit 534379
};
Packit 534379
Packit 534379
class iterable : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check)
Packit 534379
};
Packit 534379
Packit 534379
class bytes;
Packit 534379
Packit 534379
class str : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_CVT(str, object, detail::PyUnicode_Check_Permissive, raw_str)
Packit 534379
Packit 534379
    str(const char *c, size_t n)
Packit 534379
        : object(PyUnicode_FromStringAndSize(c, (ssize_t) n), stolen_t{}) {
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate string object!");
Packit 534379
    }
Packit 534379
Packit 534379
    // 'explicit' is explicitly omitted from the following constructors to allow implicit conversion to py::str from C++ string-like objects
Packit 534379
    str(const char *c = "")
Packit 534379
        : object(PyUnicode_FromString(c), stolen_t{}) {
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate string object!");
Packit 534379
    }
Packit 534379
Packit 534379
    str(const std::string &s) : str(s.data(), s.size()) { }
Packit 534379
Packit 534379
    explicit str(const bytes &b);
Packit 534379
Packit 534379
    /** \rst
Packit 534379
        Return a string representation of the object. This is analogous to
Packit 534379
        the ``str()`` function in Python.
Packit 534379
    \endrst */
Packit 534379
    explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { }
Packit 534379
Packit 534379
    operator std::string() const {
Packit 534379
        object temp = *this;
Packit 534379
        if (PyUnicode_Check(m_ptr)) {
Packit 534379
            temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
Packit 534379
            if (!temp)
Packit 534379
                pybind11_fail("Unable to extract string contents! (encoding issue)");
Packit 534379
        }
Packit 534379
        char *buffer;
Packit 534379
        ssize_t length;
Packit 534379
        if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length))
Packit 534379
            pybind11_fail("Unable to extract string contents! (invalid type)");
Packit 534379
        return std::string(buffer, (size_t) length);
Packit 534379
    }
Packit 534379
Packit 534379
    template <typename... Args>
Packit 534379
    str format(Args &&...args) const {
Packit 534379
        return attr("format")(std::forward<Args>(args)...);
Packit 534379
    }
Packit 534379
Packit 534379
private:
Packit 534379
    /// Return string representation -- always returns a new reference, even if already a str
Packit 534379
    static PyObject *raw_str(PyObject *op) {
Packit 534379
        PyObject *str_value = PyObject_Str(op);
Packit 534379
#if PY_MAJOR_VERSION < 3
Packit 534379
        if (!str_value) throw error_already_set();
Packit 534379
        PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
Packit 534379
        Py_XDECREF(str_value); str_value = unicode;
Packit 534379
#endif
Packit 534379
        return str_value;
Packit 534379
    }
Packit 534379
};
Packit 534379
/// @} pytypes
Packit 534379
Packit 534379
inline namespace literals {
Packit 534379
/** \rst
Packit 534379
    String literal version of `str`
Packit 534379
 \endrst */
Packit 534379
inline str operator"" _s(const char *s, size_t size) { return {s, size}; }
Packit 534379
}
Packit 534379
Packit 534379
/// \addtogroup pytypes
Packit 534379
/// @{
Packit 534379
class bytes : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK)
Packit 534379
Packit 534379
    // Allow implicit conversion:
Packit 534379
    bytes(const char *c = "")
Packit 534379
        : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) {
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate bytes object!");
Packit 534379
    }
Packit 534379
Packit 534379
    bytes(const char *c, size_t n)
Packit 534379
        : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, (ssize_t) n), stolen_t{}) {
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate bytes object!");
Packit 534379
    }
Packit 534379
Packit 534379
    // Allow implicit conversion:
Packit 534379
    bytes(const std::string &s) : bytes(s.data(), s.size()) { }
Packit 534379
Packit 534379
    explicit bytes(const pybind11::str &s);
Packit 534379
Packit 534379
    operator std::string() const {
Packit 534379
        char *buffer;
Packit 534379
        ssize_t length;
Packit 534379
        if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length))
Packit 534379
            pybind11_fail("Unable to extract bytes contents!");
Packit 534379
        return std::string(buffer, (size_t) length);
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
inline bytes::bytes(const pybind11::str &s) {
Packit 534379
    object temp = s;
Packit 534379
    if (PyUnicode_Check(s.ptr())) {
Packit 534379
        temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));
Packit 534379
        if (!temp)
Packit 534379
            pybind11_fail("Unable to extract string contents! (encoding issue)");
Packit 534379
    }
Packit 534379
    char *buffer;
Packit 534379
    ssize_t length;
Packit 534379
    if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length))
Packit 534379
        pybind11_fail("Unable to extract string contents! (invalid type)");
Packit 534379
    auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));
Packit 534379
    if (!obj)
Packit 534379
        pybind11_fail("Could not allocate bytes object!");
Packit 534379
    m_ptr = obj.release().ptr();
Packit 534379
}
Packit 534379
Packit 534379
inline str::str(const bytes& b) {
Packit 534379
    char *buffer;
Packit 534379
    ssize_t length;
Packit 534379
    if (PYBIND11_BYTES_AS_STRING_AND_SIZE(b.ptr(), &buffer, &length))
Packit 534379
        pybind11_fail("Unable to extract bytes contents!");
Packit 534379
    auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, (ssize_t) length));
Packit 534379
    if (!obj)
Packit 534379
        pybind11_fail("Could not allocate string object!");
Packit 534379
    m_ptr = obj.release().ptr();
Packit 534379
}
Packit 534379
Packit 534379
class none : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT(none, object, detail::PyNone_Check)
Packit 534379
    none() : object(Py_None, borrowed_t{}) { }
Packit 534379
};
Packit 534379
Packit 534379
#if PY_MAJOR_VERSION >= 3
Packit 534379
class ellipsis : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check)
Packit 534379
    ellipsis() : object(Py_Ellipsis, borrowed_t{}) { }
Packit 534379
};
Packit 534379
#endif
Packit 534379
Packit 534379
class bool_ : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool)
Packit 534379
    bool_() : object(Py_False, borrowed_t{}) { }
Packit 534379
    // Allow implicit conversion from and to `bool`:
Packit 534379
    bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) { }
Packit 534379
    operator bool() const { return m_ptr && PyLong_AsLong(m_ptr) != 0; }
Packit 534379
Packit 534379
private:
Packit 534379
    /// Return the truth value of an object -- always returns a new reference
Packit 534379
    static PyObject *raw_bool(PyObject *op) {
Packit 534379
        const auto value = PyObject_IsTrue(op);
Packit 534379
        if (value == -1) return nullptr;
Packit 534379
        return handle(value ? Py_True : Py_False).inc_ref().ptr();
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
NAMESPACE_BEGIN(detail)
Packit 534379
// Converts a value to the given unsigned type.  If an error occurs, you get back (Unsigned) -1;
Packit 534379
// otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned).
Packit 534379
// (The distinction is critically important when casting a returned -1 error value to some other
Packit 534379
// unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes).
Packit 534379
template <typename Unsigned>
Packit 534379
Unsigned as_unsigned(PyObject *o) {
Packit 534379
    if (sizeof(Unsigned) <= sizeof(unsigned long)
Packit 534379
#if PY_VERSION_HEX < 0x03000000
Packit 534379
            || PyInt_Check(o)
Packit 534379
#endif
Packit 534379
    ) {
Packit 534379
        unsigned long v = PyLong_AsUnsignedLong(o);
Packit 534379
        return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
Packit 534379
    }
Packit 534379
    else {
Packit 534379
        unsigned long long v = PyLong_AsUnsignedLongLong(o);
Packit 534379
        return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
Packit 534379
    }
Packit 534379
}
Packit 534379
NAMESPACE_END(detail)
Packit 534379
Packit 534379
class int_ : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long)
Packit 534379
    int_() : object(PyLong_FromLong(0), stolen_t{}) { }
Packit 534379
    // Allow implicit conversion from C++ integral types:
Packit 534379
    template 
Packit 534379
              detail::enable_if_t<std::is_integral<T>::value, int> = 0>
Packit 534379
    int_(T value) {
Packit 534379
        if (sizeof(T) <= sizeof(long)) {
Packit 534379
            if (std::is_signed<T>::value)
Packit 534379
                m_ptr = PyLong_FromLong((long) value);
Packit 534379
            else
Packit 534379
                m_ptr = PyLong_FromUnsignedLong((unsigned long) value);
Packit 534379
        } else {
Packit 534379
            if (std::is_signed<T>::value)
Packit 534379
                m_ptr = PyLong_FromLongLong((long long) value);
Packit 534379
            else
Packit 534379
                m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value);
Packit 534379
        }
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate int object!");
Packit 534379
    }
Packit 534379
Packit 534379
    template 
Packit 534379
              detail::enable_if_t<std::is_integral<T>::value, int> = 0>
Packit 534379
    operator T() const {
Packit 534379
        return std::is_unsigned<T>::value
Packit 534379
            ? detail::as_unsigned<T>(m_ptr)
Packit 534379
            : sizeof(T) <= sizeof(long)
Packit 534379
              ? (T) PyLong_AsLong(m_ptr)
Packit 534379
              : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
class float_ : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)
Packit 534379
    // Allow implicit conversion from float/double:
Packit 534379
    float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate float object!");
Packit 534379
    }
Packit 534379
    float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate float object!");
Packit 534379
    }
Packit 534379
    operator float() const { return (float) PyFloat_AsDouble(m_ptr); }
Packit 534379
    operator double() const { return (double) PyFloat_AsDouble(m_ptr); }
Packit 534379
};
Packit 534379
Packit 534379
class weakref : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_DEFAULT(weakref, object, PyWeakref_Check)
Packit 534379
    explicit weakref(handle obj, handle callback = {})
Packit 534379
        : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) {
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate weak reference!");
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
class slice : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check)
Packit 534379
    slice(ssize_t start_, ssize_t stop_, ssize_t step_) {
Packit 534379
        int_ start(start_), stop(stop_), step(step_);
Packit 534379
        m_ptr = PySlice_New(start.ptr(), stop.ptr(), step.ptr());
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate slice object!");
Packit 534379
    }
Packit 534379
    bool compute(size_t length, size_t *start, size_t *stop, size_t *step,
Packit 534379
                 size_t *slicelength) const {
Packit 534379
        return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
Packit 534379
                                    (ssize_t) length, (ssize_t *) start,
Packit 534379
                                    (ssize_t *) stop, (ssize_t *) step,
Packit 534379
                                    (ssize_t *) slicelength) == 0;
Packit 534379
    }
Packit 534379
    bool compute(ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step,
Packit 534379
      ssize_t *slicelength) const {
Packit 534379
      return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
Packit 534379
          length, start,
Packit 534379
          stop, step,
Packit 534379
          slicelength) == 0;
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
class capsule : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact)
Packit 534379
    PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()")
Packit 534379
    capsule(PyObject *ptr, bool is_borrowed) : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) { }
Packit 534379
Packit 534379
    explicit capsule(const void *value, const char *name = nullptr, void (*destructor)(PyObject *) = nullptr)
Packit 534379
        : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) {
Packit 534379
        if (!m_ptr)
Packit 534379
            pybind11_fail("Could not allocate capsule object!");
Packit 534379
    }
Packit 534379
Packit 534379
    PYBIND11_DEPRECATED("Please pass a destructor that takes a void pointer as input")
Packit 534379
    capsule(const void *value, void (*destruct)(PyObject *))
Packit 534379
        : object(PyCapsule_New(const_cast<void*>(value), nullptr, destruct), stolen_t{}) {
Packit 534379
        if (!m_ptr)
Packit 534379
            pybind11_fail("Could not allocate capsule object!");
Packit 534379
    }
Packit 534379
Packit 534379
    capsule(const void *value, void (*destructor)(void *)) {
Packit 534379
        m_ptr = PyCapsule_New(const_cast<void *>(value), nullptr, [](PyObject *o) {
Packit 534379
            auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o));
Packit 534379
            void *ptr = PyCapsule_GetPointer(o, nullptr);
Packit 534379
            destructor(ptr);
Packit 534379
        });
Packit 534379
Packit 534379
        if (!m_ptr)
Packit 534379
            pybind11_fail("Could not allocate capsule object!");
Packit 534379
Packit 534379
        if (PyCapsule_SetContext(m_ptr, (void *) destructor) != 0)
Packit 534379
            pybind11_fail("Could not set capsule context!");
Packit 534379
    }
Packit 534379
Packit 534379
    capsule(void (*destructor)()) {
Packit 534379
        m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) {
Packit 534379
            auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, nullptr));
Packit 534379
            destructor();
Packit 534379
        });
Packit 534379
Packit 534379
        if (!m_ptr)
Packit 534379
            pybind11_fail("Could not allocate capsule object!");
Packit 534379
    }
Packit 534379
Packit 534379
    template <typename T> operator T *() const {
Packit 534379
        auto name = this->name();
Packit 534379
        T * result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));
Packit 534379
        if (!result) pybind11_fail("Unable to extract capsule contents!");
Packit 534379
        return result;
Packit 534379
    }
Packit 534379
Packit 534379
    const char *name() const { return PyCapsule_GetName(m_ptr); }
Packit 534379
};
Packit 534379
Packit 534379
class tuple : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple)
Packit 534379
    explicit tuple(size_t size = 0) : object(PyTuple_New((ssize_t) size), stolen_t{}) {
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate tuple object!");
Packit 534379
    }
Packit 534379
    size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
Packit 534379
    bool empty() const { return size() == 0; }
Packit 534379
    detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }
Packit 534379
    detail::item_accessor operator[](handle h) const { return object::operator[](h); }
Packit 534379
    detail::tuple_iterator begin() const { return {*this, 0}; }
Packit 534379
    detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }
Packit 534379
};
Packit 534379
Packit 534379
class dict : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)
Packit 534379
    dict() : object(PyDict_New(), stolen_t{}) {
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate dict object!");
Packit 534379
    }
Packit 534379
    template 
Packit 534379
              typename = detail::enable_if_t<detail::all_of<detail::is_keyword_or_ds<Args>...>::value>,
Packit 534379
              // MSVC workaround: it can't compile an out-of-line definition, so defer the collector
Packit 534379
              typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
Packit 534379
    explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) { }
Packit 534379
Packit 534379
    size_t size() const { return (size_t) PyDict_Size(m_ptr); }
Packit 534379
    bool empty() const { return size() == 0; }
Packit 534379
    detail::dict_iterator begin() const { return {*this, 0}; }
Packit 534379
    detail::dict_iterator end() const { return {}; }
Packit 534379
    void clear() const { PyDict_Clear(ptr()); }
Packit 534379
    template <typename T> bool contains(T &&key) const {
Packit 534379
        return PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr()) == 1;
Packit 534379
    }
Packit 534379
Packit 534379
private:
Packit 534379
    /// Call the `dict` Python type -- always returns a new reference
Packit 534379
    static PyObject *raw_dict(PyObject *op) {
Packit 534379
        if (PyDict_Check(op))
Packit 534379
            return handle(op).inc_ref().ptr();
Packit 534379
        return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
class sequence : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)
Packit 534379
    size_t size() const { return (size_t) PySequence_Size(m_ptr); }
Packit 534379
    bool empty() const { return size() == 0; }
Packit 534379
    detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
Packit 534379
    detail::item_accessor operator[](handle h) const { return object::operator[](h); }
Packit 534379
    detail::sequence_iterator begin() const { return {*this, 0}; }
Packit 534379
    detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; }
Packit 534379
};
Packit 534379
Packit 534379
class list : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
Packit 534379
    explicit list(size_t size = 0) : object(PyList_New((ssize_t) size), stolen_t{}) {
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate list object!");
Packit 534379
    }
Packit 534379
    size_t size() const { return (size_t) PyList_Size(m_ptr); }
Packit 534379
    bool empty() const { return size() == 0; }
Packit 534379
    detail::list_accessor operator[](size_t index) const { return {*this, index}; }
Packit 534379
    detail::item_accessor operator[](handle h) const { return object::operator[](h); }
Packit 534379
    detail::list_iterator begin() const { return {*this, 0}; }
Packit 534379
    detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
Packit 534379
    template <typename T> void append(T &&val) const {
Packit 534379
        PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
Packit 534379
    }
Packit 534379
    template <typename T> void insert(size_t index, T &&val) const {
Packit 534379
        PyList_Insert(m_ptr, static_cast<ssize_t>(index),
Packit 534379
            detail::object_or_cast(std::forward<T>(val)).ptr());
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
class args : public tuple { PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) };
Packit 534379
class kwargs : public dict { PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check)  };
Packit 534379
Packit 534379
class set : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_CVT(set, object, PySet_Check, PySet_New)
Packit 534379
    set() : object(PySet_New(nullptr), stolen_t{}) {
Packit 534379
        if (!m_ptr) pybind11_fail("Could not allocate set object!");
Packit 534379
    }
Packit 534379
    size_t size() const { return (size_t) PySet_Size(m_ptr); }
Packit 534379
    bool empty() const { return size() == 0; }
Packit 534379
    template <typename T> bool add(T &&val) const {
Packit 534379
        return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
Packit 534379
    }
Packit 534379
    void clear() const { PySet_Clear(m_ptr); }
Packit 534379
    template <typename T> bool contains(T &&val) const {
Packit 534379
        return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1;
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
class function : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)
Packit 534379
    handle cpp_function() const {
Packit 534379
        handle fun = detail::get_function(m_ptr);
Packit 534379
        if (fun && PyCFunction_Check(fun.ptr()))
Packit 534379
            return fun;
Packit 534379
        return handle();
Packit 534379
    }
Packit 534379
    bool is_cpp_function() const { return (bool) cpp_function(); }
Packit 534379
};
Packit 534379
Packit 534379
class staticmethod : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)
Packit 534379
};
Packit 534379
Packit 534379
class buffer : public object {
Packit 534379
public:
Packit 534379
    PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)
Packit 534379
Packit 534379
    buffer_info request(bool writable = false) const {
Packit 534379
        int flags = PyBUF_STRIDES | PyBUF_FORMAT;
Packit 534379
        if (writable) flags |= PyBUF_WRITABLE;
Packit 534379
        Py_buffer *view = new Py_buffer();
Packit 534379
        if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
Packit 534379
            delete view;
Packit 534379
            throw error_already_set();
Packit 534379
        }
Packit 534379
        return buffer_info(view);
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
class memoryview : public object {
Packit 534379
public:
Packit 534379
    explicit memoryview(const buffer_info& info) {
Packit 534379
        static Py_buffer buf { };
Packit 534379
        // Py_buffer uses signed sizes, strides and shape!..
Packit 534379
        static std::vector<Py_ssize_t> py_strides { };
Packit 534379
        static std::vector<Py_ssize_t> py_shape { };
Packit 534379
        buf.buf = info.ptr;
Packit 534379
        buf.itemsize = info.itemsize;
Packit 534379
        buf.format = const_cast<char *>(info.format.c_str());
Packit 534379
        buf.ndim = (int) info.ndim;
Packit 534379
        buf.len = info.size;
Packit 534379
        py_strides.clear();
Packit 534379
        py_shape.clear();
Packit 534379
        for (size_t i = 0; i < (size_t) info.ndim; ++i) {
Packit 534379
            py_strides.push_back(info.strides[i]);
Packit 534379
            py_shape.push_back(info.shape[i]);
Packit 534379
        }
Packit 534379
        buf.strides = py_strides.data();
Packit 534379
        buf.shape = py_shape.data();
Packit 534379
        buf.suboffsets = nullptr;
Packit 534379
        buf.readonly = false;
Packit 534379
        buf.internal = nullptr;
Packit 534379
Packit 534379
        m_ptr = PyMemoryView_FromBuffer(&buf;;
Packit 534379
        if (!m_ptr)
Packit 534379
            pybind11_fail("Unable to create memoryview from buffer descriptor");
Packit 534379
    }
Packit 534379
Packit 534379
    PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
Packit 534379
};
Packit 534379
/// @} pytypes
Packit 534379
Packit 534379
/// \addtogroup python_builtins
Packit 534379
/// @{
Packit 534379
inline size_t len(handle h) {
Packit 534379
    ssize_t result = PyObject_Length(h.ptr());
Packit 534379
    if (result < 0)
Packit 534379
        pybind11_fail("Unable to compute length of object");
Packit 534379
    return (size_t) result;
Packit 534379
}
Packit 534379
Packit 534379
inline size_t len_hint(handle h) {
Packit 534379
#if PY_VERSION_HEX >= 0x03040000
Packit 534379
    ssize_t result = PyObject_LengthHint(h.ptr(), 0);
Packit 534379
#else
Packit 534379
    ssize_t result = PyObject_Length(h.ptr());
Packit 534379
#endif
Packit 534379
    if (result < 0) {
Packit 534379
        // Sometimes a length can't be determined at all (eg generators)
Packit 534379
        // In which case simply return 0
Packit 534379
        PyErr_Clear();
Packit 534379
        return 0;
Packit 534379
    }
Packit 534379
    return (size_t) result;
Packit 534379
}
Packit 534379
Packit 534379
inline str repr(handle h) {
Packit 534379
    PyObject *str_value = PyObject_Repr(h.ptr());
Packit 534379
    if (!str_value) throw error_already_set();
Packit 534379
#if PY_MAJOR_VERSION < 3
Packit 534379
    PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
Packit 534379
    Py_XDECREF(str_value); str_value = unicode;
Packit 534379
    if (!str_value) throw error_already_set();
Packit 534379
#endif
Packit 534379
    return reinterpret_steal<str>(str_value);
Packit 534379
}
Packit 534379
Packit 534379
inline iterator iter(handle obj) {
Packit 534379
    PyObject *result = PyObject_GetIter(obj.ptr());
Packit 534379
    if (!result) { throw error_already_set(); }
Packit 534379
    return reinterpret_steal<iterator>(result);
Packit 534379
}
Packit 534379
/// @} python_builtins
Packit 534379
Packit 534379
NAMESPACE_BEGIN(detail)
Packit 534379
template <typename D> iterator object_api<D>::begin() const { return iter(derived()); }
Packit 534379
template <typename D> iterator object_api<D>::end() const { return iterator::sentinel(); }
Packit 534379
template <typename D> item_accessor object_api<D>::operator[](handle key) const {
Packit 534379
    return {derived(), reinterpret_borrow<object>(key)};
Packit 534379
}
Packit 534379
template <typename D> item_accessor object_api<D>::operator[](const char *key) const {
Packit 534379
    return {derived(), pybind11::str(key)};
Packit 534379
}
Packit 534379
template <typename D> obj_attr_accessor object_api<D>::attr(handle key) const {
Packit 534379
    return {derived(), reinterpret_borrow<object>(key)};
Packit 534379
}
Packit 534379
template <typename D> str_attr_accessor object_api<D>::attr(const char *key) const {
Packit 534379
    return {derived(), key};
Packit 534379
}
Packit 534379
template <typename D> args_proxy object_api<D>::operator*() const {
Packit 534379
    return args_proxy(derived().ptr());
Packit 534379
}
Packit 534379
template <typename D> template <typename T> bool object_api<D>::contains(T &&item) const {
Packit 534379
    return attr("__contains__")(std::forward<T>(item)).template cast<bool>();
Packit 534379
}
Packit 534379
Packit 534379
template <typename D>
Packit 534379
pybind11::str object_api<D>::str() const { return pybind11::str(derived()); }
Packit 534379
Packit 534379
template <typename D>
Packit 534379
str_attr_accessor object_api<D>::doc() const { return attr("__doc__"); }
Packit 534379
Packit 534379
template <typename D>
Packit 534379
handle object_api<D>::get_type() const { return (PyObject *) Py_TYPE(derived().ptr()); }
Packit 534379
Packit 534379
template <typename D>
Packit 534379
bool object_api<D>::rich_compare(object_api const &other, int value) const {
Packit 534379
    int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
Packit 534379
    if (rv == -1)
Packit 534379
        throw error_already_set();
Packit 534379
    return rv == 1;
Packit 534379
}
Packit 534379
Packit 534379
#define PYBIND11_MATH_OPERATOR_UNARY(op, fn)                                   \
Packit 534379
    template <typename D> object object_api<D>::op() const {                   \
Packit 534379
        object result = reinterpret_steal<object>(fn(derived().ptr()));        \
Packit 534379
        if (!result.ptr())                                                     \
Packit 534379
            throw error_already_set();                                         \
Packit 534379
        return result;                                                         \
Packit 534379
    }
Packit 534379
Packit 534379
#define PYBIND11_MATH_OPERATOR_BINARY(op, fn)                                  \
Packit 534379
    template <typename D>                                                      \
Packit 534379
    object object_api<D>::op(object_api const &other) const {                  \
Packit 534379
        object result = reinterpret_steal<object>(                             \
Packit 534379
            fn(derived().ptr(), other.derived().ptr()));                       \
Packit 534379
        if (!result.ptr())                                                     \
Packit 534379
            throw error_already_set();                                         \
Packit 534379
        return result;                                                         \
Packit 534379
    }
Packit 534379
Packit 534379
PYBIND11_MATH_OPERATOR_UNARY (operator~,   PyNumber_Invert)
Packit 534379
PYBIND11_MATH_OPERATOR_UNARY (operator-,   PyNumber_Negative)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator+,   PyNumber_Add)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator+=,  PyNumber_InPlaceAdd)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator-,   PyNumber_Subtract)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator-=,  PyNumber_InPlaceSubtract)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator*,   PyNumber_Multiply)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator*=,  PyNumber_InPlaceMultiply)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator/,   PyNumber_TrueDivide)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator/=,  PyNumber_InPlaceTrueDivide)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator|,   PyNumber_Or)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator|=,  PyNumber_InPlaceOr)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator&,   PyNumber_And)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator&=,  PyNumber_InPlaceAnd)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator^,   PyNumber_Xor)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator^=,  PyNumber_InPlaceXor)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator<<,  PyNumber_Lshift)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator<<=, PyNumber_InPlaceLshift)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator>>,  PyNumber_Rshift)
Packit 534379
PYBIND11_MATH_OPERATOR_BINARY(operator>>=, PyNumber_InPlaceRshift)
Packit 534379
Packit 534379
#undef PYBIND11_MATH_OPERATOR_UNARY
Packit 534379
#undef PYBIND11_MATH_OPERATOR_BINARY
Packit 534379
Packit 534379
NAMESPACE_END(detail)
Packit 534379
NAMESPACE_END(PYBIND11_NAMESPACE)