File indexing completed on 2025-01-18 10:06:17
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010 #pragma once
0011
0012 #include "detail/common.h"
0013 #include "buffer_info.h"
0014
0015 #include <assert.h>
0016 #include <cstddef>
0017 #include <exception>
0018 #include <frameobject.h>
0019 #include <iterator>
0020 #include <memory>
0021 #include <string>
0022 #include <type_traits>
0023 #include <typeinfo>
0024 #include <utility>
0025
0026 #if defined(PYBIND11_HAS_OPTIONAL)
0027 # include <optional>
0028 #endif
0029
0030 #ifdef PYBIND11_HAS_STRING_VIEW
0031 # include <string_view>
0032 #endif
0033
0034 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0035
0036 PYBIND11_WARNING_DISABLE_MSVC(4127)
0037
0038
0039 class handle;
0040 class object;
0041 class str;
0042 class iterator;
0043 class type;
0044 struct arg;
0045 struct arg_v;
0046
0047 PYBIND11_NAMESPACE_BEGIN(detail)
0048 class args_proxy;
0049 bool isinstance_generic(handle obj, const std::type_info &tp);
0050
0051
0052 template <typename Policy>
0053 class accessor;
0054 namespace accessor_policies {
0055 struct obj_attr;
0056 struct str_attr;
0057 struct generic_item;
0058 struct sequence_item;
0059 struct list_item;
0060 struct tuple_item;
0061 }
0062
0063 using obj_attr_accessor = accessor<accessor_policies::obj_attr>;
0064 using str_attr_accessor = accessor<accessor_policies::str_attr>;
0065 using item_accessor = accessor<accessor_policies::generic_item>;
0066 using sequence_accessor = accessor<accessor_policies::sequence_item>;
0067 using list_accessor = accessor<accessor_policies::list_item>;
0068 using tuple_accessor = accessor<accessor_policies::tuple_item>;
0069
0070
0071 class pyobject_tag {};
0072 template <typename T>
0073 using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
0074
0075
0076
0077
0078
0079 template <typename Derived>
0080 class object_api : public pyobject_tag {
0081 const Derived &derived() const { return static_cast<const Derived &>(*this); }
0082
0083 public:
0084
0085
0086
0087
0088 iterator begin() const;
0089
0090 iterator end() const;
0091
0092
0093
0094
0095
0096
0097
0098 item_accessor operator[](handle key) const;
0099
0100 item_accessor operator[](object &&key) const;
0101
0102 item_accessor operator[](const char *key) const;
0103
0104
0105
0106
0107
0108
0109
0110 obj_attr_accessor attr(handle key) const;
0111
0112 obj_attr_accessor attr(object &&key) const;
0113
0114 str_attr_accessor attr(const char *key) const;
0115
0116
0117
0118
0119
0120
0121
0122 args_proxy operator*() const;
0123
0124
0125 template <typename T>
0126 bool contains(T &&item) const;
0127
0128
0129
0130
0131
0132
0133
0134
0135
0136
0137
0138 template <return_value_policy policy = return_value_policy::automatic_reference,
0139 typename... Args>
0140 object operator()(Args &&...args) const;
0141 template <return_value_policy policy = return_value_policy::automatic_reference,
0142 typename... Args>
0143 PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)")
0144 object call(Args &&...args) const;
0145
0146
0147 bool is(object_api const &other) const { return derived().ptr() == other.derived().ptr(); }
0148
0149 bool is_none() const { return derived().ptr() == Py_None; }
0150
0151 bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); }
0152 bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); }
0153 bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); }
0154 bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); }
0155 bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); }
0156 bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); }
0157
0158 object operator-() const;
0159 object operator~() const;
0160 object operator+(object_api const &other) const;
0161 object operator+=(object_api const &other);
0162 object operator-(object_api const &other) const;
0163 object operator-=(object_api const &other);
0164 object operator*(object_api const &other) const;
0165 object operator*=(object_api const &other);
0166 object operator/(object_api const &other) const;
0167 object operator/=(object_api const &other);
0168 object operator|(object_api const &other) const;
0169 object operator|=(object_api const &other);
0170 object operator&(object_api const &other) const;
0171 object operator&=(object_api const &other);
0172 object operator^(object_api const &other) const;
0173 object operator^=(object_api const &other);
0174 object operator<<(object_api const &other) const;
0175 object operator<<=(object_api const &other);
0176 object operator>>(object_api const &other) const;
0177 object operator>>=(object_api const &other);
0178
0179 PYBIND11_DEPRECATED("Use py::str(obj) instead")
0180 pybind11::str str() const;
0181
0182
0183 str_attr_accessor doc() const;
0184
0185
0186 ssize_t ref_count() const {
0187 #ifdef PYPY_VERSION
0188
0189
0190 return static_cast<ssize_t>(static_cast<int>(Py_REFCNT(derived().ptr())));
0191 #else
0192 return Py_REFCNT(derived().ptr());
0193 #endif
0194 }
0195
0196
0197
0198 handle get_type() const;
0199
0200 private:
0201 bool rich_compare(object_api const &other, int value) const;
0202 };
0203
0204 template <typename T>
0205 using is_pyobj_ptr_or_nullptr_t = detail::any_of<std::is_same<T, PyObject *>,
0206 std::is_same<T, PyObject *const>,
0207 std::is_same<T, std::nullptr_t>>;
0208
0209 PYBIND11_NAMESPACE_END(detail)
0210
0211 #if !defined(PYBIND11_HANDLE_REF_DEBUG) && !defined(NDEBUG)
0212 # define PYBIND11_HANDLE_REF_DEBUG
0213 #endif
0214
0215
0216
0217
0218
0219
0220
0221
0222
0223
0224
0225
0226 class handle : public detail::object_api<handle> {
0227 public:
0228
0229 handle() = default;
0230
0231
0232
0233 template <typename T,
0234 detail::enable_if_t<detail::is_pyobj_ptr_or_nullptr_t<T>::value, int> = 0>
0235
0236 handle(T ptr) : m_ptr(ptr) {}
0237
0238
0239 template <
0240 typename T,
0241 detail::enable_if_t<detail::all_of<detail::none_of<std::is_base_of<handle, T>,
0242 detail::is_pyobj_ptr_or_nullptr_t<T>>,
0243 std::is_convertible<T, PyObject *>>::value,
0244 int>
0245 = 0>
0246
0247 handle(T &obj) : m_ptr(obj) {}
0248
0249
0250 PyObject *ptr() const { return m_ptr; }
0251 PyObject *&ptr() { return m_ptr; }
0252
0253
0254
0255
0256
0257
0258 const handle &inc_ref() const & {
0259 #ifdef PYBIND11_HANDLE_REF_DEBUG
0260 inc_ref_counter(1);
0261 #endif
0262 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
0263 if (m_ptr != nullptr && !PyGILState_Check()) {
0264 throw_gilstate_error("pybind11::handle::inc_ref()");
0265 }
0266 #endif
0267 Py_XINCREF(m_ptr);
0268 return *this;
0269 }
0270
0271
0272
0273
0274
0275
0276 const handle &dec_ref() const & {
0277 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
0278 if (m_ptr != nullptr && !PyGILState_Check()) {
0279 throw_gilstate_error("pybind11::handle::dec_ref()");
0280 }
0281 #endif
0282 Py_XDECREF(m_ptr);
0283 return *this;
0284 }
0285
0286
0287
0288
0289
0290 template <typename T>
0291 T cast() const;
0292
0293 explicit operator bool() const { return m_ptr != nullptr; }
0294
0295
0296
0297
0298 PYBIND11_DEPRECATED("Use obj1.is(obj2) instead")
0299 bool operator==(const handle &h) const { return m_ptr == h.m_ptr; }
0300 PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead")
0301 bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }
0302 PYBIND11_DEPRECATED("Use handle::operator bool() instead")
0303 bool check() const { return m_ptr != nullptr; }
0304
0305 protected:
0306 PyObject *m_ptr = nullptr;
0307
0308 private:
0309 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
0310 void throw_gilstate_error(const std::string &function_name) const {
0311 fprintf(
0312 stderr,
0313 "%s is being called while the GIL is either not held or invalid. Please see "
0314 "https://pybind11.readthedocs.io/en/stable/advanced/"
0315 "misc.html#common-sources-of-global-interpreter-lock-errors for debugging advice.\n"
0316 "If you are convinced there is no bug in your code, you can #define "
0317 "PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF "
0318 "to disable this check. In that case you have to ensure this #define is consistently "
0319 "used for all translation units linked into a given pybind11 extension, otherwise "
0320 "there will be ODR violations.",
0321 function_name.c_str());
0322 if (Py_TYPE(m_ptr)->tp_name != nullptr) {
0323 fprintf(stderr,
0324 " The failing %s call was triggered on a %s object.",
0325 function_name.c_str(),
0326 Py_TYPE(m_ptr)->tp_name);
0327 }
0328 fprintf(stderr, "\n");
0329 fflush(stderr);
0330 throw std::runtime_error(function_name + " PyGILState_Check() failure.");
0331 }
0332 #endif
0333
0334 #ifdef PYBIND11_HANDLE_REF_DEBUG
0335 static std::size_t inc_ref_counter(std::size_t add) {
0336 thread_local std::size_t counter = 0;
0337 counter += add;
0338 return counter;
0339 }
0340
0341 public:
0342 static std::size_t inc_ref_counter() { return inc_ref_counter(0); }
0343 #endif
0344 };
0345
0346 inline void set_error(const handle &type, const char *message) {
0347 PyErr_SetString(type.ptr(), message);
0348 }
0349
0350 inline void set_error(const handle &type, const handle &value) {
0351 PyErr_SetObject(type.ptr(), value.ptr());
0352 }
0353
0354
0355
0356
0357
0358
0359
0360
0361
0362
0363
0364 class object : public handle {
0365 public:
0366 object() = default;
0367 PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()")
0368 object(handle h, bool is_borrowed) : handle(h) {
0369 if (is_borrowed) {
0370 inc_ref();
0371 }
0372 }
0373
0374 object(const object &o) : handle(o) { inc_ref(); }
0375
0376 object(object &&other) noexcept : handle(other) { other.m_ptr = nullptr; }
0377
0378 ~object() { dec_ref(); }
0379
0380
0381
0382
0383
0384
0385 handle release() {
0386 PyObject *tmp = m_ptr;
0387 m_ptr = nullptr;
0388 return handle(tmp);
0389 }
0390
0391 object &operator=(const object &other) {
0392
0393 if (!this->is(other)) {
0394 other.inc_ref();
0395
0396
0397 handle temp(m_ptr);
0398 m_ptr = other.m_ptr;
0399 temp.dec_ref();
0400 }
0401 return *this;
0402 }
0403
0404 object &operator=(object &&other) noexcept {
0405 if (this != &other) {
0406 handle temp(m_ptr);
0407 m_ptr = other.m_ptr;
0408 other.m_ptr = nullptr;
0409 temp.dec_ref();
0410 }
0411 return *this;
0412 }
0413
0414 #define PYBIND11_INPLACE_OP(iop) \
0415 object iop(object_api const &other) { return operator=(handle::iop(other)); }
0416
0417 PYBIND11_INPLACE_OP(operator+=)
0418 PYBIND11_INPLACE_OP(operator-=)
0419 PYBIND11_INPLACE_OP(operator*=)
0420 PYBIND11_INPLACE_OP(operator/=)
0421 PYBIND11_INPLACE_OP(operator|=)
0422 PYBIND11_INPLACE_OP(operator&=)
0423 PYBIND11_INPLACE_OP(operator^=)
0424 PYBIND11_INPLACE_OP(operator<<=)
0425 PYBIND11_INPLACE_OP(operator>>=)
0426 #undef PYBIND11_INPLACE_OP
0427
0428
0429 template <typename T>
0430 T cast() const &;
0431
0432 template <typename T>
0433 T cast() &&;
0434
0435 protected:
0436
0437 struct borrowed_t {};
0438 struct stolen_t {};
0439
0440
0441 template <typename T>
0442 friend T reinterpret_borrow(handle);
0443 template <typename T>
0444 friend T reinterpret_steal(handle);
0445
0446
0447 public:
0448
0449 object(handle h, borrowed_t) : handle(h) { inc_ref(); }
0450 object(handle h, stolen_t) : handle(h) {}
0451 };
0452
0453
0454
0455
0456
0457
0458
0459
0460
0461
0462
0463
0464
0465
0466 template <typename T>
0467 T reinterpret_borrow(handle h) {
0468 return {h, object::borrowed_t{}};
0469 }
0470
0471
0472
0473
0474
0475
0476
0477
0478
0479 template <typename T>
0480 T reinterpret_steal(handle h) {
0481 return {h, object::stolen_t{}};
0482 }
0483
0484 PYBIND11_NAMESPACE_BEGIN(detail)
0485
0486
0487 inline const char *obj_class_name(PyObject *obj) {
0488 if (PyType_Check(obj)) {
0489 return reinterpret_cast<PyTypeObject *>(obj)->tp_name;
0490 }
0491 return Py_TYPE(obj)->tp_name;
0492 }
0493
0494 std::string error_string();
0495
0496
0497
0498
0499
0500
0501
0502
0503
0504 struct error_fetch_and_normalize {
0505
0506
0507
0508
0509
0510
0511
0512
0513
0514 explicit error_fetch_and_normalize(const char *called) {
0515 PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
0516 if (!m_type) {
0517 pybind11_fail("Internal error: " + std::string(called)
0518 + " called while "
0519 "Python error indicator not set.");
0520 }
0521 const char *exc_type_name_orig = detail::obj_class_name(m_type.ptr());
0522 if (exc_type_name_orig == nullptr) {
0523 pybind11_fail("Internal error: " + std::string(called)
0524 + " failed to obtain the name "
0525 "of the original active exception type.");
0526 }
0527 m_lazy_error_string = exc_type_name_orig;
0528 #if PY_VERSION_HEX >= 0x030C0000
0529
0530
0531
0532 if (PyObject_HasAttrString(m_value.ptr(), "__notes__")) {
0533 m_lazy_error_string += "[WITH __notes__]";
0534 }
0535 #else
0536
0537
0538 PyErr_NormalizeException(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
0539 if (m_type.ptr() == nullptr) {
0540 pybind11_fail("Internal error: " + std::string(called)
0541 + " failed to normalize the "
0542 "active exception.");
0543 }
0544 const char *exc_type_name_norm = detail::obj_class_name(m_type.ptr());
0545 if (exc_type_name_norm == nullptr) {
0546 pybind11_fail("Internal error: " + std::string(called)
0547 + " failed to obtain the name "
0548 "of the normalized active exception type.");
0549 }
0550 # if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x07030a00
0551
0552
0553
0554 m_lazy_error_string = exc_type_name_norm;
0555 # else
0556 if (exc_type_name_norm != m_lazy_error_string) {
0557 std::string msg = std::string(called)
0558 + ": MISMATCH of original and normalized "
0559 "active exception types: ";
0560 msg += "ORIGINAL ";
0561 msg += m_lazy_error_string;
0562 msg += " REPLACED BY ";
0563 msg += exc_type_name_norm;
0564 msg += ": " + format_value_and_trace();
0565 pybind11_fail(msg);
0566 }
0567 # endif
0568 #endif
0569 }
0570
0571 error_fetch_and_normalize(const error_fetch_and_normalize &) = delete;
0572 error_fetch_and_normalize(error_fetch_and_normalize &&) = delete;
0573
0574 std::string format_value_and_trace() const {
0575 std::string result;
0576 std::string message_error_string;
0577 if (m_value) {
0578 auto value_str = reinterpret_steal<object>(PyObject_Str(m_value.ptr()));
0579 constexpr const char *message_unavailable_exc
0580 = "<MESSAGE UNAVAILABLE DUE TO ANOTHER EXCEPTION>";
0581 if (!value_str) {
0582 message_error_string = detail::error_string();
0583 result = message_unavailable_exc;
0584 } else {
0585
0586
0587 auto value_bytes = reinterpret_steal<object>(
0588 PyUnicode_AsEncodedString(value_str.ptr(), "utf-8", "backslashreplace"));
0589 if (!value_bytes) {
0590 message_error_string = detail::error_string();
0591 result = message_unavailable_exc;
0592 } else {
0593 char *buffer = nullptr;
0594 Py_ssize_t length = 0;
0595 if (PyBytes_AsStringAndSize(value_bytes.ptr(), &buffer, &length) == -1) {
0596 message_error_string = detail::error_string();
0597 result = message_unavailable_exc;
0598 } else {
0599 result = std::string(buffer, static_cast<std::size_t>(length));
0600 }
0601 }
0602 }
0603 #if PY_VERSION_HEX >= 0x030B0000
0604 auto notes
0605 = reinterpret_steal<object>(PyObject_GetAttrString(m_value.ptr(), "__notes__"));
0606 if (!notes) {
0607 PyErr_Clear();
0608 } else {
0609 auto len_notes = PyList_Size(notes.ptr());
0610 if (len_notes < 0) {
0611 result += "\nFAILURE obtaining len(__notes__): " + detail::error_string();
0612 } else {
0613 result += "\n__notes__ (len=" + std::to_string(len_notes) + "):";
0614 for (ssize_t i = 0; i < len_notes; i++) {
0615 PyObject *note = PyList_GET_ITEM(notes.ptr(), i);
0616 auto note_bytes = reinterpret_steal<object>(
0617 PyUnicode_AsEncodedString(note, "utf-8", "backslashreplace"));
0618 if (!note_bytes) {
0619 result += "\nFAILURE obtaining __notes__[" + std::to_string(i)
0620 + "]: " + detail::error_string();
0621 } else {
0622 char *buffer = nullptr;
0623 Py_ssize_t length = 0;
0624 if (PyBytes_AsStringAndSize(note_bytes.ptr(), &buffer, &length)
0625 == -1) {
0626 result += "\nFAILURE formatting __notes__[" + std::to_string(i)
0627 + "]: " + detail::error_string();
0628 } else {
0629 result += '\n';
0630 result += std::string(buffer, static_cast<std::size_t>(length));
0631 }
0632 }
0633 }
0634 }
0635 }
0636 #endif
0637 } else {
0638 result = "<MESSAGE UNAVAILABLE>";
0639 }
0640 if (result.empty()) {
0641 result = "<EMPTY MESSAGE>";
0642 }
0643
0644 bool have_trace = false;
0645 if (m_trace) {
0646 #if !defined(PYPY_VERSION)
0647 auto *tb = reinterpret_cast<PyTracebackObject *>(m_trace.ptr());
0648
0649
0650 while (tb->tb_next) {
0651 tb = tb->tb_next;
0652 }
0653
0654 PyFrameObject *frame = tb->tb_frame;
0655 Py_XINCREF(frame);
0656 result += "\n\nAt:\n";
0657 while (frame) {
0658 # if PY_VERSION_HEX >= 0x030900B1
0659 PyCodeObject *f_code = PyFrame_GetCode(frame);
0660 # else
0661 PyCodeObject *f_code = frame->f_code;
0662 Py_INCREF(f_code);
0663 # endif
0664 int lineno = PyFrame_GetLineNumber(frame);
0665 result += " ";
0666 result += handle(f_code->co_filename).cast<std::string>();
0667 result += '(';
0668 result += std::to_string(lineno);
0669 result += "): ";
0670 result += handle(f_code->co_name).cast<std::string>();
0671 result += '\n';
0672 Py_DECREF(f_code);
0673 # if PY_VERSION_HEX >= 0x030900B1
0674 auto *b_frame = PyFrame_GetBack(frame);
0675 # else
0676 auto *b_frame = frame->f_back;
0677 Py_XINCREF(b_frame);
0678 # endif
0679 Py_DECREF(frame);
0680 frame = b_frame;
0681 }
0682
0683 have_trace = true;
0684 #endif
0685 }
0686
0687 if (!message_error_string.empty()) {
0688 if (!have_trace) {
0689 result += '\n';
0690 }
0691 result += "\nMESSAGE UNAVAILABLE DUE TO EXCEPTION: " + message_error_string;
0692 }
0693
0694 return result;
0695 }
0696
0697 std::string const &error_string() const {
0698 if (!m_lazy_error_string_completed) {
0699 m_lazy_error_string += ": " + format_value_and_trace();
0700 m_lazy_error_string_completed = true;
0701 }
0702 return m_lazy_error_string;
0703 }
0704
0705 void restore() {
0706 if (m_restore_called) {
0707 pybind11_fail("Internal error: pybind11::detail::error_fetch_and_normalize::restore() "
0708 "called a second time. ORIGINAL ERROR: "
0709 + error_string());
0710 }
0711 PyErr_Restore(m_type.inc_ref().ptr(), m_value.inc_ref().ptr(), m_trace.inc_ref().ptr());
0712 m_restore_called = true;
0713 }
0714
0715 bool matches(handle exc) const {
0716 return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0);
0717 }
0718
0719
0720 object m_type, m_value, m_trace;
0721
0722 private:
0723
0724 mutable std::string m_lazy_error_string;
0725 mutable bool m_lazy_error_string_completed = false;
0726 mutable bool m_restore_called = false;
0727 };
0728
0729 inline std::string error_string() {
0730 return error_fetch_and_normalize("pybind11::detail::error_string").error_string();
0731 }
0732
0733 PYBIND11_NAMESPACE_END(detail)
0734
0735
0736
0737
0738
0739 class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::exception {
0740 public:
0741
0742
0743 error_already_set()
0744 : m_fetched_error{new detail::error_fetch_and_normalize("pybind11::error_already_set"),
0745 m_fetched_error_deleter} {}
0746
0747
0748
0749
0750 const char *what() const noexcept override;
0751
0752
0753
0754
0755
0756
0757 void restore() { m_fetched_error->restore(); }
0758
0759
0760
0761
0762
0763 void discard_as_unraisable(object err_context) {
0764 restore();
0765 PyErr_WriteUnraisable(err_context.ptr());
0766 }
0767
0768
0769
0770 void discard_as_unraisable(const char *err_context) {
0771 discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context)));
0772 }
0773
0774
0775 PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated")
0776 void clear() {}
0777
0778
0779
0780
0781 bool matches(handle exc) const { return m_fetched_error->matches(exc); }
0782
0783 const object &type() const { return m_fetched_error->m_type; }
0784 const object &value() const { return m_fetched_error->m_value; }
0785 const object &trace() const { return m_fetched_error->m_trace; }
0786
0787 private:
0788 std::shared_ptr<detail::error_fetch_and_normalize> m_fetched_error;
0789
0790
0791
0792 static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr);
0793 };
0794
0795
0796
0797 inline void raise_from(PyObject *type, const char *message) {
0798
0799
0800
0801 PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr;
0802
0803 assert(PyErr_Occurred());
0804 PyErr_Fetch(&exc, &val, &tb);
0805 PyErr_NormalizeException(&exc, &val, &tb);
0806 if (tb != nullptr) {
0807 PyException_SetTraceback(val, tb);
0808 Py_DECREF(tb);
0809 }
0810 Py_DECREF(exc);
0811 assert(!PyErr_Occurred());
0812
0813 PyErr_SetString(type, message);
0814
0815 PyErr_Fetch(&exc, &val2, &tb);
0816 PyErr_NormalizeException(&exc, &val2, &tb);
0817 Py_INCREF(val);
0818 PyException_SetCause(val2, val);
0819 PyException_SetContext(val2, val);
0820 PyErr_Restore(exc, val2, tb);
0821 }
0822
0823
0824
0825
0826 inline void raise_from(error_already_set &err, PyObject *type, const char *message) {
0827 err.restore();
0828 raise_from(type, message);
0829 }
0830
0831
0832
0833
0834
0835
0836
0837
0838
0839
0840
0841 template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0>
0842 bool isinstance(handle obj) {
0843 return T::check_(obj);
0844 }
0845
0846 template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0>
0847 bool isinstance(handle obj) {
0848 return detail::isinstance_generic(obj, typeid(T));
0849 }
0850
0851 template <>
0852 inline bool isinstance<handle>(handle) = delete;
0853 template <>
0854 inline bool isinstance<object>(handle obj) {
0855 return obj.ptr() != nullptr;
0856 }
0857
0858
0859
0860 inline bool isinstance(handle obj, handle type) {
0861 const auto result = PyObject_IsInstance(obj.ptr(), type.ptr());
0862 if (result == -1) {
0863 throw error_already_set();
0864 }
0865 return result != 0;
0866 }
0867
0868
0869
0870 inline bool hasattr(handle obj, handle name) {
0871 return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1;
0872 }
0873
0874 inline bool hasattr(handle obj, const char *name) {
0875 return PyObject_HasAttrString(obj.ptr(), name) == 1;
0876 }
0877
0878 inline void delattr(handle obj, handle name) {
0879 if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) {
0880 throw error_already_set();
0881 }
0882 }
0883
0884 inline void delattr(handle obj, const char *name) {
0885 if (PyObject_DelAttrString(obj.ptr(), name) != 0) {
0886 throw error_already_set();
0887 }
0888 }
0889
0890 inline object getattr(handle obj, handle name) {
0891 PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr());
0892 if (!result) {
0893 throw error_already_set();
0894 }
0895 return reinterpret_steal<object>(result);
0896 }
0897
0898 inline object getattr(handle obj, const char *name) {
0899 PyObject *result = PyObject_GetAttrString(obj.ptr(), name);
0900 if (!result) {
0901 throw error_already_set();
0902 }
0903 return reinterpret_steal<object>(result);
0904 }
0905
0906 inline object getattr(handle obj, handle name, handle default_) {
0907 if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) {
0908 return reinterpret_steal<object>(result);
0909 }
0910 PyErr_Clear();
0911 return reinterpret_borrow<object>(default_);
0912 }
0913
0914 inline object getattr(handle obj, const char *name, handle default_) {
0915 if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) {
0916 return reinterpret_steal<object>(result);
0917 }
0918 PyErr_Clear();
0919 return reinterpret_borrow<object>(default_);
0920 }
0921
0922 inline void setattr(handle obj, handle name, handle value) {
0923 if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) {
0924 throw error_already_set();
0925 }
0926 }
0927
0928 inline void setattr(handle obj, const char *name, handle value) {
0929 if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) {
0930 throw error_already_set();
0931 }
0932 }
0933
0934 inline ssize_t hash(handle obj) {
0935 auto h = PyObject_Hash(obj.ptr());
0936 if (h == -1) {
0937 throw error_already_set();
0938 }
0939 return h;
0940 }
0941
0942
0943
0944 PYBIND11_NAMESPACE_BEGIN(detail)
0945 inline handle get_function(handle value) {
0946 if (value) {
0947 if (PyInstanceMethod_Check(value.ptr())) {
0948 value = PyInstanceMethod_GET_FUNCTION(value.ptr());
0949 } else if (PyMethod_Check(value.ptr())) {
0950 value = PyMethod_GET_FUNCTION(value.ptr());
0951 }
0952 }
0953 return value;
0954 }
0955
0956
0957
0958
0959
0960 inline PyObject *dict_getitemstring(PyObject *v, const char *key) {
0961 PyObject *kv = nullptr, *rv = nullptr;
0962 kv = PyUnicode_FromString(key);
0963 if (kv == nullptr) {
0964 throw error_already_set();
0965 }
0966
0967 rv = PyDict_GetItemWithError(v, kv);
0968 Py_DECREF(kv);
0969 if (rv == nullptr && PyErr_Occurred()) {
0970 throw error_already_set();
0971 }
0972 return rv;
0973 }
0974
0975 inline PyObject *dict_getitem(PyObject *v, PyObject *key) {
0976 PyObject *rv = PyDict_GetItemWithError(v, key);
0977 if (rv == nullptr && PyErr_Occurred()) {
0978 throw error_already_set();
0979 }
0980 return rv;
0981 }
0982
0983 inline PyObject *dict_getitemstringref(PyObject *v, const char *key) {
0984 #if PY_VERSION_HEX >= 0x030D0000
0985 PyObject *rv;
0986 if (PyDict_GetItemStringRef(v, key, &rv) < 0) {
0987 throw error_already_set();
0988 }
0989 return rv;
0990 #else
0991 PyObject *rv = dict_getitemstring(v, key);
0992 if (rv == nullptr && PyErr_Occurred()) {
0993 throw error_already_set();
0994 }
0995 Py_XINCREF(rv);
0996 return rv;
0997 #endif
0998 }
0999
1000
1001
1002
1003 template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0>
1004 auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) {
1005 return std::forward<T>(o);
1006 }
1007
1008 template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0>
1009 object object_or_cast(T &&o);
1010
1011 inline handle object_or_cast(PyObject *ptr) { return ptr; }
1012
1013 PYBIND11_WARNING_PUSH
1014 PYBIND11_WARNING_DISABLE_MSVC(4522)
1015 template <typename Policy>
1016 class accessor : public object_api<accessor<Policy>> {
1017 using key_type = typename Policy::key_type;
1018
1019 public:
1020 accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) {}
1021 accessor(const accessor &) = default;
1022 accessor(accessor &&) noexcept = default;
1023
1024
1025
1026 void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); }
1027 void operator=(const accessor &a) & { operator=(handle(a)); }
1028
1029 template <typename T>
1030 void operator=(T &&value) && {
1031 Policy::set(obj, key, object_or_cast(std::forward<T>(value)));
1032 }
1033 template <typename T>
1034 void operator=(T &&value) & {
1035 get_cache() = ensure_object(object_or_cast(std::forward<T>(value)));
1036 }
1037
1038 template <typename T = Policy>
1039 PYBIND11_DEPRECATED(
1040 "Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
1041 explicit
1042 operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value
1043 || std::is_same<T, accessor_policies::obj_attr>::value,
1044 bool>() const {
1045 return hasattr(obj, key);
1046 }
1047 template <typename T = Policy>
1048 PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
1049 explicit
1050 operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const {
1051 return obj.contains(key);
1052 }
1053
1054
1055 operator object() const { return get_cache(); }
1056 PyObject *ptr() const { return get_cache().ptr(); }
1057 template <typename T>
1058 T cast() const {
1059 return get_cache().template cast<T>();
1060 }
1061
1062 private:
1063 static object ensure_object(object &&o) { return std::move(o); }
1064 static object ensure_object(handle h) { return reinterpret_borrow<object>(h); }
1065
1066 object &get_cache() const {
1067 if (!cache) {
1068 cache = Policy::get(obj, key);
1069 }
1070 return cache;
1071 }
1072
1073 private:
1074 handle obj;
1075 key_type key;
1076 mutable object cache;
1077 };
1078 PYBIND11_WARNING_POP
1079
1080 PYBIND11_NAMESPACE_BEGIN(accessor_policies)
1081 struct obj_attr {
1082 using key_type = object;
1083 static object get(handle obj, handle key) { return getattr(obj, key); }
1084 static void set(handle obj, handle key, handle val) { setattr(obj, key, val); }
1085 };
1086
1087 struct str_attr {
1088 using key_type = const char *;
1089 static object get(handle obj, const char *key) { return getattr(obj, key); }
1090 static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); }
1091 };
1092
1093 struct generic_item {
1094 using key_type = object;
1095
1096 static object get(handle obj, handle key) {
1097 PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr());
1098 if (!result) {
1099 throw error_already_set();
1100 }
1101 return reinterpret_steal<object>(result);
1102 }
1103
1104 static void set(handle obj, handle key, handle val) {
1105 if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) {
1106 throw error_already_set();
1107 }
1108 }
1109 };
1110
1111 struct sequence_item {
1112 using key_type = size_t;
1113
1114 template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1115 static object get(handle obj, const IdxType &index) {
1116 PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index));
1117 if (!result) {
1118 throw error_already_set();
1119 }
1120 return reinterpret_steal<object>(result);
1121 }
1122
1123 template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1124 static void set(handle obj, const IdxType &index, handle val) {
1125
1126 if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) {
1127 throw error_already_set();
1128 }
1129 }
1130 };
1131
1132 struct list_item {
1133 using key_type = size_t;
1134
1135 template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1136 static object get(handle obj, const IdxType &index) {
1137 PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index));
1138 if (!result) {
1139 throw error_already_set();
1140 }
1141 return reinterpret_borrow<object>(result);
1142 }
1143
1144 template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1145 static void set(handle obj, const IdxType &index, handle val) {
1146
1147 if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
1148 throw error_already_set();
1149 }
1150 }
1151 };
1152
1153 struct tuple_item {
1154 using key_type = size_t;
1155
1156 template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1157 static object get(handle obj, const IdxType &index) {
1158 PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index));
1159 if (!result) {
1160 throw error_already_set();
1161 }
1162 return reinterpret_borrow<object>(result);
1163 }
1164
1165 template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1166 static void set(handle obj, const IdxType &index, handle val) {
1167
1168 if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
1169 throw error_already_set();
1170 }
1171 }
1172 };
1173 PYBIND11_NAMESPACE_END(accessor_policies)
1174
1175
1176 template <typename Policy>
1177 class generic_iterator : public Policy {
1178 using It = generic_iterator;
1179
1180 public:
1181 using difference_type = ssize_t;
1182 using iterator_category = typename Policy::iterator_category;
1183 using value_type = typename Policy::value_type;
1184 using reference = typename Policy::reference;
1185 using pointer = typename Policy::pointer;
1186
1187 generic_iterator() = default;
1188 generic_iterator(handle seq, ssize_t index) : Policy(seq, index) {}
1189
1190
1191 reference operator*() const { return Policy::dereference(); }
1192
1193 reference operator[](difference_type n) const { return *(*this + n); }
1194 pointer operator->() const { return **this; }
1195
1196 It &operator++() {
1197 Policy::increment();
1198 return *this;
1199 }
1200 It operator++(int) {
1201 auto copy = *this;
1202 Policy::increment();
1203 return copy;
1204 }
1205 It &operator--() {
1206 Policy::decrement();
1207 return *this;
1208 }
1209 It operator--(int) {
1210 auto copy = *this;
1211 Policy::decrement();
1212 return copy;
1213 }
1214 It &operator+=(difference_type n) {
1215 Policy::advance(n);
1216 return *this;
1217 }
1218 It &operator-=(difference_type n) {
1219 Policy::advance(-n);
1220 return *this;
1221 }
1222
1223 friend It operator+(const It &a, difference_type n) {
1224 auto copy = a;
1225 return copy += n;
1226 }
1227 friend It operator+(difference_type n, const It &b) { return b + n; }
1228 friend It operator-(const It &a, difference_type n) {
1229 auto copy = a;
1230 return copy -= n;
1231 }
1232 friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); }
1233
1234 friend bool operator==(const It &a, const It &b) { return a.equal(b); }
1235 friend bool operator!=(const It &a, const It &b) { return !(a == b); }
1236 friend bool operator<(const It &a, const It &b) { return b - a > 0; }
1237 friend bool operator>(const It &a, const It &b) { return b < a; }
1238 friend bool operator>=(const It &a, const It &b) { return !(a < b); }
1239 friend bool operator<=(const It &a, const It &b) { return !(a > b); }
1240 };
1241
1242 PYBIND11_NAMESPACE_BEGIN(iterator_policies)
1243
1244 template <typename T>
1245 struct arrow_proxy {
1246 T value;
1247
1248
1249 arrow_proxy(T &&value) noexcept : value(std::move(value)) {}
1250 T *operator->() const { return &value; }
1251 };
1252
1253
1254 class sequence_fast_readonly {
1255 protected:
1256 using iterator_category = std::random_access_iterator_tag;
1257 using value_type = handle;
1258 using reference = const handle;
1259 using pointer = arrow_proxy<const handle>;
1260
1261 sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) {}
1262 sequence_fast_readonly() = default;
1263
1264
1265 reference dereference() const { return *ptr; }
1266 void increment() { ++ptr; }
1267 void decrement() { --ptr; }
1268 void advance(ssize_t n) { ptr += n; }
1269 bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; }
1270 ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; }
1271
1272 private:
1273 PyObject **ptr;
1274 };
1275
1276
1277 class sequence_slow_readwrite {
1278 protected:
1279 using iterator_category = std::random_access_iterator_tag;
1280 using value_type = object;
1281 using reference = sequence_accessor;
1282 using pointer = arrow_proxy<const sequence_accessor>;
1283
1284 sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) {}
1285 sequence_slow_readwrite() = default;
1286
1287 reference dereference() const { return {obj, static_cast<size_t>(index)}; }
1288 void increment() { ++index; }
1289 void decrement() { --index; }
1290 void advance(ssize_t n) { index += n; }
1291 bool equal(const sequence_slow_readwrite &b) const { return index == b.index; }
1292 ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; }
1293
1294 private:
1295 handle obj;
1296 ssize_t index;
1297 };
1298
1299
1300 class dict_readonly {
1301 protected:
1302 using iterator_category = std::forward_iterator_tag;
1303 using value_type = std::pair<handle, handle>;
1304 using reference = const value_type;
1305 using pointer = arrow_proxy<const value_type>;
1306
1307 dict_readonly() = default;
1308 dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }
1309
1310
1311 reference dereference() const { return {key, value}; }
1312 void increment() {
1313 if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) {
1314 pos = -1;
1315 }
1316 }
1317 bool equal(const dict_readonly &b) const { return pos == b.pos; }
1318
1319 private:
1320 handle obj;
1321 PyObject *key = nullptr, *value = nullptr;
1322 ssize_t pos = -1;
1323 };
1324 PYBIND11_NAMESPACE_END(iterator_policies)
1325
1326 #if !defined(PYPY_VERSION)
1327 using tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
1328 using list_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
1329 #else
1330 using tuple_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
1331 using list_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
1332 #endif
1333
1334 using sequence_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
1335 using dict_iterator = generic_iterator<iterator_policies::dict_readonly>;
1336
1337 inline bool PyIterable_Check(PyObject *obj) {
1338 PyObject *iter = PyObject_GetIter(obj);
1339 if (iter) {
1340 Py_DECREF(iter);
1341 return true;
1342 }
1343 PyErr_Clear();
1344 return false;
1345 }
1346
1347 inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
1348 inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }
1349
1350 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
1351 inline bool PyUnicode_Check_Permissive(PyObject *o) {
1352 return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o);
1353 }
1354 # define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive
1355 #else
1356 # define PYBIND11_STR_CHECK_FUN PyUnicode_Check
1357 #endif
1358
1359 inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; }
1360
1361 class kwargs_proxy : public handle {
1362 public:
1363 explicit kwargs_proxy(handle h) : handle(h) {}
1364 };
1365
1366 class args_proxy : public handle {
1367 public:
1368 explicit args_proxy(handle h) : handle(h) {}
1369 kwargs_proxy operator*() const { return kwargs_proxy(*this); }
1370 };
1371
1372
1373 template <typename T>
1374 using is_keyword = std::is_base_of<arg, T>;
1375 template <typename T>
1376 using is_s_unpacking = std::is_same<args_proxy, T>;
1377 template <typename T>
1378 using is_ds_unpacking = std::is_same<kwargs_proxy, T>;
1379 template <typename T>
1380 using is_positional = satisfies_none_of<T, is_keyword, is_s_unpacking, is_ds_unpacking>;
1381 template <typename T>
1382 using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>;
1383
1384
1385 template <return_value_policy policy = return_value_policy::automatic_reference>
1386 class simple_collector;
1387 template <return_value_policy policy = return_value_policy::automatic_reference>
1388 class unpacking_collector;
1389
1390 PYBIND11_NAMESPACE_END(detail)
1391
1392
1393
1394
1395
1396 #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1397 public: \
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)) {}
1408
1409 #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1410 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1411 \
1412 \
1413 Name(const object &o) \
1414 : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1415 if (!m_ptr) \
1416 throw ::pybind11::error_already_set(); \
1417 } \
1418 \
1419 Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1420 if (!m_ptr) \
1421 throw ::pybind11::error_already_set(); \
1422 }
1423
1424 #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \
1425 PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1426 Name() = default;
1427
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 "'")
1432
1433 #define PYBIND11_OBJECT(Name, Parent, CheckFun) \
1434 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1435 \
1436 \
1437 Name(const object &o) : Parent(o) { \
1438 if (m_ptr && !check_(m_ptr)) \
1439 throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1440 } \
1441 \
1442 Name(object &&o) : Parent(std::move(o)) { \
1443 if (m_ptr && !check_(m_ptr)) \
1444 throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1445 }
1446
1447 #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
1448 PYBIND11_OBJECT(Name, Parent, CheckFun) \
1449 Name() = default;
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462 class iterator : public object {
1463 public:
1464 using iterator_category = std::input_iterator_tag;
1465 using difference_type = ssize_t;
1466 using value_type = handle;
1467 using reference = const handle;
1468 using pointer = const handle *;
1469
1470 PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)
1471
1472 iterator &operator++() {
1473 advance();
1474 return *this;
1475 }
1476
1477 iterator operator++(int) {
1478 auto rv = *this;
1479 advance();
1480 return rv;
1481 }
1482
1483
1484 reference operator*() const {
1485 if (m_ptr && !value.ptr()) {
1486 auto &self = const_cast<iterator &>(*this);
1487 self.advance();
1488 }
1489 return value;
1490 }
1491
1492 pointer operator->() const {
1493 operator*();
1494 return &value;
1495 }
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510 static iterator sentinel() { return {}; }
1511
1512 friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); }
1513 friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); }
1514
1515 private:
1516 void advance() {
1517 value = reinterpret_steal<object>(PyIter_Next(m_ptr));
1518 if (value.ptr() == nullptr && PyErr_Occurred()) {
1519 throw error_already_set();
1520 }
1521 }
1522
1523 private:
1524 object value = {};
1525 };
1526
1527 class type : public object {
1528 public:
1529 PYBIND11_OBJECT(type, object, PyType_Check)
1530
1531
1532 static handle handle_of(handle h) { return handle((PyObject *) Py_TYPE(h.ptr())); }
1533
1534
1535 static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); }
1536
1537
1538
1539
1540
1541 template <typename T>
1542 static handle handle_of();
1543
1544
1545
1546
1547 template <typename T>
1548 static type of() {
1549 return type(type::handle_of<T>(), borrowed_t{});
1550 }
1551 };
1552
1553 class iterable : public object {
1554 public:
1555 PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check)
1556 };
1557
1558 class bytes;
1559
1560 class str : public object {
1561 public:
1562 PYBIND11_OBJECT_CVT(str, object, PYBIND11_STR_CHECK_FUN, raw_str)
1563
1564 template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1565 str(const char *c, const SzType &n)
1566 : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1567 if (!m_ptr) {
1568 if (PyErr_Occurred()) {
1569 throw error_already_set();
1570 }
1571 pybind11_fail("Could not allocate string object!");
1572 }
1573 }
1574
1575
1576
1577
1578 str(const char *c = "") : object(PyUnicode_FromString(c), stolen_t{}) {
1579 if (!m_ptr) {
1580 if (PyErr_Occurred()) {
1581 throw error_already_set();
1582 }
1583 pybind11_fail("Could not allocate string object!");
1584 }
1585 }
1586
1587
1588 str(const std::string &s) : str(s.data(), s.size()) {}
1589
1590 #ifdef PYBIND11_HAS_STRING_VIEW
1591
1592 template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>
1593
1594 str(T s) : str(s.data(), s.size()) {}
1595
1596 # ifdef PYBIND11_HAS_U8STRING
1597
1598
1599 str(std::u8string_view s) : str(reinterpret_cast<const char *>(s.data()), s.size()) {}
1600 # endif
1601
1602 #endif
1603
1604 explicit str(const bytes &b);
1605
1606
1607
1608
1609
1610 explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) {
1611 if (!m_ptr) {
1612 throw error_already_set();
1613 }
1614 }
1615
1616
1617 operator std::string() const {
1618 object temp = *this;
1619 if (PyUnicode_Check(m_ptr)) {
1620 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
1621 if (!temp) {
1622 throw error_already_set();
1623 }
1624 }
1625 char *buffer = nullptr;
1626 ssize_t length = 0;
1627 if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {
1628 throw error_already_set();
1629 }
1630 return std::string(buffer, (size_t) length);
1631 }
1632
1633 template <typename... Args>
1634 str format(Args &&...args) const {
1635 return attr("format")(std::forward<Args>(args)...);
1636 }
1637
1638 private:
1639
1640 static PyObject *raw_str(PyObject *op) {
1641 PyObject *str_value = PyObject_Str(op);
1642 return str_value;
1643 }
1644 };
1645
1646
1647 inline namespace literals {
1648
1649
1650
1651 inline str
1652 #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
1653 operator"" _s
1654 #else
1655 operator""_s
1656 #endif
1657 (const char *s, size_t size) {
1658 return {s, size};
1659 }
1660 }
1661
1662
1663
1664 class bytes : public object {
1665 public:
1666 PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK)
1667
1668
1669
1670 bytes(const char *c = "") : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) {
1671 if (!m_ptr) {
1672 pybind11_fail("Could not allocate bytes object!");
1673 }
1674 }
1675
1676 template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1677 bytes(const char *c, const SzType &n)
1678 : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, ssize_t_cast(n)), stolen_t{}) {
1679 if (!m_ptr) {
1680 pybind11_fail("Could not allocate bytes object!");
1681 }
1682 }
1683
1684
1685
1686 bytes(const std::string &s) : bytes(s.data(), s.size()) {}
1687
1688 explicit bytes(const pybind11::str &s);
1689
1690
1691 operator std::string() const { return string_op<std::string>(); }
1692
1693 #ifdef PYBIND11_HAS_STRING_VIEW
1694
1695 template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>
1696
1697 bytes(T s) : bytes(s.data(), s.size()) {}
1698
1699
1700
1701
1702
1703 operator std::string_view() const { return string_op<std::string_view>(); }
1704 #endif
1705 private:
1706 template <typename T>
1707 T string_op() const {
1708 char *buffer = nullptr;
1709 ssize_t length = 0;
1710 if (PyBytes_AsStringAndSize(m_ptr, &buffer, &length) != 0) {
1711 throw error_already_set();
1712 }
1713 return {buffer, static_cast<size_t>(length)};
1714 }
1715 };
1716
1717
1718
1719
1720 inline bytes::bytes(const pybind11::str &s) {
1721 object temp = s;
1722 if (PyUnicode_Check(s.ptr())) {
1723 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));
1724 if (!temp) {
1725 throw error_already_set();
1726 }
1727 }
1728 char *buffer = nullptr;
1729 ssize_t length = 0;
1730 if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {
1731 throw error_already_set();
1732 }
1733 auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));
1734 if (!obj) {
1735 pybind11_fail("Could not allocate bytes object!");
1736 }
1737 m_ptr = obj.release().ptr();
1738 }
1739
1740 inline str::str(const bytes &b) {
1741 char *buffer = nullptr;
1742 ssize_t length = 0;
1743 if (PyBytes_AsStringAndSize(b.ptr(), &buffer, &length) != 0) {
1744 throw error_already_set();
1745 }
1746 auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, length));
1747 if (!obj) {
1748 if (PyErr_Occurred()) {
1749 throw error_already_set();
1750 }
1751 pybind11_fail("Could not allocate string object!");
1752 }
1753 m_ptr = obj.release().ptr();
1754 }
1755
1756
1757
1758 class bytearray : public object {
1759 public:
1760 PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject)
1761
1762 template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1763 bytearray(const char *c, const SzType &n)
1764 : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1765 if (!m_ptr) {
1766 pybind11_fail("Could not allocate bytearray object!");
1767 }
1768 }
1769
1770 bytearray() : bytearray("", 0) {}
1771
1772 explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) {}
1773
1774 size_t size() const { return static_cast<size_t>(PyByteArray_Size(m_ptr)); }
1775
1776 explicit operator std::string() const {
1777 char *buffer = PyByteArray_AS_STRING(m_ptr);
1778 ssize_t size = PyByteArray_GET_SIZE(m_ptr);
1779 return std::string(buffer, static_cast<size_t>(size));
1780 }
1781 };
1782
1783
1784
1785
1786
1787
1788 class none : public object {
1789 public:
1790 PYBIND11_OBJECT(none, object, detail::PyNone_Check)
1791 none() : object(Py_None, borrowed_t{}) {}
1792 };
1793
1794 class ellipsis : public object {
1795 public:
1796 PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check)
1797 ellipsis() : object(Py_Ellipsis, borrowed_t{}) {}
1798 };
1799
1800 class bool_ : public object {
1801 public:
1802 PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool)
1803 bool_() : object(Py_False, borrowed_t{}) {}
1804
1805
1806 bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) {}
1807
1808 operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; }
1809
1810 private:
1811
1812 static PyObject *raw_bool(PyObject *op) {
1813 const auto value = PyObject_IsTrue(op);
1814 if (value == -1) {
1815 return nullptr;
1816 }
1817 return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr();
1818 }
1819 };
1820
1821 PYBIND11_NAMESPACE_BEGIN(detail)
1822
1823
1824
1825
1826 template <typename Unsigned>
1827 Unsigned as_unsigned(PyObject *o) {
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;
1831 }
1832 unsigned long long v = PyLong_AsUnsignedLongLong(o);
1833 return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1834 }
1835 PYBIND11_NAMESPACE_END(detail)
1836
1837 class int_ : public object {
1838 public:
1839 PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long)
1840 int_() : object(PyLong_FromLong(0), stolen_t{}) {}
1841
1842 template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1843
1844 int_(T value) {
1845 if (sizeof(T) <= sizeof(long)) {
1846 if (std::is_signed<T>::value) {
1847 m_ptr = PyLong_FromLong((long) value);
1848 } else {
1849 m_ptr = PyLong_FromUnsignedLong((unsigned long) value);
1850 }
1851 } else {
1852 if (std::is_signed<T>::value) {
1853 m_ptr = PyLong_FromLongLong((long long) value);
1854 } else {
1855 m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value);
1856 }
1857 }
1858 if (!m_ptr) {
1859 pybind11_fail("Could not allocate int object!");
1860 }
1861 }
1862
1863 template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1864
1865 operator T() const {
1866 return std::is_unsigned<T>::value ? detail::as_unsigned<T>(m_ptr)
1867 : sizeof(T) <= sizeof(long) ? (T) PyLong_AsLong(m_ptr)
1868 : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
1869 }
1870 };
1871
1872 class float_ : public object {
1873 public:
1874 PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)
1875
1876
1877 float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1878 if (!m_ptr) {
1879 pybind11_fail("Could not allocate float object!");
1880 }
1881 }
1882
1883 float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1884 if (!m_ptr) {
1885 pybind11_fail("Could not allocate float object!");
1886 }
1887 }
1888
1889 operator float() const { return (float) PyFloat_AsDouble(m_ptr); }
1890
1891 operator double() const { return (double) PyFloat_AsDouble(m_ptr); }
1892 };
1893
1894 class weakref : public object {
1895 public:
1896 PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref)
1897 explicit weakref(handle obj, handle callback = {})
1898 : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) {
1899 if (!m_ptr) {
1900 if (PyErr_Occurred()) {
1901 throw error_already_set();
1902 }
1903 pybind11_fail("Could not allocate weak reference!");
1904 }
1905 }
1906
1907 private:
1908 static PyObject *raw_weakref(PyObject *o) { return PyWeakref_NewRef(o, nullptr); }
1909 };
1910
1911 class slice : public object {
1912 public:
1913 PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check)
1914 slice(handle start, handle stop, handle step)
1915 : object(PySlice_New(start.ptr(), stop.ptr(), step.ptr()), stolen_t{}) {
1916 if (!m_ptr) {
1917 pybind11_fail("Could not allocate slice object!");
1918 }
1919 }
1920
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)) {}
1924 #else
1925 slice(ssize_t start_, ssize_t stop_, ssize_t step_)
1926 : slice(int_(start_), int_(stop_), int_(step_)) {}
1927 #endif
1928
1929 bool
1930 compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const {
1931 return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1932 (ssize_t) length,
1933 (ssize_t *) start,
1934 (ssize_t *) stop,
1935 (ssize_t *) step,
1936 (ssize_t *) slicelength)
1937 == 0;
1938 }
1939 bool compute(
1940 ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const {
1941 return PySlice_GetIndicesEx(
1942 (PYBIND11_SLICE_OBJECT *) m_ptr, length, start, stop, step, slicelength)
1943 == 0;
1944 }
1945
1946 private:
1947 template <typename T>
1948 static object index_to_object(T index) {
1949 return index ? object(int_(*index)) : object(none());
1950 }
1951 };
1952
1953 class capsule : public object {
1954 public:
1955 PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact)
1956 PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()")
1957 capsule(PyObject *ptr, bool is_borrowed)
1958 : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) {}
1959
1960 explicit capsule(const void *value,
1961 const char *name = nullptr,
1962 PyCapsule_Destructor destructor = nullptr)
1963 : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) {
1964 if (!m_ptr) {
1965 throw error_already_set();
1966 }
1967 }
1968
1969 PYBIND11_DEPRECATED("Please use the ctor with value, name, destructor args")
1970 capsule(const void *value, PyCapsule_Destructor destructor)
1971 : object(PyCapsule_New(const_cast<void *>(value), nullptr, destructor), stolen_t{}) {
1972 if (!m_ptr) {
1973 throw error_already_set();
1974 }
1975 }
1976
1977
1978 capsule(const void *value, void (*destructor)(void *)) {
1979 initialize_with_void_ptr_destructor(value, nullptr, destructor);
1980 }
1981
1982 capsule(const void *value, const char *name, void (*destructor)(void *)) {
1983 initialize_with_void_ptr_destructor(value, name, destructor);
1984 }
1985
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) {
1991 throw error_already_set();
1992 }
1993 destructor();
1994 });
1995
1996 if (!m_ptr) {
1997 throw error_already_set();
1998 }
1999 }
2000
2001 template <typename T>
2002 operator T *() const {
2003 return get_pointer<T>();
2004 }
2005
2006
2007 template <typename T = void>
2008 T *get_pointer() const {
2009 const auto *name = this->name();
2010 T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));
2011 if (!result) {
2012 throw error_already_set();
2013 }
2014 return result;
2015 }
2016
2017
2018 void set_pointer(const void *value) {
2019 if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0) {
2020 throw error_already_set();
2021 }
2022 }
2023
2024 const char *name() const {
2025 const char *name = PyCapsule_GetName(m_ptr);
2026 if ((name == nullptr) && PyErr_Occurred()) {
2027 throw error_already_set();
2028 }
2029 return name;
2030 }
2031
2032
2033 void set_name(const char *new_name) {
2034 if (PyCapsule_SetName(m_ptr, new_name) != 0) {
2035 throw error_already_set();
2036 }
2037 }
2038
2039 private:
2040 static const char *get_name_in_error_scope(PyObject *o) {
2041 error_scope error_guard;
2042
2043 const char *name = PyCapsule_GetName(o);
2044 if ((name == nullptr) && PyErr_Occurred()) {
2045
2046 PyErr_WriteUnraisable(o);
2047 }
2048
2049 return name;
2050 }
2051
2052 void initialize_with_void_ptr_destructor(const void *value,
2053 const char *name,
2054 void (*destructor)(void *)) {
2055 m_ptr = PyCapsule_New(const_cast<void *>(value), name, [](PyObject *o) {
2056
2057 error_scope error_guard;
2058 auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o));
2059 if (destructor == nullptr && PyErr_Occurred()) {
2060 throw error_already_set();
2061 }
2062 const char *name = get_name_in_error_scope(o);
2063 void *ptr = PyCapsule_GetPointer(o, name);
2064 if (ptr == nullptr) {
2065 throw error_already_set();
2066 }
2067
2068 if (destructor != nullptr) {
2069 destructor(ptr);
2070 }
2071 });
2072
2073 if (!m_ptr || PyCapsule_SetContext(m_ptr, reinterpret_cast<void *>(destructor)) != 0) {
2074 throw error_already_set();
2075 }
2076 }
2077 };
2078
2079 class tuple : public object {
2080 public:
2081 PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple)
2082 template <typename SzType = ssize_t,
2083 detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
2084
2085 explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) {
2086 if (!m_ptr) {
2087 pybind11_fail("Could not allocate tuple object!");
2088 }
2089 }
2090 size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
2091 bool empty() const { return size() == 0; }
2092 detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }
2093 template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
2094 detail::item_accessor operator[](T &&o) const {
2095 return object::operator[](std::forward<T>(o));
2096 }
2097 detail::tuple_iterator begin() const { return {*this, 0}; }
2098 detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }
2099 };
2100
2101
2102
2103
2104 template <typename... Args>
2105 constexpr bool args_are_all_keyword_or_ds() {
2106 return detail::all_of<detail::is_keyword_or_ds<Args>...>::value;
2107 }
2108
2109 class dict : public object {
2110 public:
2111 PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)
2112 dict() : object(PyDict_New(), stolen_t{}) {
2113 if (!m_ptr) {
2114 pybind11_fail("Could not allocate dict object!");
2115 }
2116 }
2117 template <typename... Args,
2118 typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>,
2119
2120
2121 typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
2122 explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) {}
2123
2124 size_t size() const { return (size_t) PyDict_Size(m_ptr); }
2125 bool empty() const { return size() == 0; }
2126 detail::dict_iterator begin() const { return {*this, 0}; }
2127 detail::dict_iterator end() const { return {}; }
2128 void clear() { PyDict_Clear(ptr()); }
2129 template <typename T>
2130 bool contains(T &&key) const {
2131 auto result = PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr());
2132 if (result == -1) {
2133 throw error_already_set();
2134 }
2135 return result == 1;
2136 }
2137
2138 private:
2139
2140 static PyObject *raw_dict(PyObject *op) {
2141 if (PyDict_Check(op)) {
2142 return handle(op).inc_ref().ptr();
2143 }
2144 return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
2145 }
2146 };
2147
2148 class sequence : public object {
2149 public:
2150 PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)
2151 size_t size() const {
2152 ssize_t result = PySequence_Size(m_ptr);
2153 if (result == -1) {
2154 throw error_already_set();
2155 }
2156 return (size_t) result;
2157 }
2158 bool empty() const { return size() == 0; }
2159 detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
2160 template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
2161 detail::item_accessor operator[](T &&o) const {
2162 return object::operator[](std::forward<T>(o));
2163 }
2164 detail::sequence_iterator begin() const { return {*this, 0}; }
2165 detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; }
2166 };
2167
2168 class list : public object {
2169 public:
2170 PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
2171 template <typename SzType = ssize_t,
2172 detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
2173
2174 explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) {
2175 if (!m_ptr) {
2176 pybind11_fail("Could not allocate list object!");
2177 }
2178 }
2179 size_t size() const { return (size_t) PyList_Size(m_ptr); }
2180 bool empty() const { return size() == 0; }
2181 detail::list_accessor operator[](size_t index) const { return {*this, index}; }
2182 template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
2183 detail::item_accessor operator[](T &&o) const {
2184 return object::operator[](std::forward<T>(o));
2185 }
2186 detail::list_iterator begin() const { return {*this, 0}; }
2187 detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
2188 template <typename T>
2189 void append(T &&val) {
2190 if (PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) != 0) {
2191 throw error_already_set();
2192 }
2193 }
2194 template <typename IdxType,
2195 typename ValType,
2196 detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
2197 void insert(const IdxType &index, ValType &&val) {
2198 if (PyList_Insert(m_ptr,
2199 ssize_t_cast(index),
2200 detail::object_or_cast(std::forward<ValType>(val)).ptr())
2201 != 0) {
2202 throw error_already_set();
2203 }
2204 }
2205 void clear() {
2206 if (PyList_SetSlice(m_ptr, 0, PyList_Size(m_ptr), nullptr) == -1) {
2207 throw error_already_set();
2208 }
2209 }
2210 };
2211
2212 class args : public tuple {
2213 PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check)
2214 };
2215 class kwargs : public dict {
2216 PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check)
2217 };
2218
2219 class anyset : public object {
2220 public:
2221 PYBIND11_OBJECT(anyset, object, PyAnySet_Check)
2222 size_t size() const { return static_cast<size_t>(PySet_Size(m_ptr)); }
2223 bool empty() const { return size() == 0; }
2224 template <typename T>
2225 bool contains(T &&val) const {
2226 auto result = PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
2227 if (result == -1) {
2228 throw error_already_set();
2229 }
2230 return result == 1;
2231 }
2232 };
2233
2234 class set : public anyset {
2235 public:
2236 PYBIND11_OBJECT_CVT(set, anyset, PySet_Check, PySet_New)
2237 set() : anyset(PySet_New(nullptr), stolen_t{}) {
2238 if (!m_ptr) {
2239 pybind11_fail("Could not allocate set object!");
2240 }
2241 }
2242 template <typename T>
2243 bool add(T &&val) {
2244 return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
2245 }
2246 void clear() { PySet_Clear(m_ptr); }
2247 };
2248
2249 class frozenset : public anyset {
2250 public:
2251 PYBIND11_OBJECT_CVT(frozenset, anyset, PyFrozenSet_Check, PyFrozenSet_New)
2252 };
2253
2254 class function : public object {
2255 public:
2256 PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)
2257 handle cpp_function() const {
2258 handle fun = detail::get_function(m_ptr);
2259 if (fun && PyCFunction_Check(fun.ptr())) {
2260 return fun;
2261 }
2262 return handle();
2263 }
2264 bool is_cpp_function() const { return (bool) cpp_function(); }
2265 };
2266
2267 class staticmethod : public object {
2268 public:
2269 PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)
2270 };
2271
2272 class buffer : public object {
2273 public:
2274 PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)
2275
2276 buffer_info request(bool writable = false) const {
2277 int flags = PyBUF_STRIDES | PyBUF_FORMAT;
2278 if (writable) {
2279 flags |= PyBUF_WRITABLE;
2280 }
2281 auto *view = new Py_buffer();
2282 if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
2283 delete view;
2284 throw error_already_set();
2285 }
2286 return buffer_info(view);
2287 }
2288 };
2289
2290 class memoryview : public object {
2291 public:
2292 PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303 explicit memoryview(const buffer_info &info) {
2304 if (!info.view()) {
2305 pybind11_fail("Prohibited to create memoryview without Py_buffer");
2306 }
2307
2308 m_ptr = (info.view()->obj) ? PyMemoryView_FromObject(info.view()->obj)
2309 : PyMemoryView_FromBuffer(info.view());
2310 if (!m_ptr) {
2311 pybind11_fail("Unable to create memoryview from buffer descriptor");
2312 }
2313 }
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339 static memoryview from_buffer(void *ptr,
2340 ssize_t itemsize,
2341 const char *format,
2342 detail::any_container<ssize_t> shape,
2343 detail::any_container<ssize_t> strides,
2344 bool readonly = false);
2345
2346 static memoryview from_buffer(const void *ptr,
2347 ssize_t itemsize,
2348 const char *format,
2349 detail::any_container<ssize_t> shape,
2350 detail::any_container<ssize_t> strides) {
2351 return memoryview::from_buffer(
2352 const_cast<void *>(ptr), itemsize, format, std::move(shape), std::move(strides), true);
2353 }
2354
2355 template <typename T>
2356 static memoryview from_buffer(T *ptr,
2357 detail::any_container<ssize_t> shape,
2358 detail::any_container<ssize_t> strides,
2359 bool readonly = false) {
2360 return memoryview::from_buffer(reinterpret_cast<void *>(ptr),
2361 sizeof(T),
2362 format_descriptor<T>::value,
2363 std::move(shape),
2364 std::move(strides),
2365 readonly);
2366 }
2367
2368 template <typename T>
2369 static memoryview from_buffer(const T *ptr,
2370 detail::any_container<ssize_t> shape,
2371 detail::any_container<ssize_t> strides) {
2372 return memoryview::from_buffer(
2373 const_cast<T *>(ptr), std::move(shape), std::move(strides), true);
2374 }
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388 static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) {
2389 PyObject *ptr = PyMemoryView_FromMemory(
2390 reinterpret_cast<char *>(mem), size, (readonly) ? PyBUF_READ : PyBUF_WRITE);
2391 if (!ptr) {
2392 pybind11_fail("Could not allocate memoryview object!");
2393 }
2394 return memoryview(object(ptr, stolen_t{}));
2395 }
2396
2397 static memoryview from_memory(const void *mem, ssize_t size) {
2398 return memoryview::from_memory(const_cast<void *>(mem), size, true);
2399 }
2400
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);
2404 }
2405 #endif
2406 };
2407
2408
2409 inline memoryview memoryview::from_buffer(void *ptr,
2410 ssize_t itemsize,
2411 const char *format,
2412 detail::any_container<ssize_t> shape,
2413 detail::any_container<ssize_t> strides,
2414 bool readonly) {
2415 size_t ndim = shape->size();
2416 if (ndim != strides->size()) {
2417 pybind11_fail("memoryview: shape length doesn't match strides length");
2418 }
2419 ssize_t size = ndim != 0u ? 1 : 0;
2420 for (size_t i = 0; i < ndim; ++i) {
2421 size *= (*shape)[i];
2422 }
2423 Py_buffer view;
2424 view.buf = ptr;
2425 view.obj = nullptr;
2426 view.len = size * itemsize;
2427 view.readonly = static_cast<int>(readonly);
2428 view.itemsize = itemsize;
2429 view.format = const_cast<char *>(format);
2430 view.ndim = static_cast<int>(ndim);
2431 view.shape = shape->data();
2432 view.strides = strides->data();
2433 view.suboffsets = nullptr;
2434 view.internal = nullptr;
2435 PyObject *obj = PyMemoryView_FromBuffer(&view);
2436 if (!obj) {
2437 throw error_already_set();
2438 }
2439 return memoryview(object(obj, stolen_t{}));
2440 }
2441
2442
2443
2444
2445
2446
2447
2448 inline size_t len(handle h) {
2449 ssize_t result = PyObject_Length(h.ptr());
2450 if (result < 0) {
2451 throw error_already_set();
2452 }
2453 return (size_t) result;
2454 }
2455
2456
2457
2458 inline size_t len_hint(handle h) {
2459 ssize_t result = PyObject_LengthHint(h.ptr(), 0);
2460 if (result < 0) {
2461
2462
2463 PyErr_Clear();
2464 return 0;
2465 }
2466 return (size_t) result;
2467 }
2468
2469 inline str repr(handle h) {
2470 PyObject *str_value = PyObject_Repr(h.ptr());
2471 if (!str_value) {
2472 throw error_already_set();
2473 }
2474 return reinterpret_steal<str>(str_value);
2475 }
2476
2477 inline iterator iter(handle obj) {
2478 PyObject *result = PyObject_GetIter(obj.ptr());
2479 if (!result) {
2480 throw error_already_set();
2481 }
2482 return reinterpret_steal<iterator>(result);
2483 }
2484
2485
2486 PYBIND11_NAMESPACE_BEGIN(detail)
2487 template <typename D>
2488 iterator object_api<D>::begin() const {
2489 return iter(derived());
2490 }
2491 template <typename D>
2492 iterator object_api<D>::end() const {
2493 return iterator::sentinel();
2494 }
2495 template <typename D>
2496 item_accessor object_api<D>::operator[](handle key) const {
2497 return {derived(), reinterpret_borrow<object>(key)};
2498 }
2499 template <typename D>
2500 item_accessor object_api<D>::operator[](object &&key) const {
2501 return {derived(), std::move(key)};
2502 }
2503 template <typename D>
2504 item_accessor object_api<D>::operator[](const char *key) const {
2505 return {derived(), pybind11::str(key)};
2506 }
2507 template <typename D>
2508 obj_attr_accessor object_api<D>::attr(handle key) const {
2509 return {derived(), reinterpret_borrow<object>(key)};
2510 }
2511 template <typename D>
2512 obj_attr_accessor object_api<D>::attr(object &&key) const {
2513 return {derived(), std::move(key)};
2514 }
2515 template <typename D>
2516 str_attr_accessor object_api<D>::attr(const char *key) const {
2517 return {derived(), key};
2518 }
2519 template <typename D>
2520 args_proxy object_api<D>::operator*() const {
2521 return args_proxy(derived().ptr());
2522 }
2523 template <typename D>
2524 template <typename T>
2525 bool object_api<D>::contains(T &&item) const {
2526 return attr("__contains__")(std::forward<T>(item)).template cast<bool>();
2527 }
2528
2529 template <typename D>
2530 pybind11::str object_api<D>::str() const {
2531 return pybind11::str(derived());
2532 }
2533
2534 template <typename D>
2535 str_attr_accessor object_api<D>::doc() const {
2536 return attr("__doc__");
2537 }
2538
2539 template <typename D>
2540 handle object_api<D>::get_type() const {
2541 return type::handle_of(derived());
2542 }
2543
2544 template <typename D>
2545 bool object_api<D>::rich_compare(object_api const &other, int value) const {
2546 int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
2547 if (rv == -1) {
2548 throw error_already_set();
2549 }
2550 return rv == 1;
2551 }
2552
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(); \
2559 return result; \
2560 }
2561
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(); \
2568 return result; \
2569 }
2570
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(); \
2577 return result; \
2578 }
2579
2580 PYBIND11_MATH_OPERATOR_UNARY(operator~, PyNumber_Invert)
2581 PYBIND11_MATH_OPERATOR_UNARY(operator-, PyNumber_Negative)
2582 PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)
2583 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator+=, PyNumber_InPlaceAdd)
2584 PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)
2585 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator-=, PyNumber_InPlaceSubtract)
2586 PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)
2587 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator*=, PyNumber_InPlaceMultiply)
2588 PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)
2589 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator/=, PyNumber_InPlaceTrueDivide)
2590 PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)
2591 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator|=, PyNumber_InPlaceOr)
2592 PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)
2593 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator&=, PyNumber_InPlaceAnd)
2594 PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)
2595 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator^=, PyNumber_InPlaceXor)
2596 PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)
2597 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator<<=, PyNumber_InPlaceLshift)
2598 PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)
2599 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator>>=, PyNumber_InPlaceRshift)
2600
2601 #undef PYBIND11_MATH_OPERATOR_UNARY
2602 #undef PYBIND11_MATH_OPERATOR_BINARY
2603 #undef PYBIND11_MATH_OPERATOR_BINARY_INPLACE
2604
2605 PYBIND11_NAMESPACE_END(detail)
2606 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)