12 #include "detail/common.h"
13 #include "buffer_info.h"
15 #include <type_traits>
17 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
20 class
handle; class
object;
23 struct arg; struct arg_v;
25 PYBIND11_NAMESPACE_BEGIN(detail)
27 inline
bool isinstance_generic(handle obj, const std::
type_info &tp);
31 namespace accessor_policies {
48 template <
typename T>
using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
54 template <
typename Derived>
56 const Derived &derived()
const {
return static_cast<const Derived &
>(*this); }
96 template <
typename T>
bool contains(T &&item)
const;
108 template <return_value_policy policy = return_value_policy::automatic_reference,
typename... Args>
110 template <return_value_policy policy = return_value_policy::automatic_reference,
typename... Args>
111 PYBIND11_DEPRECATED(
"call(...) was deprecated in favor of operator()(...)")
112 object call(Args&&...
args)
const;
115 bool is(
object_api const& other)
const {
return derived().ptr() == other.derived().ptr(); }
117 bool is_none()
const {
return derived().ptr() == Py_None; }
120 bool not_equal(
object_api const &other)
const {
return rich_compare(other, Py_NE); }
121 bool operator<(
object_api const &other)
const {
return rich_compare(other, Py_LT); }
122 bool operator<=(
object_api const &other)
const {
return rich_compare(other, Py_LE); }
123 bool operator>(
object_api const &other)
const {
return rich_compare(other, Py_GT); }
124 bool operator>=(
object_api const &other)
const {
return rich_compare(other, Py_GE); }
126 object operator-()
const;
127 object operator~()
const;
128 object operator+(
object_api const &other)
const;
129 object operator+=(
object_api const &other)
const;
130 object operator-(
object_api const &other)
const;
131 object operator-=(
object_api const &other)
const;
133 object operator*=(
object_api const &other)
const;
134 object operator/(
object_api const &other)
const;
135 object operator/=(
object_api const &other)
const;
136 object operator|(
object_api const &other)
const;
137 object operator|=(
object_api const &other)
const;
138 object operator&(
object_api const &other)
const;
139 object operator&=(
object_api const &other)
const;
140 object operator^(
object_api const &other)
const;
141 object operator^=(
object_api const &other)
const;
142 object operator<<(
object_api const &other)
const;
143 object operator<<=(
object_api const &other)
const;
144 object operator>>(
object_api const &other)
const;
145 object operator>>=(
object_api const &other)
const;
147 PYBIND11_DEPRECATED(
"Use py::str(obj) instead")
148 pybind11::
str str() const;
154 int ref_count()
const {
return static_cast<int>(Py_REFCNT(derived().ptr())); }
160 bool rich_compare(
object_api const &other,
int value)
const;
163 PYBIND11_NAMESPACE_END(detail)
184 PyObject *
ptr()
const {
return m_ptr; }
185 PyObject *&ptr() {
return m_ptr; }
192 const handle&
inc_ref() const & { Py_XINCREF(m_ptr);
return *
this; }
199 const handle&
dec_ref() const & { Py_XDECREF(m_ptr);
return *
this; }
205 template <
typename T> T cast()
const;
207 explicit operator bool()
const {
return m_ptr !=
nullptr; }
212 PYBIND11_DEPRECATED(
"Use obj1.is(obj2) instead")
213 bool operator==(const handle &h)
const {
return m_ptr == h.m_ptr; }
214 PYBIND11_DEPRECATED(
"Use !obj1.is(obj2) instead")
215 bool operator!=(const handle &h)
const {
return m_ptr != h.m_ptr; }
216 PYBIND11_DEPRECATED(
"Use handle::operator bool() instead")
217 bool check()
const {
return m_ptr !=
nullptr; }
219 PyObject *m_ptr =
nullptr;
235 PYBIND11_DEPRECATED(
"Use reinterpret_borrow<object>() or reinterpret_steal<object>()")
240 object(
object &&other) noexcept { m_ptr = other.m_ptr; other.m_ptr =
nullptr; }
250 PyObject *tmp = m_ptr;
255 object& operator=(
const object &other) {
262 object& operator=(
object &&other) noexcept {
263 if (
this != &other) {
266 other.m_ptr =
nullptr;
273 template <
typename T> T cast() const &;
275 template <typename T> T cast() &&;
316 PYBIND11_NAMESPACE_BEGIN(detail)
317 inline std::
string error_string();
318 PYBIND11_NAMESPACE_END(detail)
329 PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
340 void restore() { PyErr_Restore(m_type.release().ptr(), m_value.release().ptr(), m_trace.release().ptr()); }
350 PyErr_WriteUnraisable(err_context.
ptr());
352 void discard_as_unraisable(
const char *err_context) {
353 discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context)));
357 PYBIND11_DEPRECATED(
"Use of error_already_set.clear() is deprecated")
363 bool matches(
handle exc)
const {
return PyErr_GivenExceptionMatches(m_type.ptr(), exc.
ptr()); }
365 const object&
type()
const {
return m_type; }
366 const object& value()
const {
return m_value; }
367 const object& trace()
const {
return m_trace; }
370 object m_type, m_value, m_trace;
383 template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value,
int> = 0>
386 template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value,
int> = 0>
387 bool isinstance(
handle obj) {
return detail::isinstance_generic(obj,
typeid(T)); }
389 template <>
inline bool isinstance<handle>(
handle) =
delete;
390 template <>
inline bool isinstance<object>(
handle obj) {
return obj.
ptr() !=
nullptr; }
395 const auto result = PyObject_IsInstance(obj.
ptr(), type.
ptr());
404 return PyObject_HasAttr(obj.
ptr(), name.
ptr()) == 1;
407 inline bool hasattr(
handle obj,
const char *name) {
408 return PyObject_HasAttrString(obj.
ptr(), name) == 1;
415 inline void delattr(
handle obj,
const char *name) {
420 PyObject *result = PyObject_GetAttr(obj.
ptr(), name.
ptr());
422 return reinterpret_steal<object>(result);
425 inline object getattr(
handle obj,
const char *name) {
426 PyObject *result = PyObject_GetAttrString(obj.
ptr(), name);
428 return reinterpret_steal<object>(result);
432 if (PyObject *result = PyObject_GetAttr(obj.
ptr(), name.
ptr())) {
433 return reinterpret_steal<object>(result);
436 return reinterpret_borrow<object>(default_);
440 inline object getattr(
handle obj,
const char *name,
handle default_) {
441 if (PyObject *result = PyObject_GetAttrString(obj.
ptr(), name)) {
442 return reinterpret_steal<object>(result);
445 return reinterpret_borrow<object>(default_);
453 inline void setattr(
handle obj,
const char *name,
handle value) {
457 inline ssize_t hash(
handle obj) {
458 auto h = PyObject_Hash(obj.
ptr());
465 PYBIND11_NAMESPACE_BEGIN(detail)
468 #if PY_MAJOR_VERSION >= 3
469 if (PyInstanceMethod_Check(value.ptr()))
470 value = PyInstanceMethod_GET_FUNCTION(value.ptr());
473 if (PyMethod_Check(value.ptr()))
474 value = PyMethod_GET_FUNCTION(value.ptr());
482 template <typename T, enable_if_t<is_pyobject<T>::value,
int> = 0>
483 auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) {
return std::forward<T>(o); }
485 template <typename T, enable_if_t<!is_pyobject<T>::value,
int> = 0>
486 object object_or_cast(T &&o);
488 inline handle object_or_cast(PyObject *ptr) {
return ptr; }
490 template <
typename Policy>
492 using key_type =
typename Policy::key_type;
495 accessor(
handle obj, key_type key) : obj(obj), key(std::move(key)) { }
501 void operator=(
const accessor &a) && { std::move(*this).operator=(
handle(a)); }
504 template <
typename T>
void operator=(T &&value) && {
505 Policy::set(obj, key, object_or_cast(std::forward<T>(value)));
507 template <
typename T>
void operator=(T &&value) & {
508 get_cache() = reinterpret_borrow<object>(object_or_cast(std::forward<T>(value)));
511 template <
typename T = Policy>
512 PYBIND11_DEPRECATED(
"Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
513 explicit operator enable_if_t<std::is_same<T, accessor_policies::
str_attr>::value ||
514 std::is_same<T, accessor_policies::
obj_attr>::value,
bool>()
const {
515 return hasattr(obj, key);
517 template <
typename T = Policy>
518 PYBIND11_DEPRECATED(
"Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
519 explicit operator enable_if_t<std::is_same<T, accessor_policies::
generic_item>::value,
bool>()
const {
520 return obj.contains(key);
523 operator object()
const {
return get_cache(); }
524 PyObject *ptr()
const {
return get_cache().
ptr(); }
525 template <
typename T> T cast()
const {
return get_cache().template cast<T>(); }
528 object &get_cache()
const {
529 if (!cache) { cache = Policy::get(obj, key); }
536 mutable object cache;
539 PYBIND11_NAMESPACE_BEGIN(accessor_policies)
542 static object get(
handle obj,
handle key) {
return getattr(obj, key); }
547 using key_type =
const char *;
548 static object get(
handle obj,
const char *key) {
return getattr(obj, key); }
549 static void set(
handle obj,
const char *key,
handle val) { setattr(obj, key, val); }
556 PyObject *result = PyObject_GetItem(obj.
ptr(), key.ptr());
558 return reinterpret_steal<object>(result);
567 using key_type = size_t;
569 static object get(
handle obj,
size_t index) {
570 PyObject *result = PySequence_GetItem(obj.
ptr(),
static_cast<ssize_t
>(index));
572 return reinterpret_steal<object>(result);
577 if (PySequence_SetItem(obj.
ptr(),
static_cast<ssize_t
>(index), val.
ptr()) != 0) {
584 using key_type = size_t;
586 static object get(
handle obj,
size_t index) {
587 PyObject *result = PyList_GetItem(obj.
ptr(),
static_cast<ssize_t
>(index));
589 return reinterpret_borrow<object>(result);
594 if (PyList_SetItem(obj.
ptr(),
static_cast<ssize_t
>(index), val.
inc_ref().
ptr()) != 0) {
601 using key_type = size_t;
603 static object get(
handle obj,
size_t index) {
604 PyObject *result = PyTuple_GetItem(obj.
ptr(),
static_cast<ssize_t
>(index));
606 return reinterpret_borrow<object>(result);
611 if (PyTuple_SetItem(obj.
ptr(),
static_cast<ssize_t
>(index), val.
inc_ref().
ptr()) != 0) {
616 PYBIND11_NAMESPACE_END(accessor_policies)
619 template <typename Policy>
624 using difference_type = ssize_t;
625 using iterator_category =
typename Policy::iterator_category;
626 using value_type =
typename Policy::value_type;
627 using reference =
typename Policy::reference;
628 using pointer =
typename Policy::pointer;
633 reference operator*()
const {
return Policy::dereference(); }
634 reference operator[](difference_type n)
const {
return *(*
this + n); }
635 pointer operator->()
const {
return **
this; }
637 It &operator++() { Policy::increment();
return *
this; }
638 It operator++(
int) {
auto copy = *
this; Policy::increment();
return copy; }
639 It &operator--() { Policy::decrement();
return *
this; }
640 It operator--(
int) {
auto copy = *
this; Policy::decrement();
return copy; }
641 It &operator+=(difference_type n) { Policy::advance(n);
return *
this; }
642 It &operator-=(difference_type n) { Policy::advance(-n);
return *
this; }
644 friend It operator+(
const It &a, difference_type n) {
auto copy = a;
return copy += n; }
645 friend It operator+(difference_type n,
const It &b) {
return b + n; }
646 friend It operator-(
const It &a, difference_type n) {
auto copy = a;
return copy -= n; }
647 friend difference_type operator-(
const It &a,
const It &b) {
return a.distance_to(b); }
649 friend bool operator==(
const It &a,
const It &b) {
return a.equal(b); }
650 friend bool operator!=(
const It &a,
const It &b) {
return !(a == b); }
651 friend bool operator< (
const It &a,
const It &b) {
return b - a > 0; }
652 friend bool operator> (
const It &a,
const It &b) {
return b < a; }
653 friend bool operator>=(
const It &a,
const It &b) {
return !(a < b); }
654 friend bool operator<=(
const It &a,
const It &b) {
return !(a > b); }
657 PYBIND11_NAMESPACE_BEGIN(iterator_policies)
659 template <typename T>
663 arrow_proxy(T &&value) : value(std::move(value)) { }
664 T *operator->()
const {
return &value; }
670 using iterator_category = std::random_access_iterator_tag;
677 reference dereference()
const {
return *ptr; }
678 void increment() { ++ptr; }
679 void decrement() { --ptr; }
680 void advance(ssize_t n) { ptr += n; }
691 using iterator_category = std::random_access_iterator_tag;
698 reference dereference()
const {
return {obj,
static_cast<size_t>(index)}; }
699 void increment() { ++index; }
700 void decrement() { --index; }
701 void advance(ssize_t n) { index += n; }
713 using iterator_category = std::forward_iterator_tag;
714 using value_type = std::pair<handle, handle>;
715 using reference =
const value_type;
721 reference dereference()
const {
return {key, value}; }
722 void increment() {
if (!PyDict_Next(obj.
ptr(), &pos, &key, &value)) { pos = -1; } }
723 bool equal(
const dict_readonly &b)
const {
return pos == b.pos; }
727 PyObject *key =
nullptr, *value =
nullptr;
730 PYBIND11_NAMESPACE_END(iterator_policies)
732 #if !defined(PYPY_VERSION)
743 inline bool PyIterable_Check(PyObject *obj) {
744 PyObject *iter = PyObject_GetIter(obj);
754 inline bool PyNone_Check(PyObject *o) {
return o == Py_None; }
755 inline bool PyEllipsis_Check(PyObject *o) {
return o == Py_Ellipsis; }
757 inline bool PyUnicode_Check_Permissive(PyObject *o) {
return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); }
759 inline bool PyStaticMethod_Check(PyObject *o) {
return o->ob_type == &PyStaticMethod_Type; }
773 template <
typename T>
using is_keyword = std::is_base_of<arg, T>;
774 template <
typename T>
using is_s_unpacking = std::is_same<args_proxy, T>;
775 template <
typename T>
using is_ds_unpacking = std::is_same<kwargs_proxy, T>;
777 is_keyword, is_s_unpacking, is_ds_unpacking
782 template <return_value_policy policy = return_value_policy::automatic_reference>
784 template <return_value_policy policy = return_value_policy::automatic_reference>
787 PYBIND11_NAMESPACE_END(detail)
793 #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
795 PYBIND11_DEPRECATED("Use reinterpret_borrow<"#Name">() or reinterpret_steal<"#Name">()") \
796 Name(handle h, bool is_borrowed) : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) { } \
797 Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) { } \
798 Name(handle h, stolen_t) : Parent(h, stolen_t{}) { } \
799 PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
800 bool check() const { return m_ptr != nullptr && (bool) CheckFun(m_ptr); } \
801 static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \
802 template <typename Policy_> \
803 Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) { }
805 #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
806 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
808 Name(const object &o) \
809 : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) \
810 { if (!m_ptr) throw error_already_set(); } \
812 : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) \
813 { if (!m_ptr) throw error_already_set(); }
815 #define PYBIND11_OBJECT_CHECK_FAILED(Name, o) \
816 ::pybind11::type_error("Object of type '" + \
817 ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o.ptr())) + \
818 "' is not an instance of '" #Name "'")
820 #define PYBIND11_OBJECT(Name, Parent, CheckFun) \
821 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
823 Name(const object &o) : Parent(o) \
824 { if (o && !check_(o)) throw PYBIND11_OBJECT_CHECK_FAILED(Name, o); } \
825 Name(object &&o) : Parent(std::move(o)) \
826 { if (o && !check_(o)) throw PYBIND11_OBJECT_CHECK_FAILED(Name, o); }
828 #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
829 PYBIND11_OBJECT(Name, Parent, CheckFun) \
830 Name() : Parent() { }
845 using iterator_category = std::input_iterator_tag;
846 using difference_type = ssize_t;
851 PYBIND11_OBJECT_DEFAULT(
iterator,
object, PyIter_Check)
865 if (m_ptr && !value.ptr()) {
866 auto&
self =
const_cast<iterator &
>(*this);
872 pointer operator->()
const { operator*();
return &value; }
894 value = reinterpret_steal<object>(PyIter_Next(m_ptr));
906 PYBIND11_OBJECT(
type,
object, PyType_Check)
919 static handle handle_of();
930 PYBIND11_OBJECT_DEFAULT(
iterable,
object, detail::PyIterable_Check)
937 PYBIND11_OBJECT_CVT(
str,
object, detail::PyUnicode_Check_Permissive, raw_str)
939 str(
const char *c,
size_t n)
940 :
object(PyUnicode_FromStringAndSize(c, (ssize_t) n),
stolen_t{}) {
941 if (!m_ptr) pybind11_fail(
"Could not allocate string object!");
945 str(
const char *c =
"")
947 if (!m_ptr) pybind11_fail(
"Could not allocate string object!");
950 str(
const std::string &s) :
str(s.data(), s.size()) { }
960 operator std::string()
const {
962 if (PyUnicode_Check(m_ptr)) {
963 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
965 pybind11_fail(
"Unable to extract string contents! (encoding issue)");
969 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.
ptr(), &buffer, &length))
970 pybind11_fail(
"Unable to extract string contents! (invalid type)");
971 return std::string(buffer, (
size_t) length);
974 template <
typename... Args>
975 str format(Args &&...
args)
const {
976 return attr(
"format")(std::forward<Args>(
args)...);
982 PyObject *str_value = PyObject_Str(op);
983 #if PY_MAJOR_VERSION < 3
985 PyObject *unicode = PyUnicode_FromEncodedObject(str_value,
"utf-8",
nullptr);
986 Py_XDECREF(str_value); str_value = unicode;
993 inline namespace literals {
997 inline str operator"" _s(
const char *s,
size_t size) {
return {s, size}; }
1004 PYBIND11_OBJECT(
bytes,
object, PYBIND11_BYTES_CHECK)
1007 bytes(
const char *c =
"")
1009 if (!m_ptr) pybind11_fail(
"Could not allocate bytes object!");
1012 bytes(
const char *c,
size_t n)
1013 :
object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, (ssize_t) n),
stolen_t{}) {
1014 if (!m_ptr) pybind11_fail(
"Could not allocate bytes object!");
1018 bytes(
const std::string &s) :
bytes(s.data(), s.size()) { }
1020 explicit bytes(
const pybind11::str &s);
1022 operator std::string()
const {
1025 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length))
1026 pybind11_fail(
"Unable to extract bytes contents!");
1027 return std::string(buffer, (
size_t) length);
1034 inline bytes::bytes(
const pybind11::str &s) {
1036 if (PyUnicode_Check(s.ptr())) {
1037 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));
1039 pybind11_fail(
"Unable to extract string contents! (encoding issue)");
1043 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.
ptr(), &buffer, &length))
1044 pybind11_fail(
"Unable to extract string contents! (invalid type)");
1045 auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));
1047 pybind11_fail(
"Could not allocate bytes object!");
1048 m_ptr = obj.release().ptr();
1051 inline str::str(
const bytes& b) {
1054 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(b.
ptr(), &buffer, &length))
1055 pybind11_fail(
"Unable to extract bytes contents!");
1056 auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, (ssize_t) length));
1058 pybind11_fail(
"Could not allocate string object!");
1059 m_ptr = obj.release().ptr();
1066 PYBIND11_OBJECT(
none,
object, detail::PyNone_Check)
1072 PYBIND11_OBJECT(
ellipsis,
object, detail::PyEllipsis_Check)
1078 PYBIND11_OBJECT_CVT(
bool_,
object, PyBool_Check, raw_bool)
1082 operator bool()
const {
return m_ptr && PyLong_AsLong(m_ptr) != 0; }
1087 const auto value = PyObject_IsTrue(op);
1088 if (value == -1)
return nullptr;
1093 PYBIND11_NAMESPACE_BEGIN(detail)
1098 template <typename Unsigned>
1099 Unsigned as_unsigned(PyObject *o) {
1100 if (
sizeof(Unsigned) <=
sizeof(
unsigned long)
1101 #
if PY_VERSION_HEX < 0x03000000
1105 unsigned long v = PyLong_AsUnsignedLong(o);
1106 return v == (
unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1109 unsigned long long v = PyLong_AsUnsignedLongLong(o);
1110 return v == (
unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1113 PYBIND11_NAMESPACE_END(detail)
1117 PYBIND11_OBJECT_CVT(
int_,
object, PYBIND11_LONG_CHECK, PyNumber_Long)
1120 template <
typename T,
1121 detail::enable_if_t<std::is_integral<T>::value,
int> = 0>
1123 if (
sizeof(T) <=
sizeof(
long)) {
1124 if (std::is_signed<T>::value)
1125 m_ptr = PyLong_FromLong((
long) value);
1127 m_ptr = PyLong_FromUnsignedLong((
unsigned long) value);
1129 if (std::is_signed<T>::value)
1130 m_ptr = PyLong_FromLongLong((
long long) value);
1132 m_ptr = PyLong_FromUnsignedLongLong((
unsigned long long) value);
1134 if (!m_ptr) pybind11_fail(
"Could not allocate int object!");
1137 template <
typename T,
1138 detail::enable_if_t<std::is_integral<T>::value,
int> = 0>
1139 operator T()
const {
1140 return std::is_unsigned<T>::value
1141 ? detail::as_unsigned<T>(m_ptr)
1142 :
sizeof(T) <=
sizeof(long)
1143 ? (T) PyLong_AsLong(m_ptr)
1144 : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
1150 PYBIND11_OBJECT_CVT(
float_,
object, PyFloat_Check, PyNumber_Float)
1153 if (!m_ptr) pybind11_fail(
"Could not allocate float object!");
1156 if (!m_ptr) pybind11_fail(
"Could not allocate float object!");
1158 operator float()
const {
return (
float) PyFloat_AsDouble(m_ptr); }
1159 operator double()
const {
return (
double) PyFloat_AsDouble(m_ptr); }
1164 PYBIND11_OBJECT_DEFAULT(
weakref,
object, PyWeakref_Check)
1166 :
object(PyWeakref_NewRef(obj.
ptr(), callback.ptr()),
stolen_t{}) {
1167 if (!m_ptr) pybind11_fail(
"Could not allocate weak reference!");
1173 PYBIND11_OBJECT_DEFAULT(
slice,
object, PySlice_Check)
1174 slice(ssize_t start_, ssize_t stop_, ssize_t step_) {
1175 int_ start(start_), stop(stop_), step(step_);
1176 m_ptr = PySlice_New(start.ptr(), stop.ptr(), step.
ptr());
1177 if (!m_ptr) pybind11_fail(
"Could not allocate slice object!");
1179 bool compute(
size_t length,
size_t *start,
size_t *stop,
size_t *step,
1180 size_t *slicelength)
const {
1181 return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1182 (ssize_t) length, (ssize_t *) start,
1183 (ssize_t *) stop, (ssize_t *) step,
1184 (ssize_t *) slicelength) == 0;
1186 bool compute(ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step,
1187 ssize_t *slicelength)
const {
1188 return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1197 PYBIND11_OBJECT_DEFAULT(
capsule,
object, PyCapsule_CheckExact)
1198 PYBIND11_DEPRECATED(
"Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()")
1201 explicit capsule(
const void *value,
const char *name =
nullptr,
void (*destructor)(PyObject *) =
nullptr)
1202 :
object(PyCapsule_New(const_cast<void *>(value), name, destructor),
stolen_t{}) {
1204 pybind11_fail(
"Could not allocate capsule object!");
1207 PYBIND11_DEPRECATED(
"Please pass a destructor that takes a void pointer as input")
1208 capsule(
const void *value,
void (*destruct)(PyObject *))
1209 :
object(PyCapsule_New(const_cast<void*>(value),
nullptr, destruct),
stolen_t{}) {
1211 pybind11_fail(
"Could not allocate capsule object!");
1214 capsule(
const void *value,
void (*destructor)(
void *)) {
1215 m_ptr = PyCapsule_New(const_cast<void *>(value),
nullptr, [](PyObject *o) {
1216 auto destructor =
reinterpret_cast<void (*)(
void *)
>(PyCapsule_GetContext(o));
1217 void *ptr = PyCapsule_GetPointer(o,
nullptr);
1222 pybind11_fail(
"Could not allocate capsule object!");
1224 if (PyCapsule_SetContext(m_ptr, (
void *) destructor) != 0)
1225 pybind11_fail(
"Could not set capsule context!");
1228 capsule(
void (*destructor)()) {
1229 m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor),
nullptr, [](PyObject *o) {
1230 auto destructor =
reinterpret_cast<void (*)()
>(PyCapsule_GetPointer(o,
nullptr));
1235 pybind11_fail(
"Could not allocate capsule object!");
1238 template <
typename T>
operator T *()
const {
1239 return get_pointer<T>();
1243 template<
typename T =
void>
1244 T* get_pointer()
const {
1245 auto name = this->name();
1246 T *result =
static_cast<T *
>(PyCapsule_GetPointer(m_ptr, name));
1247 if (!result) pybind11_fail(
"Unable to extract capsule contents!");
1252 void set_pointer(
const void *value) {
1253 if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0)
1254 pybind11_fail(
"Could not set capsule pointer");
1257 const char *name()
const {
return PyCapsule_GetName(m_ptr); }
1262 PYBIND11_OBJECT_CVT(
tuple,
object, PyTuple_Check, PySequence_Tuple)
1264 if (!m_ptr) pybind11_fail(
"Could not allocate tuple object!");
1266 size_t size()
const {
return (
size_t) PyTuple_Size(m_ptr); }
1267 bool empty()
const {
return size() == 0; }
1268 detail::tuple_accessor operator[](
size_t index)
const {
return {*
this, index}; }
1269 detail::item_accessor operator[](
handle h)
const {
return object::operator[](h); }
1270 detail::tuple_iterator begin()
const {
return {*
this, 0}; }
1271 detail::tuple_iterator end()
const {
return {*
this, PyTuple_GET_SIZE(m_ptr)}; }
1276 PYBIND11_OBJECT_CVT(
dict,
object, PyDict_Check, raw_dict)
1278 if (!m_ptr) pybind11_fail(
"Could not allocate dict object!");
1280 template <
typename... Args,
1281 typename = detail::enable_if_t<detail::all_of<detail::is_keyword_or_ds<Args>...>::value>,
1283 typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
1286 size_t size()
const {
return (
size_t) PyDict_Size(m_ptr); }
1287 bool empty()
const {
return size() == 0; }
1288 detail::dict_iterator begin()
const {
return {*
this, 0}; }
1289 detail::dict_iterator end()
const {
return {}; }
1290 void clear()
const { PyDict_Clear(ptr()); }
1291 template <
typename T>
bool contains(T &&key)
const {
1292 return PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr()) == 1;
1298 if (PyDict_Check(op))
1300 return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op,
nullptr);
1306 PYBIND11_OBJECT_DEFAULT(
sequence,
object, PySequence_Check)
1307 size_t size()
const {
1308 ssize_t result = PySequence_Size(m_ptr);
1311 return (
size_t) result;
1313 bool empty()
const {
return size() == 0; }
1314 detail::sequence_accessor operator[](
size_t index)
const {
return {*
this, index}; }
1315 detail::item_accessor operator[](
handle h)
const {
return object::operator[](h); }
1316 detail::sequence_iterator begin()
const {
return {*
this, 0}; }
1317 detail::sequence_iterator end()
const {
return {*
this, PySequence_Size(m_ptr)}; }
1322 PYBIND11_OBJECT_CVT(
list,
object, PyList_Check, PySequence_List)
1324 if (!m_ptr) pybind11_fail(
"Could not allocate list object!");
1326 size_t size()
const {
return (
size_t) PyList_Size(m_ptr); }
1327 bool empty()
const {
return size() == 0; }
1328 detail::list_accessor operator[](
size_t index)
const {
return {*
this, index}; }
1329 detail::item_accessor operator[](
handle h)
const {
return object::operator[](h); }
1330 detail::list_iterator begin()
const {
return {*
this, 0}; }
1331 detail::list_iterator end()
const {
return {*
this, PyList_GET_SIZE(m_ptr)}; }
1332 template <
typename T>
void append(T &&val)
const {
1333 PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
1335 template <
typename T>
void insert(
size_t index, T &&val)
const {
1336 PyList_Insert(m_ptr, static_cast<ssize_t>(index),
1337 detail::object_or_cast(std::forward<T>(val)).ptr());
1346 PYBIND11_OBJECT_CVT(
set,
object, PySet_Check, PySet_New)
1348 if (!m_ptr) pybind11_fail(
"Could not allocate set object!");
1350 size_t size()
const {
return (
size_t) PySet_Size(m_ptr); }
1351 bool empty()
const {
return size() == 0; }
1352 template <
typename T>
bool add(T &&val)
const {
1353 return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
1355 void clear()
const { PySet_Clear(m_ptr); }
1356 template <
typename T>
bool contains(T &&val)
const {
1357 return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1;
1363 PYBIND11_OBJECT_DEFAULT(
function,
object, PyCallable_Check)
1365 handle fun = detail::get_function(m_ptr);
1366 if (fun && PyCFunction_Check(fun.
ptr()))
1370 bool is_cpp_function()
const {
return (
bool)
cpp_function(); }
1375 PYBIND11_OBJECT_CVT(
staticmethod,
object, detail::PyStaticMethod_Check, PyStaticMethod_New)
1380 PYBIND11_OBJECT_DEFAULT(buffer,
object, PyObject_CheckBuffer)
1382 buffer_info request(
bool writable =
false)
const {
1383 int flags = PyBUF_STRIDES | PyBUF_FORMAT;
1384 if (writable) flags |= PyBUF_WRITABLE;
1385 auto *view =
new Py_buffer();
1386 if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
1396 PYBIND11_OBJECT_CVT(
memoryview,
object, PyMemoryView_Check, PyMemoryView_FromObject)
1409 pybind11_fail(
"Prohibited to create memoryview without Py_buffer");
1411 m_ptr = (info.view()->obj) ?
1412 PyMemoryView_FromObject(info.view()->obj) :
1413 PyMemoryView_FromBuffer(info.view());
1415 pybind11_fail(
"Unable to create memoryview from buffer descriptor");
1442 void *ptr, ssize_t itemsize,
const char *format,
1443 detail::any_container<ssize_t> shape,
1444 detail::any_container<ssize_t> strides,
bool readonly =
false);
1447 const void *ptr, ssize_t itemsize,
const char *format,
1448 detail::any_container<ssize_t> shape,
1449 detail::any_container<ssize_t> strides) {
1451 const_cast<void*>(ptr), itemsize, format, shape, strides,
true);
1454 template<
typename T>
1456 T *ptr, detail::any_container<ssize_t> shape,
1457 detail::any_container<ssize_t> strides,
bool readonly =
false) {
1459 reinterpret_cast<void*>(ptr),
sizeof(T),
1463 template<
typename T>
1465 const T *ptr, detail::any_container<ssize_t> shape,
1466 detail::any_container<ssize_t> strides) {
1468 const_cast<T*>(ptr), shape, strides,
true);
1471 #if PY_MAJOR_VERSION >= 3
1485 static memoryview from_memory(
void *mem, ssize_t size,
bool readonly =
false) {
1486 PyObject* ptr = PyMemoryView_FromMemory(
1487 reinterpret_cast<char*>(mem), size,
1488 (readonly) ? PyBUF_READ : PyBUF_WRITE);
1490 pybind11_fail(
"Could not allocate memoryview object!");
1494 static memoryview from_memory(
const void *mem, ssize_t size) {
1495 return memoryview::from_memory(const_cast<void*>(mem), size,
true);
1500 #ifndef DOXYGEN_SHOULD_SKIP_THIS
1502 void *ptr, ssize_t itemsize,
const char* format,
1503 detail::any_container<ssize_t> shape,
1504 detail::any_container<ssize_t> strides,
bool readonly) {
1505 size_t ndim = shape->size();
1506 if (ndim != strides->size())
1507 pybind11_fail(
"memoryview: shape length doesn't match strides length");
1508 ssize_t size = ndim ? 1 : 0;
1509 for (
size_t i = 0; i < ndim; ++i)
1510 size *= (*shape)[i];
1514 view.len = size * itemsize;
1515 view.readonly =
static_cast<int>(readonly);
1516 view.itemsize = itemsize;
1517 view.format =
const_cast<char*
>(format);
1518 view.ndim =
static_cast<int>(ndim);
1519 view.shape = shape->data();
1520 view.strides = strides->data();
1521 view.suboffsets =
nullptr;
1522 view.internal =
nullptr;
1523 PyObject* obj = PyMemoryView_FromBuffer(&view);
1528 #endif // DOXYGEN_SHOULD_SKIP_THIS
1536 ssize_t result = PyObject_Length(h.
ptr());
1539 return (
size_t) result;
1545 #if PY_VERSION_HEX >= 0x03040000
1546 ssize_t result = PyObject_LengthHint(h.
ptr(), 0);
1548 ssize_t result = PyObject_Length(h.
ptr());
1556 return (
size_t) result;
1560 PyObject *str_value = PyObject_Repr(h.
ptr());
1562 #if PY_MAJOR_VERSION < 3
1563 PyObject *unicode = PyUnicode_FromEncodedObject(str_value,
"utf-8",
nullptr);
1564 Py_XDECREF(str_value); str_value = unicode;
1567 return reinterpret_steal<str>(str_value);
1571 PyObject *result = PyObject_GetIter(obj.
ptr());
1573 return reinterpret_steal<iterator>(result);
1577 PYBIND11_NAMESPACE_BEGIN(detail)
1581 return {derived(), reinterpret_borrow<object>(key)};
1584 return {derived(), pybind11::str(key)};
1587 return {derived(), reinterpret_borrow<object>(key)};
1590 return {derived(), key};
1596 return attr(
"__contains__")(std::forward<T>(item)).template cast<bool>();
1599 template <
typename D>
1602 template <
typename D>
1605 template <
typename D>
1608 template <
typename D>
1610 int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
1616 #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
1617 template <typename D> object object_api<D>::op() const { \
1618 object result = reinterpret_steal<object>(fn(derived().ptr())); \
1619 if (!result.ptr()) \
1620 throw error_already_set(); \
1624 #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
1625 template <typename D> \
1626 object object_api<D>::op(object_api const &other) const { \
1627 object result = reinterpret_steal<object>( \
1628 fn(derived().ptr(), other.derived().ptr())); \
1629 if (!result.ptr()) \
1630 throw error_already_set(); \
1634 PYBIND11_MATH_OPERATOR_UNARY (
operator~, PyNumber_Invert)
1635 PYBIND11_MATH_OPERATOR_UNARY (operator-, PyNumber_Negative)
1636 PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)
1637 PYBIND11_MATH_OPERATOR_BINARY(operator+=, PyNumber_InPlaceAdd)
1638 PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)
1639 PYBIND11_MATH_OPERATOR_BINARY(operator-=, PyNumber_InPlaceSubtract)
1640 PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)
1641 PYBIND11_MATH_OPERATOR_BINARY(operator*=, PyNumber_InPlaceMultiply)
1642 PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)
1643 PYBIND11_MATH_OPERATOR_BINARY(operator/=, PyNumber_InPlaceTrueDivide)
1644 PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)
1645 PYBIND11_MATH_OPERATOR_BINARY(operator|=, PyNumber_InPlaceOr)
1646 PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)
1647 PYBIND11_MATH_OPERATOR_BINARY(operator&=, PyNumber_InPlaceAnd)
1648 PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)
1649 PYBIND11_MATH_OPERATOR_BINARY(operator^=, PyNumber_InPlaceXor)
1650 PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)
1651 PYBIND11_MATH_OPERATOR_BINARY(operator<<=, PyNumber_InPlaceLshift)
1652 PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)
1653 PYBIND11_MATH_OPERATOR_BINARY(operator>>=, PyNumber_InPlaceRshift)
1655 #undef PYBIND11_MATH_OPERATOR_UNARY
1656 #undef PYBIND11_MATH_OPERATOR_BINARY
1658 PYBIND11_NAMESPACE_END(detail)
1659 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
Quick proxy class needed to implement operator-> for iterators which can't return pointers.
iterator end() const
Return a sentinel which ends iteration.
object(object &&other) noexcept
Move constructor; steals the object from other and preserves its reference count. ...
bool contains(T &&item) const
Check if the given item is contained within this object, i.e. item in obj.
friend T reinterpret_borrow(handle)
static PyObject * raw_str(PyObject *op)
Return string representation – always returns a new reference, even if already a str...
Annotation for documentation.
const handle & dec_ref() const &
static PyObject * raw_bool(PyObject *op)
Return the truth value of an object – always returns a new reference.
handle(PyObject *ptr)
Creates a handle from the given raw Python object pointer.
friend T reinterpret_steal(handle)
static type of(handle h)
Return a type object from a handle or an object.
STL iterator template used for tuple, list, sequence and dict.
bool isinstance(handle obj)
object operator()(Args &&...args) const
~object()
Destructor; automatically calls handle::dec_ref()
object(const object &o)
Copy constructor; always increases the reference count.
str_attr_accessor doc() const
Get or set the object's docstring, i.e. obj.__doc__.
bool equal(object_api const &other) const
Equivalent to obj == other in Python.
PyObject * ptr() const
Return the underlying PyObject * pointer.
const handle & inc_ref() const &
args_proxy operator*() const
Python's dictionary protocol permits this to be a forward iterator.
Full read and write access using the sequence protocol: see detail::sequence_accessor ...
Tag and check to identify a class which implements the Python object API.
bool is(object_api const &other) const
Equivalent to obj is other in Python.
int ref_count() const
Return the object's current reference count.
obj_attr_accessor attr(handle key) const
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
size_t len_hint(handle h)
bool is_none() const
Equivalent to obj is None in Python.
static memoryview from_buffer(void *ptr, ssize_t itemsize, const char *format, detail::any_container< ssize_t > shape, detail::any_container< ssize_t > strides, bool readonly=false)
void discard_as_unraisable(object err_context)
static iterator sentinel()
Annotation for function names.
item_accessor operator[](handle key) const
Information record describing a Python buffer object.
size_t len(handle h)
Get the length of a Python object.
static PyObject * raw_dict(PyObject *op)
Call the dict Python type – always returns a new reference.
static handle handle_of()
bool matches(handle exc) const
handle()=default
The default constructor creates a handle with a nullptr-valued pointer.
Lightweight iterator policy using just a simple pointer: see PySequence_Fast_ITEMS ...