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