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