Go to the documentation of this file.
18 #include <frameobject.h>
22 #include <type_traits>
26 #if defined(PYBIND11_HAS_OPTIONAL)
30 #ifdef PYBIND11_HAS_STRING_VIEW
31 # include <string_view>
52 template <typename Policy>
73 using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
79 template <
typename Derived>
81 const Derived &
derived()
const {
return static_cast<const Derived &
>(*this); }
125 template <
typename T>
190 return static_cast<ssize_t>(
static_cast<int>(Py_REFCNT(
derived().ptr())));
192 return Py_REFCNT(
derived().ptr());
204 template <
typename T>
206 std::is_same<T, PyObject *const>,
207 std::is_same<T, std::nullptr_t>>;
211 #if !defined(PYBIND11_HANDLE_REF_DEBUG) && !defined(NDEBUG)
212 # define PYBIND11_HANDLE_REF_DEBUG
226 class handle :
public detail::object_api<handle> {
233 template <
typename T,
241 detail::enable_if_t<detail::all_of<detail::none_of<std::is_base_of<handle, T>,
242 detail::is_pyobj_ptr_or_nullptr_t<T>>,
243 std::is_convertible<T, PyObject *>>
::value,
259 #ifdef PYBIND11_HANDLE_REF_DEBUG
262 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
263 if (
m_ptr !=
nullptr && !PyGILState_Check()) {
277 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
278 if (
m_ptr !=
nullptr && !PyGILState_Check()) {
290 template <
typename T>
293 explicit operator bool()
const {
return m_ptr !=
nullptr; }
309 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
313 "%s is being called while the GIL is either not held or invalid. Please see "
314 "https://pybind11.readthedocs.io/en/stable/advanced/"
315 "misc.html#common-sources-of-global-interpreter-lock-errors for debugging advice.\n"
316 "If you are convinced there is no bug in your code, you can #define "
317 "PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF "
318 "to disable this check. In that case you have to ensure this #define is consistently "
319 "used for all translation units linked into a given pybind11 extension, otherwise "
320 "there will be ODR violations.",
321 function_name.c_str());
322 if (Py_TYPE(
m_ptr)->tp_name !=
nullptr) {
324 " The failing %s call was triggered on a %s object.",
325 function_name.c_str(),
326 Py_TYPE(
m_ptr)->tp_name);
330 throw std::runtime_error(function_name +
" PyGILState_Check() failure.");
334 #ifdef PYBIND11_HANDLE_REF_DEBUG
347 PyErr_SetString(
type.
ptr(), message);
386 PyObject *tmp =
m_ptr;
393 if (!this->is(
other)) {
405 if (
this != &
other) {
408 other.m_ptr =
nullptr;
414 #define PYBIND11_INPLACE_OP(iop) \
415 object iop(object_api const &other) { return operator=(handle::iop(other)); }
426 #undef PYBIND11_INPLACE_OP
429 template <
typename T>
432 template <typename
T>
441 template <
typename T>
443 template <
typename T>
466 template <
typename T>
479 template <
typename T>
488 if (PyType_Check(obj)) {
489 return reinterpret_cast<PyTypeObject *
>(obj)->tp_name;
491 return Py_TYPE(obj)->tp_name;
519 "Python error indicator not set.");
522 if (exc_type_name_orig ==
nullptr) {
524 +
" failed to obtain the name "
525 "of the original active exception type.");
528 #if PY_VERSION_HEX >= 0x030C0000
532 if (PyObject_HasAttrString(
m_value.
ptr(),
"__notes__")) {
541 +
" failed to normalize the "
542 "active exception.");
545 if (exc_type_name_norm ==
nullptr) {
547 +
" failed to obtain the name "
548 "of the normalized active exception type.");
550 # if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x07030a00
557 std::string
msg = std::string(called)
558 +
": MISMATCH of original and normalized "
559 "active exception types: ";
562 msg +=
" REPLACED BY ";
563 msg += exc_type_name_norm;
576 std::string message_error_string;
578 auto value_str = reinterpret_steal<object>(PyObject_Str(
m_value.
ptr()));
579 constexpr
const char *message_unavailable_exc
580 =
"<MESSAGE UNAVAILABLE DUE TO ANOTHER EXCEPTION>";
583 result = message_unavailable_exc;
587 auto value_bytes = reinterpret_steal<object>(
588 PyUnicode_AsEncodedString(value_str.ptr(),
"utf-8",
"backslashreplace"));
591 result = message_unavailable_exc;
594 Py_ssize_t length = 0;
595 if (PyBytes_AsStringAndSize(value_bytes.ptr(), &
buffer, &length) == -1) {
597 result = message_unavailable_exc;
603 #if PY_VERSION_HEX >= 0x030B0000
605 = reinterpret_steal<object>(PyObject_GetAttrString(
m_value.
ptr(),
"__notes__"));
609 auto len_notes = PyList_Size(notes.ptr());
613 result +=
"\n__notes__ (len=" + std::to_string(len_notes) +
"):";
615 PyObject *note = PyList_GET_ITEM(notes.ptr(),
i);
616 auto note_bytes = reinterpret_steal<object>(
617 PyUnicode_AsEncodedString(note,
"utf-8",
"backslashreplace"));
619 result +=
"\nFAILURE obtaining __notes__[" + std::to_string(
i)
623 Py_ssize_t length = 0;
624 if (PyBytes_AsStringAndSize(note_bytes.ptr(), &
buffer, &length)
626 result +=
"\nFAILURE formatting __notes__[" + std::to_string(
i)
638 result =
"<MESSAGE UNAVAILABLE>";
641 result =
"<EMPTY MESSAGE>";
644 bool have_trace =
false;
646 #if !defined(PYPY_VERSION)
647 auto *tb =
reinterpret_cast<PyTracebackObject *
>(
m_trace.
ptr());
650 while (tb->tb_next) {
654 PyFrameObject *frame = tb->tb_frame;
658 # if PY_VERSION_HEX >= 0x030900B1
659 PyCodeObject *f_code = PyFrame_GetCode(frame);
661 PyCodeObject *f_code = frame->f_code;
664 int lineno = PyFrame_GetLineNumber(frame);
668 result += std::to_string(lineno);
673 # if PY_VERSION_HEX >= 0x030900B1
674 auto *b_frame = PyFrame_GetBack(frame);
676 auto *b_frame = frame->f_back;
687 if (!message_error_string.empty()) {
691 result +=
"\nMESSAGE UNAVAILABLE DUE TO EXCEPTION: " + message_error_string;
707 pybind11_fail(
"Internal error: pybind11::detail::error_fetch_and_normalize::restore() "
708 "called a second time. ORIGINAL ERROR: "
716 return (PyErr_GivenExceptionMatches(
m_type.
ptr(), exc.
ptr()) != 0);
744 : m_fetched_error{
new detail::error_fetch_and_normalize(
"pybind11::error_already_set"),
745 m_fetched_error_deleter} {}
750 const char *what() const noexcept override;
757 void restore() { m_fetched_error->restore(); }
765 PyErr_WriteUnraisable(err_context.
ptr());
783 const object &
type()
const {
return m_fetched_error->m_type; }
784 const object &
value()
const {
return m_fetched_error->m_value; }
785 const object &
trace()
const {
return m_fetched_error->m_trace; }
792 static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr);
801 PyObject *exc =
nullptr, *val =
nullptr, *val2 =
nullptr, *tb =
nullptr;
803 assert(PyErr_Occurred());
804 PyErr_Fetch(&exc, &val, &tb);
805 PyErr_NormalizeException(&exc, &val, &tb);
807 PyException_SetTraceback(val, tb);
811 assert(!PyErr_Occurred());
813 PyErr_SetString(
type, message);
815 PyErr_Fetch(&exc, &val2, &tb);
816 PyErr_NormalizeException(&exc, &val2, &tb);
818 PyException_SetCause(val2, val);
819 PyException_SetContext(val2, val);
820 PyErr_Restore(exc, val2, tb);
843 return T::check_(obj);
855 return obj.
ptr() !=
nullptr;
871 return PyObject_HasAttr(obj.
ptr(),
name.ptr()) == 1;
875 return PyObject_HasAttrString(obj.
ptr(),
name) == 1;
879 if (PyObject_DelAttr(obj.
ptr(),
name.ptr()) != 0) {
885 if (PyObject_DelAttrString(obj.
ptr(),
name) != 0) {
895 return reinterpret_steal<object>(
result);
903 return reinterpret_steal<object>(
result);
907 if (PyObject *
result = PyObject_GetAttr(obj.
ptr(),
name.ptr())) {
908 return reinterpret_steal<object>(
result);
911 return reinterpret_borrow<object>(default_);
915 if (PyObject *
result = PyObject_GetAttrString(obj.
ptr(),
name)) {
916 return reinterpret_steal<object>(
result);
919 return reinterpret_borrow<object>(default_);
923 if (PyObject_SetAttr(obj.
ptr(),
name.ptr(),
value.ptr()) != 0) {
929 if (PyObject_SetAttrString(obj.
ptr(),
name,
value.ptr()) != 0) {
935 auto h = PyObject_Hash(obj.
ptr());
947 if (PyInstanceMethod_Check(
value.ptr())) {
948 value = PyInstanceMethod_GET_FUNCTION(
value.ptr());
949 }
else if (PyMethod_Check(
value.ptr())) {
961 PyObject *kv =
nullptr, *rv =
nullptr;
962 kv = PyUnicode_FromString(
key);
967 rv = PyDict_GetItemWithError(
v, kv);
969 if (rv ==
nullptr && PyErr_Occurred()) {
976 PyObject *rv = PyDict_GetItemWithError(
v,
key);
977 if (rv ==
nullptr && PyErr_Occurred()) {
984 #if PY_VERSION_HEX >= 0x030D0000
986 if (PyDict_GetItemStringRef(
v,
key, &rv) < 0) {
992 if (rv ==
nullptr && PyErr_Occurred()) {
1005 return std::forward<T>(o);
1013 PYBIND11_WARNING_PUSH
1015 template <typename Policy>
1017 using key_type =
typename Policy::key_type;
1026 void operator=(const
accessor &
a) && { std::move(*this).operator=(
handle(
a)); }
1029 template <
typename T>
1030 void operator=(
T &&
value) && {
1033 template <
typename T>
1034 void operator=(
T &&
value) & {
1038 template <
typename T = Policy>
1040 "Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
1047 template <
typename T = Policy>
1048 PYBIND11_DEPRECATED(
"Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
1051 return obj.contains(
key);
1055 operator object()
const {
return get_cache(); }
1056 PyObject *ptr()
const {
return get_cache().ptr(); }
1057 template <
typename T>
1059 return get_cache().template cast<T>();
1063 static object ensure_object(
object &&o) {
return std::move(o); }
1064 static object ensure_object(
handle h) {
return reinterpret_borrow<object>(
h); }
1066 object &get_cache()
const {
1076 mutable object cache;
1097 PyObject *
result = PyObject_GetItem(obj.
ptr(),
key.ptr());
1101 return reinterpret_steal<object>(
result);
1105 if (PyObject_SetItem(obj.
ptr(),
key.ptr(), val.
ptr()) != 0) {
1120 return reinterpret_steal<object>(
result);
1141 return reinterpret_borrow<object>(
result);
1162 return reinterpret_borrow<object>(
result);
1175 template <
typename Policy>
1197 Policy::increment();
1202 Policy::increment();
1206 Policy::decrement();
1211 Policy::decrement();
1219 Policy::advance(-
n);
1244 template <
typename T>
1324 #if !defined(PYPY_VERSION)
1336 PyObject *
iter = PyObject_GetIter(obj);
1348 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
1349 inline bool PyUnicode_Check_Permissive(PyObject *o) {
1352 # define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive
1354 # define PYBIND11_STR_CHECK_FUN PyUnicode_Check
1371 template <
typename T>
1373 template <
typename T>
1375 template <
typename T>
1377 template <
typename T>
1379 template <
typename T>
1383 template <return_value_policy policy = return_value_policy::automatic_reference>
1385 template <return_value_policy policy = return_value_policy::automatic_reference>
1394 #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1396 PYBIND11_DEPRECATED("Use reinterpret_borrow<" #Name ">() or reinterpret_steal<" #Name ">()") \
1397 Name(handle h, bool is_borrowed) \
1398 : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {} \
1399 Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {} \
1400 Name(handle h, stolen_t) : Parent(h, stolen_t{}) {} \
1401 PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
1402 bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \
1403 static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \
1404 template <typename Policy_> \
1405 Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) {}
1407 #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1408 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1411 Name(const object &o) \
1412 : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1414 throw ::pybind11::error_already_set(); \
1417 Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1419 throw ::pybind11::error_already_set(); \
1422 #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \
1423 PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1426 #define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \
1427 ::pybind11::type_error("Object of type '" \
1428 + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) \
1429 + "' is not an instance of '" #Name "'")
1431 #define PYBIND11_OBJECT(Name, Parent, CheckFun) \
1432 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1435 Name(const object &o) : Parent(o) { \
1436 if (m_ptr && !check_(m_ptr)) \
1437 throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1440 Name(object &&o) : Parent(std::move(o)) { \
1441 if (m_ptr && !check_(m_ptr)) \
1442 throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1445 #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
1446 PYBIND11_OBJECT(Name, Parent, CheckFun) \
1483 if (m_ptr && !
value.ptr()) {
1484 auto &
self =
const_cast<iterator &
>(*this);
1515 value = reinterpret_steal<object>(PyIter_Next(m_ptr));
1516 if (
value.ptr() ==
nullptr && PyErr_Occurred()) {
1539 template <
typename T>
1540 static handle handle_of();
1545 template <
typename T>
1566 if (PyErr_Occurred()) {
1578 if (PyErr_Occurred()) {
1588 #ifdef PYBIND11_HAS_STRING_VIEW
1594 # ifdef PYBIND11_HAS_U8STRING
1597 str(std::u8string_view
s) :
str(reinterpret_cast<const char *>(
s.
data()),
s.
size()) {}
1615 operator std::string()
const {
1616 object temp = *
this;
1617 if (PyUnicode_Check(m_ptr)) {
1618 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
1625 if (PyBytes_AsStringAndSize(temp.
ptr(), &
buffer, &length) != 0) {
1628 return std::string(
buffer, (
size_t) length);
1631 template <
typename... Args>
1633 return attr(
"format")(std::forward<Args>(
args)...);
1639 PyObject *str_value = PyObject_Str(op);
1650 #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
1689 operator std::string()
const {
return string_op<std::string>(); }
1691 #ifdef PYBIND11_HAS_STRING_VIEW
1701 operator std::string_view()
const {
return string_op<std::string_view>(); }
1704 template <
typename T>
1708 if (PyBytes_AsStringAndSize(m_ptr, &
buffer, &length) != 0) {
1711 return {
buffer,
static_cast<size_t>(length)};
1720 if (PyUnicode_Check(
s.ptr())) {
1721 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(
s.ptr()));
1728 if (PyBytes_AsStringAndSize(temp.
ptr(), &
buffer, &length) != 0) {
1735 m_ptr = obj.release().
ptr();
1741 if (PyBytes_AsStringAndSize(
b.ptr(), &
buffer, &length) != 0) {
1744 auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(
buffer, length));
1746 if (PyErr_Occurred()) {
1751 m_ptr = obj.release().
ptr();
1772 size_t size()
const {
return static_cast<size_t>(PyByteArray_Size(m_ptr)); }
1774 explicit operator std::string()
const {
1775 char *
buffer = PyByteArray_AS_STRING(m_ptr);
1777 return std::string(
buffer,
static_cast<size_t>(
size));
1806 operator bool()
const {
return (m_ptr !=
nullptr) && PyLong_AsLong(m_ptr) != 0; }
1811 const auto value = PyObject_IsTrue(op);
1824 template <
typename Un
signed>
1826 if (
sizeof(Unsigned) <=
sizeof(
unsigned long)) {
1827 unsigned long v = PyLong_AsUnsignedLong(o);
1828 return v == (
unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned)
v;
1830 unsigned long long v = PyLong_AsUnsignedLongLong(o);
1831 return v == (
unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned)
v;
1843 if (
sizeof(
T) <=
sizeof(
long)) {
1845 m_ptr = PyLong_FromLong((
long)
value);
1847 m_ptr = PyLong_FromUnsignedLong((
unsigned long)
value);
1851 m_ptr = PyLong_FromLongLong((
long long)
value);
1853 m_ptr = PyLong_FromUnsignedLongLong((
unsigned long long)
value);
1863 operator T()
const {
1865 :
sizeof(
T) <=
sizeof(
long) ? (
T) PyLong_AsLong(m_ptr)
1887 operator float()
const {
return (
float) PyFloat_AsDouble(m_ptr); }
1889 operator double()
const {
return (
double) PyFloat_AsDouble(m_ptr); }
1896 :
object(PyWeakref_NewRef(obj.
ptr(), callback.ptr()), stolen_t{}) {
1898 if (PyErr_Occurred()) {
1906 static PyObject *
raw_weakref(PyObject *o) {
return PyWeakref_NewRef(o,
nullptr); }
1913 :
object(PySlice_New(start.ptr(), stop.ptr(),
step.ptr()),
stolen_t{}) {
1919 #ifdef PYBIND11_HAS_OPTIONAL
1920 slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t>
step)
1921 :
slice(index_to_object(start), index_to_object(stop), index_to_object(
step)) {}
1928 compute(
size_t length,
size_t *start,
size_t *stop,
size_t *
step,
size_t *slicelength)
const {
1939 return PySlice_GetIndicesEx(
1945 template <
typename T>
1955 capsule(PyObject *ptr,
bool is_borrowed)
1959 const char *
name =
nullptr,
1960 PyCapsule_Destructor destructor =
nullptr)
1961 :
object(PyCapsule_New(const_cast<void *>(
value),
name, destructor), stolen_t{}) {
1968 capsule(const
void *
value, PyCapsule_Destructor destructor)
1969 :
object(PyCapsule_New(const_cast<
void *>(
value),
nullptr, destructor), stolen_t{}) {
1976 capsule(
const void *
value,
void (*destructor)(
void *)) {
1977 initialize_with_void_ptr_destructor(
value,
nullptr, destructor);
1981 initialize_with_void_ptr_destructor(
value,
name, destructor);
1984 explicit capsule(
void (*destructor)()) {
1985 m_ptr = PyCapsule_New(
reinterpret_cast<void *
>(destructor),
nullptr, [](PyObject *o) {
1986 const char *
name = get_name_in_error_scope(o);
1987 auto destructor =
reinterpret_cast<void (*)()
>(PyCapsule_GetPointer(o,
name));
1988 if (destructor ==
nullptr) {
1999 template <
typename T>
2000 operator T *()
const {
2001 return get_pointer<T>();
2005 template <
typename T =
void>
2006 T *get_pointer()
const {
2008 T *
result =
static_cast<T *
>(PyCapsule_GetPointer(m_ptr,
name));
2016 void set_pointer(
const void *
value) {
2017 if (PyCapsule_SetPointer(m_ptr,
const_cast<void *
>(
value)) != 0) {
2022 const char *
name()
const {
2023 const char *
name = PyCapsule_GetName(m_ptr);
2024 if ((
name ==
nullptr) && PyErr_Occurred()) {
2031 void set_name(
const char *new_name) {
2032 if (PyCapsule_SetName(m_ptr, new_name) != 0) {
2038 static const char *get_name_in_error_scope(PyObject *o) {
2041 const char *
name = PyCapsule_GetName(o);
2042 if ((
name ==
nullptr) && PyErr_Occurred()) {
2044 PyErr_WriteUnraisable(o);
2050 void initialize_with_void_ptr_destructor(
const void *
value,
2052 void (*destructor)(
void *)) {
2053 m_ptr = PyCapsule_New(
const_cast<void *
>(
value),
name, [](PyObject *o) {
2056 auto destructor =
reinterpret_cast<void (*)(
void *)
>(PyCapsule_GetContext(o));
2057 if (destructor ==
nullptr && PyErr_Occurred()) {
2060 const char *
name = get_name_in_error_scope(o);
2061 void *ptr = PyCapsule_GetPointer(o,
name);
2062 if (ptr ==
nullptr) {
2066 if (destructor !=
nullptr) {
2071 if (!m_ptr || PyCapsule_SetContext(m_ptr,
reinterpret_cast<void *
>(destructor)) != 0) {
2080 template <
typename SzType =
ssize_t,
2088 size_t size()
const {
return (
size_t) PyTuple_Size(m_ptr); }
2093 return object::operator[](std::forward<T>(o));
2102 template <
typename... Args>
2104 return detail::all_of<detail::is_keyword_or_ds<Args>...>
::value;
2115 template <
typename... Args,
2122 size_t size()
const {
return (
size_t) PyDict_Size(m_ptr); }
2127 template <
typename T>
2139 if (PyDict_Check(op)) {
2142 return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op,
nullptr);
2160 return object::operator[](std::forward<T>(o));
2169 template <
typename SzType =
ssize_t,
2177 size_t size()
const {
return (
size_t) PyList_Size(m_ptr); }
2182 return object::operator[](std::forward<T>(o));
2186 template <
typename T>
2192 template <
typename IdxType,
2195 void insert(
const IdxType &index, ValType &&val) {
2196 if (PyList_Insert(m_ptr,
2204 if (PyList_SetSlice(m_ptr, 0, PyList_Size(m_ptr),
nullptr) == -1) {
2220 size_t size()
const {
return static_cast<size_t>(PySet_Size(m_ptr)); }
2222 template <
typename T>
2240 template <
typename T>
2257 if (fun && PyCFunction_Check(fun.
ptr())) {
2275 int flags = PyBUF_STRIDES | PyBUF_FORMAT;
2277 flags |= PyBUF_WRITABLE;
2279 auto *
view =
new Py_buffer();
2280 if (PyObject_GetBuffer(m_ptr,
view, flags) != 0) {
2303 pybind11_fail(
"Prohibited to create memoryview without Py_buffer");
2306 m_ptr = (
info.view()->obj) ? PyMemoryView_FromObject(
info.view()->obj)
2307 : PyMemoryView_FromBuffer(
info.view());
2309 pybind11_fail(
"Unable to create memoryview from buffer descriptor");
2340 detail::any_container<ssize_t> shape,
2341 detail::any_container<ssize_t>
strides,
2342 bool readonly =
false);
2347 detail::any_container<ssize_t> shape,
2348 detail::any_container<ssize_t>
strides) {
2350 const_cast<void *
>(ptr), itemsize,
format, std::move(shape), std::move(
strides),
true);
2353 template <
typename T>
2355 detail::any_container<ssize_t> shape,
2356 detail::any_container<ssize_t>
strides,
2357 bool readonly =
false) {
2366 template <
typename T>
2368 detail::any_container<ssize_t> shape,
2369 detail::any_container<ssize_t>
strides) {
2371 const_cast<T *
>(ptr), std::move(shape), std::move(
strides),
true);
2387 PyObject *ptr = PyMemoryView_FromMemory(
2388 reinterpret_cast<char *
>(mem),
size, (readonly) ? PyBUF_READ : PyBUF_WRITE);
2399 #ifdef PYBIND11_HAS_STRING_VIEW
2400 static memoryview from_memory(std::string_view mem) {
2401 return from_memory(
const_cast<char *
>(mem.data()),
static_cast<ssize_t>(mem.size()),
true);
2410 detail::any_container<ssize_t> shape,
2411 detail::any_container<ssize_t>
strides,
2413 size_t ndim = shape->size();
2415 pybind11_fail(
"memoryview: shape length doesn't match strides length");
2418 for (
size_t i = 0;
i < ndim; ++
i) {
2419 size *= (*shape)[
i];
2425 view.readonly =
static_cast<int>(readonly);
2426 view.itemsize = itemsize;
2428 view.ndim =
static_cast<int>(ndim);
2429 view.shape = shape->data();
2431 view.suboffsets =
nullptr;
2432 view.internal =
nullptr;
2433 PyObject *obj = PyMemoryView_FromBuffer(&
view);
2468 PyObject *str_value = PyObject_Repr(
h.ptr());
2472 return reinterpret_steal<str>(str_value);
2476 PyObject *
result = PyObject_GetIter(obj.
ptr());
2480 return reinterpret_steal<iterator>(
result);
2485 template <
typename D>
2487 return iter(derived());
2489 template <
typename D>
2493 template <
typename D>
2495 return {derived(), reinterpret_borrow<object>(
key)};
2497 template <
typename D>
2499 return {derived(), std::move(
key)};
2501 template <
typename D>
2505 template <
typename D>
2507 return {derived(), reinterpret_borrow<object>(
key)};
2509 template <
typename D>
2511 return {derived(), std::move(
key)};
2513 template <
typename D>
2515 return {derived(),
key};
2517 template <
typename D>
2521 template <
typename D>
2522 template <
typename T>
2524 return attr(
"__contains__")(std::forward<T>(item)).
template cast<bool>();
2527 template <
typename D>
2532 template <
typename D>
2534 return attr(
"__doc__");
2537 template <
typename D>
2542 template <
typename D>
2544 int rv = PyObject_RichCompareBool(derived().ptr(),
other.derived().ptr(),
value);
2551 #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
2552 template <typename D> \
2553 object object_api<D>::op() const { \
2554 object result = reinterpret_steal<object>(fn(derived().ptr())); \
2555 if (!result.ptr()) \
2556 throw error_already_set(); \
2560 #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
2561 template <typename D> \
2562 object object_api<D>::op(object_api const &other) const { \
2563 object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
2564 if (!result.ptr()) \
2565 throw error_already_set(); \
2569 #define PYBIND11_MATH_OPERATOR_BINARY_INPLACE(iop, fn) \
2570 template <typename D> \
2571 object object_api<D>::iop(object_api const &other) { \
2572 object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
2573 if (!result.ptr()) \
2574 throw error_already_set(); \
2599 #undef PYBIND11_MATH_OPERATOR_UNARY
2600 #undef PYBIND11_MATH_OPERATOR_BINARY
2601 #undef PYBIND11_MATH_OPERATOR_BINARY_INPLACE
friend bool operator>(const It &a, const It &b)
reference dereference() const
object operator+=(object_api const &other)
bool PyNone_Check(PyObject *o)
static object index_to_object(T index)
const Derived & derived() const
static type of(handle h)
Return a type object from a handle or an object.
str(const std::string &s)
RAII wrapper that temporarily clears any Python error state.
friend It operator-(const It &a, difference_type n)
bool matches(handle exc) const
std::shared_ptr< detail::error_fetch_and_normalize > m_fetched_error
#define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun)
object operator>>=(object_api const &other)
detail::list_iterator end() const
object(const object &o)
Copy constructor; always increases the reference count.
Annotation for function names.
friend bool operator<=(const It &a, const It &b)
void setattr(handle obj, handle name, handle value)
std::is_same< args_proxy, T > is_s_unpacking
bool isinstance_generic(handle obj, const std::type_info &tp)
static void set(handle obj, const IdxType &index, handle val)
typename Policy::pointer pointer
bool rich_compare(object_api const &other, int value) const
detail::item_accessor operator[](T &&o) const
const std::string & error_string() const
std::string format(const std::string &str, const std::vector< std::string > &find, const std::vector< std::string > &replace)
EIGEN_ALWAYS_INLINE DSizes< IndexType, NumDims > strides(const DSizes< IndexType, NumDims > &dimensions)
typename Policy::iterator_category iterator_category
Python's dictionary protocol permits this to be a forward iterator.
#define PYBIND11_OBJECT(Name, Parent, CheckFun)
bool is_cpp_function() const
It & operator+=(difference_type n)
object operator-=(object_api const &other)
object operator<<(object_api const &other) const
accessor< accessor_policies::list_item > list_accessor
bool is_none() const
Equivalent to obj is None in Python.
const object & trace() const
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
static object get(handle obj, const char *key)
ssize_t distance_to(const sequence_fast_readonly &b) const
std::string error_string()
static void set(handle obj, const char *key, handle val)
str format(Args &&...args) const
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)
bytes(const char *c, const SzType &n)
std::pair< handle, handle > value_type
detail::any_of< std::is_same< T, PyObject * >, std::is_same< T, PyObject *const >, std::is_same< T, std::nullptr_t > > is_pyobj_ptr_or_nullptr_t
typename deferred_type< T, Us... >::type deferred_t
bool equal(const dict_readonly &b) const
const handle & inc_ref() const &
accessor< accessor_policies::sequence_item > sequence_accessor
bool operator>=(object_api const &other) const
#define PYBIND11_STR_CHECK_FUN
PYBIND11_WARNING_PUSH PYBIND11_WARNING_POP
std::string m_lazy_error_string
#define PYBIND11_NAMESPACE_END(name)
bool hasattr(handle obj, handle name)
#define PYBIND11_BYTES_FROM_STRING
pybind11::str str() const
bool operator<(object_api const &other) const
Quick proxy class needed to implement operator-> for iterators which can't return pointers.
typename Policy::reference reference
bool contains(T &&item) const
Check if the given item is contained within this object, i.e. item in obj.
object operator*=(object_api const &other)
object operator&(object_api const &other) const
detail::dict_iterator end() const
slice(ssize_t start_, ssize_t stop_, ssize_t step_)
object getattr(handle obj, handle name)
Eigen::Triplet< double > T
object operator()(Args &&...args) const
object operator^=(object_api const &other)
bool not_equal(object_api const &other) const
PyObject * dict_getitemstring(PyObject *v, const char *key)
std::random_access_iterator_tag iterator_category
static memoryview from_buffer(const T *ptr, detail::any_container< ssize_t > shape, detail::any_container< ssize_t > strides)
#define PYBIND11_NAMESPACE_BEGIN(name)
static memoryview from_memory(const void *mem, ssize_t size)
bool isinstance< handle >(handle)=delete
Lightweight iterator policy using just a simple pointer: see PySequence_Fast_ITEMS
#define PYBIND11_FROM_STRING
object operator/(object_api const &other) const
PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()") object(handle h
#define PYBIND11_LONG_AS_LONGLONG(o)
Unsigned as_unsigned(PyObject *o)
friend bool operator==(const It &a, const It &b)
bool equal(object_api const &other) const
Equivalent to obj == other in Python.
bool equal(const sequence_fast_readonly &b) const
bool operator>(object_api const &other) const
It & operator-=(difference_type n)
~object()
Destructor; automatically calls handle::dec_ref()
static PyObject * raw_bool(PyObject *op)
Return the truth value of an object – always returns a new reference.
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy y set format x g set format y g set format x2 g set format y2 g set format z g set angles radians set nogrid set key title set key left top Right noreverse box linetype linewidth samplen spacing width set nolabel set noarrow set nologscale set logscale x set set pointsize set encoding default set nopolar set noparametric set view
bool m_lazy_error_string_completed
const object & value() const
static object get(handle obj, handle key)
Annotation for documentation.
void discard_as_unraisable(const char *err_context)
STL iterator template used for tuple, list, sequence and dict.
detail::tuple_iterator begin() const
friend bool operator>=(const It &a, const It &b)
#define PYBIND11_LONG_CHECK(o)
static void set(handle obj, const IdxType &index, handle val)
const value_type reference
void raise_from(PyObject *type, const char *message)
object operator|=(object_api const &other)
bool isinstance(handle obj)
bytearray(const char *c, const SzType &n)
detail::sequence_iterator begin() const
generic_iterator(handle seq, ssize_t index)
accessor< accessor_policies::tuple_item > tuple_accessor
detail::item_accessor operator[](T &&o) const
static handle handle_of()
T reinterpret_borrow(handle h)
void delattr(handle obj, handle name)
error_fetch_and_normalize(const char *called)
std::input_iterator_tag iterator_category
object operator<<=(object_api const &other)
bool PyStaticMethod_Check(PyObject *o)
constexpr bool args_are_all_keyword_or_ds()
kwargs_proxy operator*() const
static std::size_t inc_ref_counter(std::size_t add)
#define PYBIND11_EXPORT_EXCEPTION
static memoryview from_buffer(const void *ptr, ssize_t itemsize, const char *format, detail::any_container< ssize_t > shape, detail::any_container< ssize_t > strides)
static memoryview from_buffer(T *ptr, detail::any_container< ssize_t > shape, detail::any_container< ssize_t > strides, bool readonly=false)
handle get_function(handle value)
graph add(PriorFactor< Pose2 >(1, priorMean, priorNoise))
friend bool operator!=(const iterator &a, const iterator &b)
bool contains(T &&val) const
void insert(const IdxType &index, ValType &&val)
object operator>>(object_api const &other) const
bool compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const
def step(data, isam, result, truth, currPoseIndex, isamArgs=())
sequence_slow_readwrite(handle obj, ssize_t index)
arrow_proxy(T &&value) noexcept
friend bool operator<(const It &a, const It &b)
auto object_or_cast(T &&o) -> decltype(std::forward< T >(o))
PyObject * dict_getitemstringref(PyObject *v, const char *key)
detail::item_accessor operator[](T &&o) const
std::is_same< kwargs_proxy, T > is_ds_unpacking
bool is(object_api const &other) const
Equivalent to obj is other in Python.
A small structure to hold a non zero as a triplet (i,j,value).
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
static std::size_t inc_ref_counter()
PyObject * dict_getitem(PyObject *v, PyObject *key)
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
str(const char *c, const SzType &n)
void set_error(const handle &type, const char *message)
detail::tuple_accessor operator[](size_t index) const
object(object &&other) noexcept
Move constructor; steals the object from other and preserves its reference count.
pointer operator->() const
#define PYBIND11_INPLACE_OP(iop)
#define PYBIND11_MATH_OPERATOR_UNARY(op, fn)
std::is_base_of< arg, T > is_keyword
Python argument categories (using PEP 448 terms)
static void set(handle obj, const IdxType &index, handle val)
const gtsam::Symbol key('X', 0)
void set(Container &c, Position position, const Value &value)
bytearray(const std::string &s)
object & operator=(object &&other) noexcept
Helper class which collects positional, keyword, * and ** arguments for a Python function call.
handle(T &obj)
Enable implicit conversion through T::operator PyObject *().
bool isinstance< object >(handle obj)
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
generic_iterator< iterator_policies::sequence_fast_readonly > tuple_iterator
detail::tuple_iterator end() const
pointer operator->() const
object operator/=(object_api const &other)
std::forward_iterator_tag iterator_category
bool contains(T &&key) const
PyObject * ptr() const
Return the underlying PyObject * pointer.
static object get(handle obj, const IdxType &index)
friend It operator+(difference_type n, const It &b)
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)
dict_readonly(handle obj, ssize_t pos)
std::random_access_iterator_tag iterator_category
friend bool operator==(const iterator &a, const iterator &b)
const object & type() const
PYBIND11_WARNING_PUSH PYBIND11_WARNING_DISABLE_MSVC(5054) PYBIND11_WARNING_POP static_assert(EIGEN_VERSION_AT_LEAST(3
detail::sequence_accessor operator[](size_t index) const
handle()=default
The default constructor creates a handle with a nullptr-valued pointer.
ssize_t ssize_t_cast(const IntType &val)
static object get(handle obj, handle key)
iterator iter(handle obj)
object(handle h, borrowed_t)
void throw_gilstate_error(const std::string &function_name) const
accessor< accessor_policies::generic_item > item_accessor
detail::dict_iterator begin() const
std::string format_value_and_trace() const
Information record describing a Python buffer object.
EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE std::size_t size()
sequence_fast_readonly(handle obj, ssize_t n)
static object get(handle obj, const IdxType &index)
typename Policy::value_type value_type
Full read and write access using the sequence protocol: see detail::sequence_accessor
reference operator*() const
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
detail::list_accessor operator[](size_t index) const
static memoryview from_memory(void *mem, ssize_t size, bool readonly=false)
str_attr_accessor doc() const
Get or set the object's docstring, i.e. obj.__doc__.
Array< int, Dynamic, 1 > v
const handle & dec_ref() const &
object(handle h, stolen_t)
bool operator<=(object_api const &other) const
generic_iterator< iterator_policies::sequence_fast_readonly > list_iterator
bool PyIterable_Check(PyObject *obj)
bool equal(const sequence_slow_readwrite &b) const
object operator&=(object_api const &other)
static PyObject * raw_str(PyObject *op)
Return string representation – always returns a new reference, even if already a str.
#define PYBIND11_MATH_OPERATOR_BINARY(op, fn)
item_accessor operator[](handle key) const
static void set(handle obj, handle key, handle val)
#define PYBIND11_MATH_OPERATOR_BINARY_INPLACE(iop, fn)
obj_attr_accessor attr(handle key) const
void discard_as_unraisable(object err_context)
object & operator=(const object &other)
size_t len_hint(handle h)
static PyObject * raw_weakref(PyObject *o)
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.
PYBIND11_DEPRECATED("make_simple_namespace should be replaced with " "py::module_::import(\"types\").attr(\"SimpleNamespace\") ") object make_simple_namespace(Args &&...args_)
object operator|(object_api const &other) const
Tag and check to identify a class which implements the Python object API.
object operator+(object_api const &other) const
bool matches(handle exc) const
generic_iterator< iterator_policies::sequence_slow_readwrite > sequence_iterator
#define PYBIND11_BYTES_FROM_STRING_AND_SIZE
friend bool operator!=(const It &a, const It &b)
object operator^(object_api const &other) const
ssize_t ref_count() const
Return the object's current reference count.
reference dereference() const
T reinterpret_steal(handle h)
args_proxy operator*() const
generic_iterator< iterator_policies::dict_readonly > dict_iterator
bool PyEllipsis_Check(PyObject *o)
#define PYBIND11_SLICE_OBJECT
internal::enable_if<!(symbolic::is_symbolic< FirstType >::value||symbolic::is_symbolic< LastType >::value), ArithmeticSequence< typename internal::cleanup_index_type< FirstType >::type, Index > >::type seq(FirstType f, LastType l)
#define PYBIND11_BYTES_CHECK
Container::iterator get(Container &c, Position position)
bool compute(ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
static object get(handle obj, const IdxType &index)
reference operator[](difference_type n) const
friend difference_type operator-(const It &a, const It &b)
ssize_t distance_to(const sequence_slow_readwrite &b) const
const char * obj_class_name(PyObject *obj)
friend It operator+(const It &a, difference_type n)
reference dereference() const
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
reference operator*() const
PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)") object call(Args &&...args) const
Vector3_ operator*(const Double_ &s, const Vector3_ &v)
static void set(handle obj, handle key, handle val)
static iterator sentinel()
bytes(const std::string &s)
iterator end() const
Return a sentinel which ends iteration.
detail::sequence_iterator end() const
detail::list_iterator begin() const
gtsam
Author(s):
autogenerated on Fri Nov 1 2024 03:34:49