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>
72 using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
78 template <
typename Derived>
80 const Derived &
derived()
const {
return static_cast<const Derived &
>(*this); }
124 template <
typename T>
195 template <
typename T>
197 std::is_same<T, PyObject *const>,
198 std::is_same<T, std::nullptr_t>>;
202 #if !defined(PYBIND11_HANDLE_REF_DEBUG) && !defined(NDEBUG)
203 # define PYBIND11_HANDLE_REF_DEBUG
217 class handle :
public detail::object_api<handle> {
224 template <
typename T,
232 detail::enable_if_t<detail::all_of<detail::none_of<std::is_base_of<handle, T>,
233 detail::is_pyobj_ptr_or_nullptr_t<T>>,
234 std::is_convertible<T, PyObject *>>
::value,
250 #ifdef PYBIND11_HANDLE_REF_DEBUG
253 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
254 if (
m_ptr !=
nullptr && !PyGILState_Check()) {
268 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
269 if (
m_ptr !=
nullptr && !PyGILState_Check()) {
281 template <
typename T>
284 explicit operator bool()
const {
return m_ptr !=
nullptr; }
300 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
304 "%s is being called while the GIL is either not held or invalid. Please see "
305 "https://pybind11.readthedocs.io/en/stable/advanced/"
306 "misc.html#common-sources-of-global-interpreter-lock-errors for debugging advice.\n"
307 "If you are convinced there is no bug in your code, you can #define "
308 "PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF"
309 "to disable this check. In that case you have to ensure this #define is consistently "
310 "used for all translation units linked into a given pybind11 extension, otherwise "
311 "there will be ODR violations.",
312 function_name.c_str());
314 if (Py_TYPE(
m_ptr)->tp_name !=
nullptr) {
316 "The failing %s call was triggered on a %s object.\n",
317 function_name.c_str(),
318 Py_TYPE(
m_ptr)->tp_name);
321 throw std::runtime_error(function_name +
" PyGILState_Check() failure.");
325 #ifdef PYBIND11_HANDLE_REF_DEBUG
369 PyObject *tmp =
m_ptr;
376 if (!this->is(
other)) {
388 if (
this != &
other) {
391 other.m_ptr =
nullptr;
397 #define PYBIND11_INPLACE_OP(iop) \
398 object iop(object_api const &other) { return operator=(handle::iop(other)); }
409 #undef PYBIND11_INPLACE_OP
412 template <
typename T>
415 template <typename
T>
424 template <
typename T>
426 template <
typename T>
449 template <
typename T>
462 template <
typename T>
471 if (PyType_Check(obj)) {
472 return reinterpret_cast<PyTypeObject *
>(obj)->tp_name;
474 return Py_TYPE(obj)->tp_name;
502 "Python error indicator not set.");
505 if (exc_type_name_orig ==
nullptr) {
507 +
" failed to obtain the name "
508 "of the original active exception type.");
511 #if PY_VERSION_HEX >= 0x030C0000
515 if (PyObject_HasAttrString(
m_value.
ptr(),
"__notes__")) {
524 +
" failed to normalize the "
525 "active exception.");
528 if (exc_type_name_norm ==
nullptr) {
530 +
" failed to obtain the name "
531 "of the normalized active exception type.");
533 # if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x07030a00
540 std::string
msg = std::string(called)
541 +
": MISMATCH of original and normalized "
542 "active exception types: ";
545 msg +=
" REPLACED BY ";
546 msg += exc_type_name_norm;
559 std::string message_error_string;
561 auto value_str = reinterpret_steal<object>(PyObject_Str(
m_value.
ptr()));
562 constexpr
const char *message_unavailable_exc
563 =
"<MESSAGE UNAVAILABLE DUE TO ANOTHER EXCEPTION>";
566 result = message_unavailable_exc;
570 auto value_bytes = reinterpret_steal<object>(
571 PyUnicode_AsEncodedString(value_str.ptr(),
"utf-8",
"backslashreplace"));
574 result = message_unavailable_exc;
577 Py_ssize_t length = 0;
578 if (PyBytes_AsStringAndSize(value_bytes.ptr(), &
buffer, &length) == -1) {
580 result = message_unavailable_exc;
586 #if PY_VERSION_HEX >= 0x030B0000
588 = reinterpret_steal<object>(PyObject_GetAttrString(
m_value.
ptr(),
"__notes__"));
592 auto len_notes = PyList_Size(notes.ptr());
596 result +=
"\n__notes__ (len=" + std::to_string(len_notes) +
"):";
598 PyObject *note = PyList_GET_ITEM(notes.ptr(),
i);
599 auto note_bytes = reinterpret_steal<object>(
600 PyUnicode_AsEncodedString(note,
"utf-8",
"backslashreplace"));
602 result +=
"\nFAILURE obtaining __notes__[" + std::to_string(
i)
606 Py_ssize_t length = 0;
607 if (PyBytes_AsStringAndSize(note_bytes.ptr(), &
buffer, &length)
609 result +=
"\nFAILURE formatting __notes__[" + std::to_string(
i)
621 result =
"<MESSAGE UNAVAILABLE>";
624 result =
"<EMPTY MESSAGE>";
627 bool have_trace =
false;
629 #if !defined(PYPY_VERSION)
630 auto *tb =
reinterpret_cast<PyTracebackObject *
>(
m_trace.
ptr());
633 while (tb->tb_next) {
637 PyFrameObject *frame = tb->tb_frame;
641 # if PY_VERSION_HEX >= 0x030900B1
642 PyCodeObject *f_code = PyFrame_GetCode(frame);
644 PyCodeObject *f_code = frame->f_code;
647 int lineno = PyFrame_GetLineNumber(frame);
651 result += std::to_string(lineno);
656 # if PY_VERSION_HEX >= 0x030900B1
657 auto *b_frame = PyFrame_GetBack(frame);
659 auto *b_frame = frame->f_back;
670 if (!message_error_string.empty()) {
674 result +=
"\nMESSAGE UNAVAILABLE DUE TO EXCEPTION: " + message_error_string;
690 pybind11_fail(
"Internal error: pybind11::detail::error_fetch_and_normalize::restore() "
691 "called a second time. ORIGINAL ERROR: "
699 return (PyErr_GivenExceptionMatches(
m_type.
ptr(), exc.
ptr()) != 0);
727 : m_fetched_error{
new detail::error_fetch_and_normalize(
"pybind11::error_already_set"),
728 m_fetched_error_deleter} {}
733 const char *what() const noexcept override;
740 void restore() { m_fetched_error->restore(); }
748 PyErr_WriteUnraisable(err_context.
ptr());
766 const object &
type()
const {
return m_fetched_error->m_type; }
767 const object &
value()
const {
return m_fetched_error->m_value; }
768 const object &
trace()
const {
return m_fetched_error->m_trace; }
775 static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr);
784 PyObject *exc =
nullptr, *val =
nullptr, *val2 =
nullptr, *tb =
nullptr;
786 assert(PyErr_Occurred());
787 PyErr_Fetch(&exc, &val, &tb);
788 PyErr_NormalizeException(&exc, &val, &tb);
790 PyException_SetTraceback(val, tb);
794 assert(!PyErr_Occurred());
796 PyErr_SetString(
type, message);
798 PyErr_Fetch(&exc, &val2, &tb);
799 PyErr_NormalizeException(&exc, &val2, &tb);
801 PyException_SetCause(val2, val);
802 PyException_SetContext(val2, val);
803 PyErr_Restore(exc, val2, tb);
826 return T::check_(obj);
838 return obj.
ptr() !=
nullptr;
854 return PyObject_HasAttr(obj.
ptr(),
name.ptr()) == 1;
858 return PyObject_HasAttrString(obj.
ptr(),
name) == 1;
862 if (PyObject_DelAttr(obj.
ptr(),
name.ptr()) != 0) {
868 if (PyObject_DelAttrString(obj.
ptr(),
name) != 0) {
878 return reinterpret_steal<object>(
result);
886 return reinterpret_steal<object>(
result);
890 if (PyObject *
result = PyObject_GetAttr(obj.
ptr(),
name.ptr())) {
891 return reinterpret_steal<object>(
result);
894 return reinterpret_borrow<object>(default_);
898 if (PyObject *
result = PyObject_GetAttrString(obj.
ptr(),
name)) {
899 return reinterpret_steal<object>(
result);
902 return reinterpret_borrow<object>(default_);
906 if (PyObject_SetAttr(obj.
ptr(),
name.ptr(),
value.ptr()) != 0) {
912 if (PyObject_SetAttrString(obj.
ptr(),
name,
value.ptr()) != 0) {
918 auto h = PyObject_Hash(obj.
ptr());
930 if (PyInstanceMethod_Check(
value.ptr())) {
931 value = PyInstanceMethod_GET_FUNCTION(
value.ptr());
932 }
else if (PyMethod_Check(
value.ptr())) {
944 PyObject *kv =
nullptr, *rv =
nullptr;
945 kv = PyUnicode_FromString(
key);
950 rv = PyDict_GetItemWithError(
v, kv);
952 if (rv ==
nullptr && PyErr_Occurred()) {
959 PyObject *rv = PyDict_GetItemWithError(
v,
key);
960 if (rv ==
nullptr && PyErr_Occurred()) {
971 return std::forward<T>(o);
979 PYBIND11_WARNING_PUSH
981 template <typename Policy>
983 using key_type =
typename Policy::key_type;
992 void operator=(const
accessor &
a) && { std::move(*this).operator=(
handle(
a)); }
995 template <
typename T>
996 void operator=(
T &&
value) && {
999 template <
typename T>
1000 void operator=(
T &&
value) & {
1004 template <
typename T = Policy>
1006 "Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
1013 template <
typename T = Policy>
1014 PYBIND11_DEPRECATED(
"Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
1017 return obj.contains(
key);
1021 operator object()
const {
return get_cache(); }
1022 PyObject *ptr()
const {
return get_cache().ptr(); }
1023 template <
typename T>
1025 return get_cache().template cast<T>();
1029 static object ensure_object(
object &&o) {
return std::move(o); }
1030 static object ensure_object(
handle h) {
return reinterpret_borrow<object>(
h); }
1032 object &get_cache()
const {
1042 mutable object cache;
1063 PyObject *
result = PyObject_GetItem(obj.
ptr(),
key.ptr());
1067 return reinterpret_steal<object>(
result);
1071 if (PyObject_SetItem(obj.
ptr(),
key.ptr(), val.
ptr()) != 0) {
1086 return reinterpret_steal<object>(
result);
1107 return reinterpret_borrow<object>(
result);
1128 return reinterpret_borrow<object>(
result);
1141 template <
typename Policy>
1163 Policy::increment();
1168 Policy::increment();
1172 Policy::decrement();
1177 Policy::decrement();
1185 Policy::advance(-
n);
1210 template <
typename T>
1290 #if !defined(PYPY_VERSION)
1302 PyObject *
iter = PyObject_GetIter(obj);
1314 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
1315 inline bool PyUnicode_Check_Permissive(PyObject *o) {
1318 # define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive
1320 # define PYBIND11_STR_CHECK_FUN PyUnicode_Check
1337 template <
typename T>
1339 template <
typename T>
1341 template <
typename T>
1343 template <
typename T>
1345 template <
typename T>
1349 template <return_value_policy policy = return_value_policy::automatic_reference>
1351 template <return_value_policy policy = return_value_policy::automatic_reference>
1360 #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1362 PYBIND11_DEPRECATED("Use reinterpret_borrow<" #Name ">() or reinterpret_steal<" #Name ">()") \
1363 Name(handle h, bool is_borrowed) \
1364 : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {} \
1365 Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {} \
1366 Name(handle h, stolen_t) : Parent(h, stolen_t{}) {} \
1367 PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
1368 bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \
1369 static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \
1370 template <typename Policy_> \
1371 Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) {}
1373 #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1374 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1377 Name(const object &o) \
1378 : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1380 throw ::pybind11::error_already_set(); \
1383 Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1385 throw ::pybind11::error_already_set(); \
1388 #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \
1389 PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1392 #define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \
1393 ::pybind11::type_error("Object of type '" \
1394 + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) \
1395 + "' is not an instance of '" #Name "'")
1397 #define PYBIND11_OBJECT(Name, Parent, CheckFun) \
1398 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1401 Name(const object &o) : Parent(o) { \
1402 if (m_ptr && !check_(m_ptr)) \
1403 throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1406 Name(object &&o) : Parent(std::move(o)) { \
1407 if (m_ptr && !check_(m_ptr)) \
1408 throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1411 #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
1412 PYBIND11_OBJECT(Name, Parent, CheckFun) \
1449 if (m_ptr && !
value.ptr()) {
1450 auto &
self =
const_cast<iterator &
>(*this);
1481 value = reinterpret_steal<object>(PyIter_Next(m_ptr));
1482 if (
value.ptr() ==
nullptr && PyErr_Occurred()) {
1505 template <
typename T>
1506 static handle handle_of();
1511 template <
typename T>
1532 if (PyErr_Occurred()) {
1544 if (PyErr_Occurred()) {
1554 #ifdef PYBIND11_HAS_STRING_VIEW
1560 # ifdef PYBIND11_HAS_U8STRING
1563 str(std::u8string_view
s) :
str(reinterpret_cast<const char *>(
s.
data()),
s.
size()) {}
1581 operator std::string()
const {
1582 object temp = *
this;
1583 if (PyUnicode_Check(m_ptr)) {
1584 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
1591 if (PyBytes_AsStringAndSize(temp.
ptr(), &
buffer, &length) != 0) {
1594 return std::string(
buffer, (
size_t) length);
1597 template <
typename... Args>
1599 return attr(
"format")(std::forward<Args>(
args)...);
1605 PyObject *str_value = PyObject_Str(op);
1647 operator std::string()
const {
return string_op<std::string>(); }
1649 #ifdef PYBIND11_HAS_STRING_VIEW
1659 operator std::string_view()
const {
return string_op<std::string_view>(); }
1662 template <
typename T>
1666 if (PyBytes_AsStringAndSize(m_ptr, &
buffer, &length) != 0) {
1669 return {
buffer,
static_cast<size_t>(length)};
1678 if (PyUnicode_Check(
s.ptr())) {
1679 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(
s.ptr()));
1686 if (PyBytes_AsStringAndSize(temp.
ptr(), &
buffer, &length) != 0) {
1693 m_ptr = obj.release().
ptr();
1699 if (PyBytes_AsStringAndSize(
b.ptr(), &
buffer, &length) != 0) {
1702 auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(
buffer, length));
1704 if (PyErr_Occurred()) {
1709 m_ptr = obj.release().
ptr();
1730 size_t size()
const {
return static_cast<size_t>(PyByteArray_Size(m_ptr)); }
1732 explicit operator std::string()
const {
1733 char *
buffer = PyByteArray_AS_STRING(m_ptr);
1735 return std::string(
buffer,
static_cast<size_t>(
size));
1764 operator bool()
const {
return (m_ptr !=
nullptr) && PyLong_AsLong(m_ptr) != 0; }
1769 const auto value = PyObject_IsTrue(op);
1782 template <
typename Un
signed>
1784 if (
sizeof(Unsigned) <=
sizeof(
unsigned long)) {
1785 unsigned long v = PyLong_AsUnsignedLong(o);
1786 return v == (
unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned)
v;
1788 unsigned long long v = PyLong_AsUnsignedLongLong(o);
1789 return v == (
unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned)
v;
1801 if (
sizeof(
T) <=
sizeof(
long)) {
1803 m_ptr = PyLong_FromLong((
long)
value);
1805 m_ptr = PyLong_FromUnsignedLong((
unsigned long)
value);
1809 m_ptr = PyLong_FromLongLong((
long long)
value);
1811 m_ptr = PyLong_FromUnsignedLongLong((
unsigned long long)
value);
1821 operator T()
const {
1823 :
sizeof(
T) <=
sizeof(
long) ? (
T) PyLong_AsLong(m_ptr)
1845 operator float()
const {
return (
float) PyFloat_AsDouble(m_ptr); }
1847 operator double()
const {
return (
double) PyFloat_AsDouble(m_ptr); }
1854 :
object(PyWeakref_NewRef(obj.
ptr(), callback.ptr()), stolen_t{}) {
1856 if (PyErr_Occurred()) {
1864 static PyObject *
raw_weakref(PyObject *o) {
return PyWeakref_NewRef(o,
nullptr); }
1871 :
object(PySlice_New(start.ptr(), stop.ptr(),
step.ptr()),
stolen_t{}) {
1877 #ifdef PYBIND11_HAS_OPTIONAL
1878 slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t>
step)
1879 :
slice(index_to_object(start), index_to_object(stop), index_to_object(
step)) {}
1886 compute(
size_t length,
size_t *start,
size_t *stop,
size_t *
step,
size_t *slicelength)
const {
1897 return PySlice_GetIndicesEx(
1903 template <
typename T>
1913 capsule(PyObject *ptr,
bool is_borrowed)
1917 const char *
name =
nullptr,
1918 PyCapsule_Destructor destructor =
nullptr)
1919 :
object(PyCapsule_New(const_cast<void *>(
value),
name, destructor), stolen_t{}) {
1926 capsule(const
void *
value, PyCapsule_Destructor destructor)
1927 :
object(PyCapsule_New(const_cast<
void *>(
value),
nullptr, destructor), stolen_t{}) {
1934 capsule(
const void *
value,
void (*destructor)(
void *)) {
1935 initialize_with_void_ptr_destructor(
value,
nullptr, destructor);
1939 initialize_with_void_ptr_destructor(
value,
name, destructor);
1942 explicit capsule(
void (*destructor)()) {
1943 m_ptr = PyCapsule_New(
reinterpret_cast<void *
>(destructor),
nullptr, [](PyObject *o) {
1944 const char *
name = get_name_in_error_scope(o);
1945 auto destructor =
reinterpret_cast<void (*)()
>(PyCapsule_GetPointer(o,
name));
1946 if (destructor ==
nullptr) {
1957 template <
typename T>
1958 operator T *()
const {
1959 return get_pointer<T>();
1963 template <
typename T =
void>
1964 T *get_pointer()
const {
1966 T *
result =
static_cast<T *
>(PyCapsule_GetPointer(m_ptr,
name));
1974 void set_pointer(
const void *
value) {
1975 if (PyCapsule_SetPointer(m_ptr,
const_cast<void *
>(
value)) != 0) {
1980 const char *
name()
const {
1981 const char *
name = PyCapsule_GetName(m_ptr);
1982 if ((
name ==
nullptr) && PyErr_Occurred()) {
1989 void set_name(
const char *new_name) {
1990 if (PyCapsule_SetName(m_ptr, new_name) != 0) {
1996 static const char *get_name_in_error_scope(PyObject *o) {
1999 const char *
name = PyCapsule_GetName(o);
2000 if ((
name ==
nullptr) && PyErr_Occurred()) {
2002 PyErr_WriteUnraisable(o);
2008 void initialize_with_void_ptr_destructor(
const void *
value,
2010 void (*destructor)(
void *)) {
2011 m_ptr = PyCapsule_New(
const_cast<void *
>(
value),
name, [](PyObject *o) {
2014 auto destructor =
reinterpret_cast<void (*)(
void *)
>(PyCapsule_GetContext(o));
2015 if (destructor ==
nullptr && PyErr_Occurred()) {
2018 const char *
name = get_name_in_error_scope(o);
2019 void *ptr = PyCapsule_GetPointer(o,
name);
2020 if (ptr ==
nullptr) {
2024 if (destructor !=
nullptr) {
2029 if (!m_ptr || PyCapsule_SetContext(m_ptr,
reinterpret_cast<void *
>(destructor)) != 0) {
2038 template <
typename SzType =
ssize_t,
2046 size_t size()
const {
return (
size_t) PyTuple_Size(m_ptr); }
2051 return object::operator[](std::forward<T>(o));
2060 template <
typename... Args>
2062 return detail::all_of<detail::is_keyword_or_ds<Args>...>
::value;
2073 template <
typename... Args,
2080 size_t size()
const {
return (
size_t) PyDict_Size(m_ptr); }
2085 template <
typename T>
2097 if (PyDict_Check(op)) {
2100 return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op,
nullptr);
2118 return object::operator[](std::forward<T>(o));
2127 template <
typename SzType =
ssize_t,
2135 size_t size()
const {
return (
size_t) PyList_Size(m_ptr); }
2140 return object::operator[](std::forward<T>(o));
2144 template <
typename T>
2150 template <
typename IdxType,
2153 void insert(
const IdxType &index, ValType &&val) {
2154 if (PyList_Insert(m_ptr,
2173 size_t size()
const {
return static_cast<size_t>(PySet_Size(m_ptr)); }
2175 template <
typename T>
2193 template <
typename T>
2210 if (fun && PyCFunction_Check(fun.
ptr())) {
2228 int flags = PyBUF_STRIDES | PyBUF_FORMAT;
2230 flags |= PyBUF_WRITABLE;
2232 auto *
view =
new Py_buffer();
2233 if (PyObject_GetBuffer(m_ptr,
view, flags) != 0) {
2256 pybind11_fail(
"Prohibited to create memoryview without Py_buffer");
2259 m_ptr = (
info.view()->obj) ? PyMemoryView_FromObject(
info.view()->obj)
2260 : PyMemoryView_FromBuffer(
info.view());
2262 pybind11_fail(
"Unable to create memoryview from buffer descriptor");
2293 detail::any_container<ssize_t> shape,
2294 detail::any_container<ssize_t>
strides,
2295 bool readonly =
false);
2300 detail::any_container<ssize_t> shape,
2301 detail::any_container<ssize_t>
strides) {
2303 const_cast<void *
>(ptr), itemsize,
format, std::move(shape), std::move(
strides),
true);
2306 template <
typename T>
2308 detail::any_container<ssize_t> shape,
2309 detail::any_container<ssize_t>
strides,
2310 bool readonly =
false) {
2319 template <
typename T>
2321 detail::any_container<ssize_t> shape,
2322 detail::any_container<ssize_t>
strides) {
2324 const_cast<T *
>(ptr), std::move(shape), std::move(
strides),
true);
2340 PyObject *ptr = PyMemoryView_FromMemory(
2341 reinterpret_cast<char *
>(mem),
size, (readonly) ? PyBUF_READ : PyBUF_WRITE);
2352 #ifdef PYBIND11_HAS_STRING_VIEW
2353 static memoryview from_memory(std::string_view mem) {
2354 return from_memory(
const_cast<char *
>(mem.data()),
static_cast<ssize_t>(mem.size()),
true);
2363 detail::any_container<ssize_t> shape,
2364 detail::any_container<ssize_t>
strides,
2366 size_t ndim = shape->size();
2368 pybind11_fail(
"memoryview: shape length doesn't match strides length");
2371 for (
size_t i = 0;
i < ndim; ++
i) {
2372 size *= (*shape)[
i];
2378 view.readonly =
static_cast<int>(readonly);
2379 view.itemsize = itemsize;
2381 view.ndim =
static_cast<int>(ndim);
2382 view.shape = shape->data();
2384 view.suboffsets =
nullptr;
2385 view.internal =
nullptr;
2386 PyObject *obj = PyMemoryView_FromBuffer(&
view);
2421 PyObject *str_value = PyObject_Repr(
h.ptr());
2425 return reinterpret_steal<str>(str_value);
2429 PyObject *
result = PyObject_GetIter(obj.
ptr());
2433 return reinterpret_steal<iterator>(
result);
2438 template <
typename D>
2440 return iter(derived());
2442 template <
typename D>
2446 template <
typename D>
2448 return {derived(), reinterpret_borrow<object>(
key)};
2450 template <
typename D>
2452 return {derived(), std::move(
key)};
2454 template <
typename D>
2458 template <
typename D>
2460 return {derived(), reinterpret_borrow<object>(
key)};
2462 template <
typename D>
2464 return {derived(), std::move(
key)};
2466 template <
typename D>
2468 return {derived(),
key};
2470 template <
typename D>
2474 template <
typename D>
2475 template <
typename T>
2477 return attr(
"__contains__")(std::forward<T>(item)).
template cast<bool>();
2480 template <
typename D>
2485 template <
typename D>
2487 return attr(
"__doc__");
2490 template <
typename D>
2495 template <
typename D>
2497 int rv = PyObject_RichCompareBool(derived().ptr(),
other.derived().ptr(),
value);
2504 #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
2505 template <typename D> \
2506 object object_api<D>::op() const { \
2507 object result = reinterpret_steal<object>(fn(derived().ptr())); \
2508 if (!result.ptr()) \
2509 throw error_already_set(); \
2513 #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
2514 template <typename D> \
2515 object object_api<D>::op(object_api const &other) const { \
2516 object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
2517 if (!result.ptr()) \
2518 throw error_already_set(); \
2522 #define PYBIND11_MATH_OPERATOR_BINARY_INPLACE(iop, fn) \
2523 template <typename D> \
2524 object object_api<D>::iop(object_api const &other) { \
2525 object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
2526 if (!result.ptr()) \
2527 throw error_already_set(); \
2552 #undef PYBIND11_MATH_OPERATOR_UNARY
2553 #undef PYBIND11_MATH_OPERATOR_BINARY
2554 #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))
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)
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 *().
int ref_count() const
Return the object's current reference count.
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
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 Jun 13 2024 03:04:47