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>
1326 #if !defined(PYPY_VERSION)
1338 PyObject *
iter = PyObject_GetIter(obj);
1350 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
1351 inline bool PyUnicode_Check_Permissive(PyObject *o) {
1354 # define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive
1356 # define PYBIND11_STR_CHECK_FUN PyUnicode_Check
1373 template <
typename T>
1375 template <
typename T>
1377 template <
typename T>
1379 template <
typename T>
1381 template <
typename T>
1385 template <return_value_policy policy = return_value_policy::automatic_reference>
1387 template <return_value_policy policy = return_value_policy::automatic_reference>
1396 #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1398 PYBIND11_DEPRECATED("Use reinterpret_borrow<" #Name ">() or reinterpret_steal<" #Name ">()") \
1399 Name(handle h, bool is_borrowed) \
1400 : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {} \
1401 Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {} \
1402 Name(handle h, stolen_t) : Parent(h, stolen_t{}) {} \
1403 PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
1404 bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \
1405 static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \
1406 template <typename Policy_> \
1407 Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) {}
1409 #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1410 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1413 Name(const object &o) \
1414 : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1416 throw ::pybind11::error_already_set(); \
1419 Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1421 throw ::pybind11::error_already_set(); \
1424 #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \
1425 PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1428 #define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \
1429 ::pybind11::type_error("Object of type '" \
1430 + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) \
1431 + "' is not an instance of '" #Name "'")
1433 #define PYBIND11_OBJECT(Name, Parent, CheckFun) \
1434 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1437 Name(const object &o) : Parent(o) { \
1438 if (m_ptr && !check_(m_ptr)) \
1439 throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1442 Name(object &&o) : Parent(std::move(o)) { \
1443 if (m_ptr && !check_(m_ptr)) \
1444 throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1447 #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
1448 PYBIND11_OBJECT(Name, Parent, CheckFun) \
1485 if (m_ptr && !
value.ptr()) {
1486 auto &
self =
const_cast<iterator &
>(*this);
1517 value = reinterpret_steal<object>(PyIter_Next(m_ptr));
1518 if (
value.ptr() ==
nullptr && PyErr_Occurred()) {
1541 template <
typename T>
1542 static handle handle_of();
1547 template <
typename T>
1568 if (PyErr_Occurred()) {
1580 if (PyErr_Occurred()) {
1590 #ifdef PYBIND11_HAS_STRING_VIEW
1596 # ifdef PYBIND11_HAS_U8STRING
1599 str(std::u8string_view
s) :
str(reinterpret_cast<const char *>(
s.
data()),
s.
size()) {}
1617 operator std::string()
const {
1618 object temp = *
this;
1619 if (PyUnicode_Check(m_ptr)) {
1620 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
1627 if (PyBytes_AsStringAndSize(temp.
ptr(), &
buffer, &length) != 0) {
1630 return std::string(
buffer, (
size_t) length);
1633 template <
typename... Args>
1635 return attr(
"format")(std::forward<Args>(
args)...);
1641 PyObject *str_value = PyObject_Str(op);
1652 #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
1691 operator std::string()
const {
return string_op<std::string>(); }
1693 #ifdef PYBIND11_HAS_STRING_VIEW
1703 operator std::string_view()
const {
return string_op<std::string_view>(); }
1706 template <
typename T>
1710 if (PyBytes_AsStringAndSize(m_ptr, &
buffer, &length) != 0) {
1713 return {
buffer,
static_cast<size_t>(length)};
1722 if (PyUnicode_Check(
s.ptr())) {
1723 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(
s.ptr()));
1730 if (PyBytes_AsStringAndSize(temp.
ptr(), &
buffer, &length) != 0) {
1737 m_ptr = obj.release().
ptr();
1743 if (PyBytes_AsStringAndSize(
b.ptr(), &
buffer, &length) != 0) {
1746 auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(
buffer, length));
1748 if (PyErr_Occurred()) {
1753 m_ptr = obj.release().
ptr();
1774 size_t size()
const {
return static_cast<size_t>(PyByteArray_Size(m_ptr)); }
1776 explicit operator std::string()
const {
1777 char *
buffer = PyByteArray_AS_STRING(m_ptr);
1779 return std::string(
buffer,
static_cast<size_t>(
size));
1808 operator bool()
const {
return (m_ptr !=
nullptr) && PyLong_AsLong(m_ptr) != 0; }
1813 const auto value = PyObject_IsTrue(op);
1826 template <
typename Un
signed>
1828 if (
sizeof(Unsigned) <=
sizeof(
unsigned long)) {
1829 unsigned long v = PyLong_AsUnsignedLong(o);
1830 return v == (
unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned)
v;
1832 unsigned long long v = PyLong_AsUnsignedLongLong(o);
1833 return v == (
unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned)
v;
1845 if (
sizeof(
T) <=
sizeof(
long)) {
1847 m_ptr = PyLong_FromLong((
long)
value);
1849 m_ptr = PyLong_FromUnsignedLong((
unsigned long)
value);
1853 m_ptr = PyLong_FromLongLong((
long long)
value);
1855 m_ptr = PyLong_FromUnsignedLongLong((
unsigned long long)
value);
1865 operator T()
const {
1867 :
sizeof(
T) <=
sizeof(
long) ? (
T) PyLong_AsLong(m_ptr)
1889 operator float()
const {
return (
float) PyFloat_AsDouble(m_ptr); }
1891 operator double()
const {
return (
double) PyFloat_AsDouble(m_ptr); }
1898 :
object(PyWeakref_NewRef(obj.
ptr(), callback.ptr()), stolen_t{}) {
1900 if (PyErr_Occurred()) {
1908 static PyObject *
raw_weakref(PyObject *o) {
return PyWeakref_NewRef(o,
nullptr); }
1915 :
object(PySlice_New(start.ptr(), stop.ptr(),
step.ptr()),
stolen_t{}) {
1921 #ifdef PYBIND11_HAS_OPTIONAL
1922 slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t>
step)
1923 :
slice(index_to_object(start), index_to_object(stop), index_to_object(
step)) {}
1930 compute(
size_t length,
size_t *start,
size_t *stop,
size_t *
step,
size_t *slicelength)
const {
1941 return PySlice_GetIndicesEx(
1947 template <
typename T>
1957 capsule(PyObject *ptr,
bool is_borrowed)
1961 const char *
name =
nullptr,
1962 PyCapsule_Destructor destructor =
nullptr)
1963 :
object(PyCapsule_New(const_cast<void *>(
value),
name, destructor), stolen_t{}) {
1970 capsule(const
void *
value, PyCapsule_Destructor destructor)
1971 :
object(PyCapsule_New(const_cast<
void *>(
value),
nullptr, destructor), stolen_t{}) {
1978 capsule(
const void *
value,
void (*destructor)(
void *)) {
1979 initialize_with_void_ptr_destructor(
value,
nullptr, destructor);
1983 initialize_with_void_ptr_destructor(
value,
name, destructor);
1986 explicit capsule(
void (*destructor)()) {
1987 m_ptr = PyCapsule_New(
reinterpret_cast<void *
>(destructor),
nullptr, [](PyObject *o) {
1988 const char *
name = get_name_in_error_scope(o);
1989 auto destructor =
reinterpret_cast<void (*)()
>(PyCapsule_GetPointer(o,
name));
1990 if (destructor ==
nullptr) {
2001 template <
typename T>
2002 operator T *()
const {
2003 return get_pointer<T>();
2007 template <
typename T =
void>
2008 T *get_pointer()
const {
2010 T *
result =
static_cast<T *
>(PyCapsule_GetPointer(m_ptr,
name));
2018 void set_pointer(
const void *
value) {
2019 if (PyCapsule_SetPointer(m_ptr,
const_cast<void *
>(
value)) != 0) {
2024 const char *
name()
const {
2025 const char *
name = PyCapsule_GetName(m_ptr);
2026 if ((
name ==
nullptr) && PyErr_Occurred()) {
2033 void set_name(
const char *new_name) {
2034 if (PyCapsule_SetName(m_ptr, new_name) != 0) {
2040 static const char *get_name_in_error_scope(PyObject *o) {
2043 const char *
name = PyCapsule_GetName(o);
2044 if ((
name ==
nullptr) && PyErr_Occurred()) {
2046 PyErr_WriteUnraisable(o);
2052 void initialize_with_void_ptr_destructor(
const void *
value,
2054 void (*destructor)(
void *)) {
2055 m_ptr = PyCapsule_New(
const_cast<void *
>(
value),
name, [](PyObject *o) {
2058 auto destructor =
reinterpret_cast<void (*)(
void *)
>(PyCapsule_GetContext(o));
2059 if (destructor ==
nullptr && PyErr_Occurred()) {
2062 const char *
name = get_name_in_error_scope(o);
2063 void *ptr = PyCapsule_GetPointer(o,
name);
2064 if (ptr ==
nullptr) {
2068 if (destructor !=
nullptr) {
2073 if (!m_ptr || PyCapsule_SetContext(m_ptr,
reinterpret_cast<void *
>(destructor)) != 0) {
2082 template <
typename SzType =
ssize_t,
2090 size_t size()
const {
return (
size_t) PyTuple_Size(m_ptr); }
2095 return object::operator[](std::forward<T>(o));
2104 template <
typename... Args>
2106 return detail::all_of<detail::is_keyword_or_ds<Args>...>
::value;
2117 template <
typename... Args,
2124 size_t size()
const {
return (
size_t) PyDict_Size(m_ptr); }
2129 template <
typename T>
2141 if (PyDict_Check(op)) {
2144 return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op,
nullptr);
2162 return object::operator[](std::forward<T>(o));
2171 template <
typename SzType =
ssize_t,
2179 size_t size()
const {
return (
size_t) PyList_Size(m_ptr); }
2184 return object::operator[](std::forward<T>(o));
2188 template <
typename T>
2194 template <
typename IdxType,
2197 void insert(
const IdxType &index, ValType &&val) {
2198 if (PyList_Insert(m_ptr,
2206 if (PyList_SetSlice(m_ptr, 0, PyList_Size(m_ptr),
nullptr) == -1) {
2222 size_t size()
const {
return static_cast<size_t>(PySet_Size(m_ptr)); }
2224 template <
typename T>
2242 template <
typename T>
2259 if (fun && PyCFunction_Check(fun.
ptr())) {
2277 int flags = PyBUF_STRIDES | PyBUF_FORMAT;
2279 flags |= PyBUF_WRITABLE;
2281 auto *
view =
new Py_buffer();
2282 if (PyObject_GetBuffer(m_ptr,
view, flags) != 0) {
2305 pybind11_fail(
"Prohibited to create memoryview without Py_buffer");
2308 m_ptr = (
info.view()->obj) ? PyMemoryView_FromObject(
info.view()->obj)
2309 : PyMemoryView_FromBuffer(
info.view());
2311 pybind11_fail(
"Unable to create memoryview from buffer descriptor");
2342 detail::any_container<ssize_t> shape,
2343 detail::any_container<ssize_t>
strides,
2344 bool readonly =
false);
2349 detail::any_container<ssize_t> shape,
2350 detail::any_container<ssize_t>
strides) {
2352 const_cast<void *
>(ptr), itemsize,
format, std::move(shape), std::move(
strides),
true);
2355 template <
typename T>
2357 detail::any_container<ssize_t> shape,
2358 detail::any_container<ssize_t>
strides,
2359 bool readonly =
false) {
2368 template <
typename T>
2370 detail::any_container<ssize_t> shape,
2371 detail::any_container<ssize_t>
strides) {
2373 const_cast<T *
>(ptr), std::move(shape), std::move(
strides),
true);
2389 PyObject *ptr = PyMemoryView_FromMemory(
2390 reinterpret_cast<char *
>(mem),
size, (readonly) ? PyBUF_READ : PyBUF_WRITE);
2401 #ifdef PYBIND11_HAS_STRING_VIEW
2402 static memoryview from_memory(std::string_view mem) {
2403 return from_memory(
const_cast<char *
>(mem.data()),
static_cast<ssize_t>(mem.size()),
true);
2412 detail::any_container<ssize_t> shape,
2413 detail::any_container<ssize_t>
strides,
2415 size_t ndim = shape->size();
2417 pybind11_fail(
"memoryview: shape length doesn't match strides length");
2420 for (
size_t i = 0;
i < ndim; ++
i) {
2421 size *= (*shape)[
i];
2427 view.readonly =
static_cast<int>(readonly);
2428 view.itemsize = itemsize;
2430 view.ndim =
static_cast<int>(ndim);
2431 view.shape = shape->data();
2433 view.suboffsets =
nullptr;
2434 view.internal =
nullptr;
2435 PyObject *obj = PyMemoryView_FromBuffer(&
view);
2470 PyObject *str_value = PyObject_Repr(
h.ptr());
2474 return reinterpret_steal<str>(str_value);
2478 PyObject *
result = PyObject_GetIter(obj.
ptr());
2482 return reinterpret_steal<iterator>(
result);
2487 template <
typename D>
2489 return iter(derived());
2491 template <
typename D>
2495 template <
typename D>
2497 return {derived(), reinterpret_borrow<object>(
key)};
2499 template <
typename D>
2501 return {derived(), std::move(
key)};
2503 template <
typename D>
2507 template <
typename D>
2509 return {derived(), reinterpret_borrow<object>(
key)};
2511 template <
typename D>
2513 return {derived(), std::move(
key)};
2515 template <
typename D>
2517 return {derived(),
key};
2519 template <
typename D>
2523 template <
typename D>
2524 template <
typename T>
2526 return attr(
"__contains__")(std::forward<T>(item)).
template cast<bool>();
2529 template <
typename D>
2534 template <
typename D>
2536 return attr(
"__doc__");
2539 template <
typename D>
2544 template <
typename D>
2546 int rv = PyObject_RichCompareBool(derived().ptr(),
other.derived().ptr(),
value);
2553 #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
2554 template <typename D> \
2555 object object_api<D>::op() const { \
2556 object result = reinterpret_steal<object>(fn(derived().ptr())); \
2557 if (!result.ptr()) \
2558 throw error_already_set(); \
2562 #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
2563 template <typename D> \
2564 object object_api<D>::op(object_api const &other) const { \
2565 object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
2566 if (!result.ptr()) \
2567 throw error_already_set(); \
2571 #define PYBIND11_MATH_OPERATOR_BINARY_INPLACE(iop, fn) \
2572 template <typename D> \
2573 object object_api<D>::iop(object_api const &other) { \
2574 object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
2575 if (!result.ptr()) \
2576 throw error_already_set(); \
2601 #undef PYBIND11_MATH_OPERATOR_UNARY
2602 #undef PYBIND11_MATH_OPERATOR_BINARY
2603 #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 Thu Apr 10 2025 03:03:00