pytypes.h
Go to the documentation of this file.
1 /*
2  pybind11/pytypes.h: Convenience wrapper classes for basic Python types
3 
4  Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5 
6  All rights reserved. Use of this source code is governed by a
7  BSD-style license that can be found in the LICENSE file.
8 */
9 
10 #pragma once
11 
12 #include "detail/common.h"
13 #include "buffer_info.h"
14 
15 #include <assert.h>
16 #include <cstddef>
17 #include <exception>
18 #include <frameobject.h>
19 #include <iterator>
20 #include <memory>
21 #include <string>
22 #include <type_traits>
23 #include <typeinfo>
24 #include <utility>
25 
26 #if defined(PYBIND11_HAS_OPTIONAL)
27 # include <optional>
28 #endif
29 
30 #ifdef PYBIND11_HAS_STRING_VIEW
31 # include <string_view>
32 #endif
33 
35 
37 
38 /* A few forward declarations */
39 class handle;
40 class object;
41 class str;
42 class iterator;
43 class type;
44 struct arg;
45 struct arg_v;
46 
48 class args_proxy;
49 bool isinstance_generic(handle obj, const std::type_info &tp);
50 
51 // Accessor forward declarations
52 template <typename Policy>
53 class accessor;
54 namespace accessor_policies {
55 struct obj_attr;
56 struct str_attr;
57 struct generic_item;
58 struct sequence_item;
59 struct list_item;
60 struct tuple_item;
61 } // namespace accessor_policies
68 
70 class pyobject_tag {};
71 template <typename T>
72 using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
73 
78 template <typename Derived>
79 class object_api : public pyobject_tag {
80  const Derived &derived() const { return static_cast<const Derived &>(*this); }
81 
82 public:
87  iterator begin() const;
89  iterator end() const;
90 
99  item_accessor operator[](object &&key) const;
101  item_accessor operator[](const char *key) const;
102 
111  obj_attr_accessor attr(object &&key) const;
113  str_attr_accessor attr(const char *key) const;
114 
121  args_proxy operator*() const;
122 
124  template <typename T>
125  bool contains(T &&item) const;
126 
138  typename... Args>
139  object operator()(Args &&...args) const;
141  typename... Args>
142  PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)")
143  object call(Args &&...args) const;
144 
146  bool is(object_api const &other) const { return derived().ptr() == other.derived().ptr(); }
148  bool is_none() const { return derived().ptr() == Py_None; }
150  bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); }
151  bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); }
152  bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); }
153  bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); }
154  bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); }
155  bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); }
156 
157  object operator-() const;
158  object operator~() const;
159  object operator+(object_api const &other) const;
160  object operator+=(object_api const &other);
161  object operator-(object_api const &other) const;
162  object operator-=(object_api const &other);
163  object operator*(object_api const &other) const;
164  object operator*=(object_api const &other);
165  object operator/(object_api const &other) const;
166  object operator/=(object_api const &other);
167  object operator|(object_api const &other) const;
168  object operator|=(object_api const &other);
169  object operator&(object_api const &other) const;
170  object operator&=(object_api const &other);
171  object operator^(object_api const &other) const;
172  object operator^=(object_api const &other);
173  object operator<<(object_api const &other) const;
174  object operator<<=(object_api const &other);
175  object operator>>(object_api const &other) const;
176  object operator>>=(object_api const &other);
177 
178  PYBIND11_DEPRECATED("Use py::str(obj) instead")
179  pybind11::str str() const;
180 
182  str_attr_accessor doc() const;
183 
185  int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); }
186 
187  // TODO PYBIND11_DEPRECATED(
188  // "Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()")
189  handle get_type() const;
190 
191 private:
192  bool rich_compare(object_api const &other, int value) const;
193 };
194 
195 template <typename T>
196 using is_pyobj_ptr_or_nullptr_t = detail::any_of<std::is_same<T, PyObject *>,
197  std::is_same<T, PyObject *const>,
198  std::is_same<T, std::nullptr_t>>;
199 
201 
202 #if !defined(PYBIND11_HANDLE_REF_DEBUG) && !defined(NDEBUG)
203 # define PYBIND11_HANDLE_REF_DEBUG
204 #endif
205 
217 class handle : public detail::object_api<handle> {
218 public:
220  handle() = default;
221 
224  template <typename T,
226  // NOLINTNEXTLINE(google-explicit-constructor)
228 
230  template <
231  typename T,
232  detail::enable_if_t<detail::all_of<detail::none_of<std::is_base_of<handle, T>,
233  detail::is_pyobj_ptr_or_nullptr_t<T>>,
234  std::is_convertible<T, PyObject *>>::value,
235  int>
236  = 0>
237  // NOLINTNEXTLINE(google-explicit-constructor)
238  handle(T &obj) : m_ptr(obj) {}
239 
241  PyObject *ptr() const { return m_ptr; }
242  PyObject *&ptr() { return m_ptr; }
243 
249  const handle &inc_ref() const & {
250 #ifdef PYBIND11_HANDLE_REF_DEBUG
251  inc_ref_counter(1);
252 #endif
253 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
254  if (m_ptr != nullptr && !PyGILState_Check()) {
255  throw_gilstate_error("pybind11::handle::inc_ref()");
256  }
257 #endif
258  Py_XINCREF(m_ptr);
259  return *this;
260  }
261 
267  const handle &dec_ref() const & {
268 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
269  if (m_ptr != nullptr && !PyGILState_Check()) {
270  throw_gilstate_error("pybind11::handle::dec_ref()");
271  }
272 #endif
273  Py_XDECREF(m_ptr);
274  return *this;
275  }
276 
281  template <typename T>
282  T cast() const;
284  explicit operator bool() const { return m_ptr != nullptr; }
289  PYBIND11_DEPRECATED("Use obj1.is(obj2) instead")
290  bool operator==(const handle &h) const { return m_ptr == h.m_ptr; }
291  PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead")
292  bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }
293  PYBIND11_DEPRECATED("Use handle::operator bool() instead")
294  bool check() const { return m_ptr != nullptr; }
295 
296 protected:
297  PyObject *m_ptr = nullptr;
298 
299 private:
300 #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
301  void throw_gilstate_error(const std::string &function_name) const {
302  fprintf(
303  stderr,
304  "%s is being called while the GIL is either not held or invalid. Please see "
305  "https://pybind11.readthedocs.io/en/stable/advanced/"
306  "misc.html#common-sources-of-global-interpreter-lock-errors for debugging advice.\n"
307  "If you are convinced there is no bug in your code, you can #define "
308  "PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF"
309  "to disable this check. In that case you have to ensure this #define is consistently "
310  "used for all translation units linked into a given pybind11 extension, otherwise "
311  "there will be ODR violations.",
312  function_name.c_str());
313  fflush(stderr);
314  if (Py_TYPE(m_ptr)->tp_name != nullptr) {
315  fprintf(stderr,
316  "The failing %s call was triggered on a %s object.\n",
317  function_name.c_str(),
318  Py_TYPE(m_ptr)->tp_name);
319  fflush(stderr);
320  }
321  throw std::runtime_error(function_name + " PyGILState_Check() failure.");
322  }
323 #endif
324 
325 #ifdef PYBIND11_HANDLE_REF_DEBUG
327  thread_local std::size_t counter = 0;
328  counter += add;
329  return counter;
330  }
331 
332 public:
334 #endif
335 };
336 
347 class object : public handle {
348 public:
349  object() = default;
350  PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()")
351  object(handle h, bool is_borrowed) : handle(h) {
352  if (is_borrowed) {
354  }
355  }
357  object(const object &o) : handle(o) { inc_ref(); }
359  object(object &&other) noexcept : handle(other) { other.m_ptr = nullptr; }
361  ~object() { dec_ref(); }
362 
369  PyObject *tmp = m_ptr;
370  m_ptr = nullptr;
371  return handle(tmp);
372  }
373 
374  object &operator=(const object &other) {
375  // Skip inc_ref and dec_ref if both objects are the same
376  if (!this->is(other)) {
377  other.inc_ref();
378  // Use temporary variable to ensure `*this` remains valid while
379  // `Py_XDECREF` executes, in case `*this` is accessible from Python.
380  handle temp(m_ptr);
381  m_ptr = other.m_ptr;
382  temp.dec_ref();
383  }
384  return *this;
385  }
386 
387  object &operator=(object &&other) noexcept {
388  if (this != &other) {
389  handle temp(m_ptr);
390  m_ptr = other.m_ptr;
391  other.m_ptr = nullptr;
392  temp.dec_ref();
393  }
394  return *this;
395  }
396 
397 #define PYBIND11_INPLACE_OP(iop) \
398  object iop(object_api const &other) { return operator=(handle::iop(other)); }
399 
400  PYBIND11_INPLACE_OP(operator+=)
401  PYBIND11_INPLACE_OP(operator-=)
402  PYBIND11_INPLACE_OP(operator*=)
403  PYBIND11_INPLACE_OP(operator/=)
404  PYBIND11_INPLACE_OP(operator|=)
405  PYBIND11_INPLACE_OP(operator&=)
406  PYBIND11_INPLACE_OP(operator^=)
407  PYBIND11_INPLACE_OP(operator<<=)
408  PYBIND11_INPLACE_OP(operator>>=)
409 #undef PYBIND11_INPLACE_OP
410 
411  // Calling cast() on an object lvalue just copies (via handle::cast)
412  template <typename T>
413  T cast() const &;
414  // Calling on an object rvalue does a move, if needed and/or possible
415  template <typename T>
416  T cast() &&;
417 
418 protected:
419  // Tags for choosing constructors from raw PyObject *
420  struct borrowed_t {};
421  struct stolen_t {};
422 
424  template <typename T>
425  friend T reinterpret_borrow(handle);
426  template <typename T>
427  friend T reinterpret_steal(handle);
429 
430 public:
431  // Only accessible from derived classes and the reinterpret_* functions
434 };
435 
449 template <typename T>
451  return {h, object::borrowed_t{}};
452 }
453 
462 template <typename T>
464  return {h, object::stolen_t{}};
465 }
466 
468 
469 // Equivalent to obj.__class__.__name__ (or obj.__name__ if obj is a class).
470 inline const char *obj_class_name(PyObject *obj) {
471  if (PyType_Check(obj)) {
472  return reinterpret_cast<PyTypeObject *>(obj)->tp_name;
473  }
474  return Py_TYPE(obj)->tp_name;
475 }
476 
477 std::string error_string();
478 
479 // The code in this struct is very unusual, to minimize the chances of
480 // masking bugs (elsewhere) by errors during the error handling (here).
481 // This is meant to be a lifeline for troubleshooting long-running processes
482 // that crash under conditions that are virtually impossible to reproduce.
483 // Low-level implementation alternatives are preferred to higher-level ones
484 // that might raise cascading exceptions. Last-ditch-kind-of attempts are made
485 // to report as much of the original error as possible, even if there are
486 // secondary issues obtaining some of the details.
488  // This comment only applies to Python <= 3.11:
489  // Immediate normalization is long-established behavior (starting with
490  // https://github.com/pybind/pybind11/commit/135ba8deafb8bf64a15b24d1513899eb600e2011
491  // from Sep 2016) and safest. Normalization could be deferred, but this could mask
492  // errors elsewhere, the performance gain is very minor in typical situations
493  // (usually the dominant bottleneck is EH unwinding), and the implementation here
494  // would be more complex.
495  // Starting with Python 3.12, PyErr_Fetch() normalizes exceptions immediately.
496  // Any errors during normalization are tracked under __notes__.
497  explicit error_fetch_and_normalize(const char *called) {
498  PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
499  if (!m_type) {
500  pybind11_fail("Internal error: " + std::string(called)
501  + " called while "
502  "Python error indicator not set.");
503  }
504  const char *exc_type_name_orig = detail::obj_class_name(m_type.ptr());
505  if (exc_type_name_orig == nullptr) {
506  pybind11_fail("Internal error: " + std::string(called)
507  + " failed to obtain the name "
508  "of the original active exception type.");
509  }
510  m_lazy_error_string = exc_type_name_orig;
511 #if PY_VERSION_HEX >= 0x030C0000
512  // The presence of __notes__ is likely due to exception normalization
513  // errors, although that is not necessarily true, therefore insert a
514  // hint only:
515  if (PyObject_HasAttrString(m_value.ptr(), "__notes__")) {
516  m_lazy_error_string += "[WITH __notes__]";
517  }
518 #else
519  // PyErr_NormalizeException() may change the exception type if there are cascading
520  // failures. This can potentially be extremely confusing.
521  PyErr_NormalizeException(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
522  if (m_type.ptr() == nullptr) {
523  pybind11_fail("Internal error: " + std::string(called)
524  + " failed to normalize the "
525  "active exception.");
526  }
527  const char *exc_type_name_norm = detail::obj_class_name(m_type.ptr());
528  if (exc_type_name_norm == nullptr) {
529  pybind11_fail("Internal error: " + std::string(called)
530  + " failed to obtain the name "
531  "of the normalized active exception type.");
532  }
533 # if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x07030a00
534  // This behavior runs the risk of masking errors in the error handling, but avoids a
535  // conflict with PyPy, which relies on the normalization here to change OSError to
536  // FileNotFoundError (https://github.com/pybind/pybind11/issues/4075).
537  m_lazy_error_string = exc_type_name_norm;
538 # else
539  if (exc_type_name_norm != m_lazy_error_string) {
540  std::string msg = std::string(called)
541  + ": MISMATCH of original and normalized "
542  "active exception types: ";
543  msg += "ORIGINAL ";
545  msg += " REPLACED BY ";
546  msg += exc_type_name_norm;
547  msg += ": " + format_value_and_trace();
549  }
550 # endif
551 #endif
552  }
553 
556 
557  std::string format_value_and_trace() const {
558  std::string result;
559  std::string message_error_string;
560  if (m_value) {
561  auto value_str = reinterpret_steal<object>(PyObject_Str(m_value.ptr()));
562  constexpr const char *message_unavailable_exc
563  = "<MESSAGE UNAVAILABLE DUE TO ANOTHER EXCEPTION>";
564  if (!value_str) {
565  message_error_string = detail::error_string();
566  result = message_unavailable_exc;
567  } else {
568  // Not using `value_str.cast<std::string>()`, to not potentially throw a secondary
569  // error_already_set that will then result in process termination (#4288).
570  auto value_bytes = reinterpret_steal<object>(
571  PyUnicode_AsEncodedString(value_str.ptr(), "utf-8", "backslashreplace"));
572  if (!value_bytes) {
573  message_error_string = detail::error_string();
574  result = message_unavailable_exc;
575  } else {
576  char *buffer = nullptr;
577  Py_ssize_t length = 0;
578  if (PyBytes_AsStringAndSize(value_bytes.ptr(), &buffer, &length) == -1) {
579  message_error_string = detail::error_string();
580  result = message_unavailable_exc;
581  } else {
582  result = std::string(buffer, static_cast<std::size_t>(length));
583  }
584  }
585  }
586 #if PY_VERSION_HEX >= 0x030B0000
587  auto notes
588  = reinterpret_steal<object>(PyObject_GetAttrString(m_value.ptr(), "__notes__"));
589  if (!notes) {
590  PyErr_Clear(); // No notes is good news.
591  } else {
592  auto len_notes = PyList_Size(notes.ptr());
593  if (len_notes < 0) {
594  result += "\nFAILURE obtaining len(__notes__): " + detail::error_string();
595  } else {
596  result += "\n__notes__ (len=" + std::to_string(len_notes) + "):";
597  for (ssize_t i = 0; i < len_notes; i++) {
598  PyObject *note = PyList_GET_ITEM(notes.ptr(), i);
599  auto note_bytes = reinterpret_steal<object>(
600  PyUnicode_AsEncodedString(note, "utf-8", "backslashreplace"));
601  if (!note_bytes) {
602  result += "\nFAILURE obtaining __notes__[" + std::to_string(i)
603  + "]: " + detail::error_string();
604  } else {
605  char *buffer = nullptr;
606  Py_ssize_t length = 0;
607  if (PyBytes_AsStringAndSize(note_bytes.ptr(), &buffer, &length)
608  == -1) {
609  result += "\nFAILURE formatting __notes__[" + std::to_string(i)
610  + "]: " + detail::error_string();
611  } else {
612  result += '\n';
613  result += std::string(buffer, static_cast<std::size_t>(length));
614  }
615  }
616  }
617  }
618  }
619 #endif
620  } else {
621  result = "<MESSAGE UNAVAILABLE>";
622  }
623  if (result.empty()) {
624  result = "<EMPTY MESSAGE>";
625  }
626 
627  bool have_trace = false;
628  if (m_trace) {
629 #if !defined(PYPY_VERSION)
630  auto *tb = reinterpret_cast<PyTracebackObject *>(m_trace.ptr());
631 
632  // Get the deepest trace possible.
633  while (tb->tb_next) {
634  tb = tb->tb_next;
635  }
636 
637  PyFrameObject *frame = tb->tb_frame;
638  Py_XINCREF(frame);
639  result += "\n\nAt:\n";
640  while (frame) {
641 # if PY_VERSION_HEX >= 0x030900B1
642  PyCodeObject *f_code = PyFrame_GetCode(frame);
643 # else
644  PyCodeObject *f_code = frame->f_code;
645  Py_INCREF(f_code);
646 # endif
647  int lineno = PyFrame_GetLineNumber(frame);
648  result += " ";
649  result += handle(f_code->co_filename).cast<std::string>();
650  result += '(';
651  result += std::to_string(lineno);
652  result += "): ";
653  result += handle(f_code->co_name).cast<std::string>();
654  result += '\n';
655  Py_DECREF(f_code);
656 # if PY_VERSION_HEX >= 0x030900B1
657  auto *b_frame = PyFrame_GetBack(frame);
658 # else
659  auto *b_frame = frame->f_back;
660  Py_XINCREF(b_frame);
661 # endif
662  Py_DECREF(frame);
663  frame = b_frame;
664  }
665 
666  have_trace = true;
667 #endif
668  }
669 
670  if (!message_error_string.empty()) {
671  if (!have_trace) {
672  result += '\n';
673  }
674  result += "\nMESSAGE UNAVAILABLE DUE TO EXCEPTION: " + message_error_string;
675  }
676 
677  return result;
678  }
679 
680  std::string const &error_string() const {
684  }
685  return m_lazy_error_string;
686  }
687 
688  void restore() {
689  if (m_restore_called) {
690  pybind11_fail("Internal error: pybind11::detail::error_fetch_and_normalize::restore() "
691  "called a second time. ORIGINAL ERROR: "
692  + error_string());
693  }
694  PyErr_Restore(m_type.inc_ref().ptr(), m_value.inc_ref().ptr(), m_trace.inc_ref().ptr());
695  m_restore_called = true;
696  }
697 
698  bool matches(handle exc) const {
699  return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0);
700  }
701 
702  // Not protecting these for simplicity.
704 
705 private:
706  // Only protecting invariants.
707  mutable std::string m_lazy_error_string;
708  mutable bool m_lazy_error_string_completed = false;
709  mutable bool m_restore_called = false;
710 };
711 
712 inline std::string error_string() {
713  return error_fetch_and_normalize("pybind11::detail::error_string").error_string();
714 }
715 
717 
718 class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::exception {
723 public:
727  : m_fetched_error{new detail::error_fetch_and_normalize("pybind11::error_already_set"),
728  m_fetched_error_deleter} {}
729 
733  const char *what() const noexcept override;
734 
740  void restore() { m_fetched_error->restore(); }
741 
746  void discard_as_unraisable(object err_context) {
747  restore();
748  PyErr_WriteUnraisable(err_context.ptr());
749  }
753  void discard_as_unraisable(const char *err_context) {
754  discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context)));
755  }
756 
757  // Does nothing; provided for backwards compatibility.
758  PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated")
759  void clear() {}
760 
764  bool matches(handle exc) const { return m_fetched_error->matches(exc); }
765 
766  const object &type() const { return m_fetched_error->m_type; }
767  const object &value() const { return m_fetched_error->m_value; }
768  const object &trace() const { return m_fetched_error->m_trace; }
769 
770 private:
771  std::shared_ptr<detail::error_fetch_and_normalize> m_fetched_error;
772 
775  static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr);
776 };
777 
780 inline void raise_from(PyObject *type, const char *message) {
781  // Based on _PyErr_FormatVFromCause:
782  // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405
783  // See https://github.com/pybind/pybind11/pull/2112 for details.
784  PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr;
785 
786  assert(PyErr_Occurred());
787  PyErr_Fetch(&exc, &val, &tb);
788  PyErr_NormalizeException(&exc, &val, &tb);
789  if (tb != nullptr) {
790  PyException_SetTraceback(val, tb);
791  Py_DECREF(tb);
792  }
793  Py_DECREF(exc);
794  assert(!PyErr_Occurred());
795 
796  PyErr_SetString(type, message);
797 
798  PyErr_Fetch(&exc, &val2, &tb);
799  PyErr_NormalizeException(&exc, &val2, &tb);
800  Py_INCREF(val);
801  PyException_SetCause(val2, val);
802  PyException_SetContext(val2, val);
803  PyErr_Restore(exc, val2, tb);
804 }
805 
809 inline void raise_from(error_already_set &err, PyObject *type, const char *message) {
810  err.restore();
811  raise_from(type, message);
812 }
813 
825 bool isinstance(handle obj) {
826  return T::check_(obj);
827 }
828 
830 bool isinstance(handle obj) {
831  return detail::isinstance_generic(obj, typeid(T));
832 }
833 
834 template <>
835 inline bool isinstance<handle>(handle) = delete;
836 template <>
837 inline bool isinstance<object>(handle obj) {
838  return obj.ptr() != nullptr;
839 }
840 
843 inline bool isinstance(handle obj, handle type) {
844  const auto result = PyObject_IsInstance(obj.ptr(), type.ptr());
845  if (result == -1) {
846  throw error_already_set();
847  }
848  return result != 0;
849 }
850 
853 inline bool hasattr(handle obj, handle name) {
854  return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1;
855 }
856 
857 inline bool hasattr(handle obj, const char *name) {
858  return PyObject_HasAttrString(obj.ptr(), name) == 1;
859 }
860 
861 inline void delattr(handle obj, handle name) {
862  if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) {
863  throw error_already_set();
864  }
865 }
866 
867 inline void delattr(handle obj, const char *name) {
868  if (PyObject_DelAttrString(obj.ptr(), name) != 0) {
869  throw error_already_set();
870  }
871 }
872 
873 inline object getattr(handle obj, handle name) {
874  PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr());
875  if (!result) {
876  throw error_already_set();
877  }
878  return reinterpret_steal<object>(result);
879 }
880 
881 inline object getattr(handle obj, const char *name) {
882  PyObject *result = PyObject_GetAttrString(obj.ptr(), name);
883  if (!result) {
884  throw error_already_set();
885  }
886  return reinterpret_steal<object>(result);
887 }
888 
889 inline object getattr(handle obj, handle name, handle default_) {
890  if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) {
891  return reinterpret_steal<object>(result);
892  }
893  PyErr_Clear();
894  return reinterpret_borrow<object>(default_);
895 }
896 
897 inline object getattr(handle obj, const char *name, handle default_) {
898  if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) {
899  return reinterpret_steal<object>(result);
900  }
901  PyErr_Clear();
902  return reinterpret_borrow<object>(default_);
903 }
904 
905 inline void setattr(handle obj, handle name, handle value) {
906  if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) {
907  throw error_already_set();
908  }
909 }
910 
911 inline void setattr(handle obj, const char *name, handle value) {
912  if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) {
913  throw error_already_set();
914  }
915 }
916 
917 inline ssize_t hash(handle obj) {
918  auto h = PyObject_Hash(obj.ptr());
919  if (h == -1) {
920  throw error_already_set();
921  }
922  return h;
923 }
924 
926 
929  if (value) {
930  if (PyInstanceMethod_Check(value.ptr())) {
931  value = PyInstanceMethod_GET_FUNCTION(value.ptr());
932  } else if (PyMethod_Check(value.ptr())) {
933  value = PyMethod_GET_FUNCTION(value.ptr());
934  }
935  }
936  return value;
937 }
938 
939 // Reimplementation of python's dict helper functions to ensure that exceptions
940 // aren't swallowed (see #2862)
941 
942 // copied from cpython _PyDict_GetItemStringWithError
943 inline PyObject *dict_getitemstring(PyObject *v, const char *key) {
944  PyObject *kv = nullptr, *rv = nullptr;
945  kv = PyUnicode_FromString(key);
946  if (kv == nullptr) {
947  throw error_already_set();
948  }
949 
950  rv = PyDict_GetItemWithError(v, kv);
951  Py_DECREF(kv);
952  if (rv == nullptr && PyErr_Occurred()) {
953  throw error_already_set();
954  }
955  return rv;
956 }
957 
958 inline PyObject *dict_getitem(PyObject *v, PyObject *key) {
959  PyObject *rv = PyDict_GetItemWithError(v, key);
960  if (rv == nullptr && PyErr_Occurred()) {
961  throw error_already_set();
962  }
963  return rv;
964 }
965 
966 // Helper aliases/functions to support implicit casting of values given to python
967 // accessors/methods. When given a pyobject, this simply returns the pyobject as-is; for other C++
968 // type, the value goes through pybind11::cast(obj) to convert it to an `object`.
970 auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) {
971  return std::forward<T>(o);
972 }
973 // The following casting version is implemented in cast.h:
975 object object_or_cast(T &&o);
976 // Match a PyObject*, which we want to convert directly to handle via its converting constructor
977 inline handle object_or_cast(PyObject *ptr) { return ptr; }
978 
979 PYBIND11_WARNING_PUSH
980 PYBIND11_WARNING_DISABLE_MSVC(4522) // warning C4522: multiple assignment operators specified
981 template <typename Policy>
982 class accessor : public object_api<accessor<Policy>> {
983  using key_type = typename Policy::key_type;
984 
985 public:
986  accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) {}
987  accessor(const accessor &) = default;
988  accessor(accessor &&) noexcept = default;
989 
990  // accessor overload required to override default assignment operator (templates are not
991  // allowed to replace default compiler-generated assignments).
992  void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); }
993  void operator=(const accessor &a) & { operator=(handle(a)); }
994 
995  template <typename T>
996  void operator=(T &&value) && {
997  Policy::set(obj, key, object_or_cast(std::forward<T>(value)));
998  }
999  template <typename T>
1000  void operator=(T &&value) & {
1001  get_cache() = ensure_object(object_or_cast(std::forward<T>(value)));
1002  }
1003 
1004  template <typename T = Policy>
1006  "Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
1007  explicit
1008  operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value
1009  || std::is_same<T, accessor_policies::obj_attr>::value,
1010  bool>() const {
1011  return hasattr(obj, key);
1012  }
1013  template <typename T = Policy>
1014  PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
1015  explicit
1016  operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const {
1017  return obj.contains(key);
1018  }
1019 
1020  // NOLINTNEXTLINE(google-explicit-constructor)
1021  operator object() const { return get_cache(); }
1022  PyObject *ptr() const { return get_cache().ptr(); }
1023  template <typename T>
1024  T cast() const {
1025  return get_cache().template cast<T>();
1026  }
1027 
1028 private:
1029  static object ensure_object(object &&o) { return std::move(o); }
1030  static object ensure_object(handle h) { return reinterpret_borrow<object>(h); }
1031 
1032  object &get_cache() const {
1033  if (!cache) {
1034  cache = Policy::get(obj, key);
1035  }
1036  return cache;
1037  }
1038 
1039 private:
1040  handle obj;
1041  key_type key;
1042  mutable object cache;
1043 };
1045 
1047 struct obj_attr {
1048  using key_type = object;
1049  static object get(handle obj, handle key) { return getattr(obj, key); }
1050  static void set(handle obj, handle key, handle val) { setattr(obj, key, val); }
1051 };
1052 
1053 struct str_attr {
1054  using key_type = const char *;
1055  static object get(handle obj, const char *key) { return getattr(obj, key); }
1056  static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); }
1057 };
1058 
1060  using key_type = object;
1061 
1062  static object get(handle obj, handle key) {
1063  PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr());
1064  if (!result) {
1065  throw error_already_set();
1066  }
1067  return reinterpret_steal<object>(result);
1068  }
1069 
1070  static void set(handle obj, handle key, handle val) {
1071  if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) {
1072  throw error_already_set();
1073  }
1074  }
1075 };
1076 
1078  using key_type = size_t;
1079 
1081  static object get(handle obj, const IdxType &index) {
1082  PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index));
1083  if (!result) {
1084  throw error_already_set();
1085  }
1086  return reinterpret_steal<object>(result);
1087  }
1088 
1090  static void set(handle obj, const IdxType &index, handle val) {
1091  // PySequence_SetItem does not steal a reference to 'val'
1092  if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) {
1093  throw error_already_set();
1094  }
1095  }
1096 };
1097 
1098 struct list_item {
1099  using key_type = size_t;
1100 
1102  static object get(handle obj, const IdxType &index) {
1103  PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index));
1104  if (!result) {
1105  throw error_already_set();
1106  }
1107  return reinterpret_borrow<object>(result);
1108  }
1109 
1111  static void set(handle obj, const IdxType &index, handle val) {
1112  // PyList_SetItem steals a reference to 'val'
1113  if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
1114  throw error_already_set();
1115  }
1116  }
1117 };
1118 
1119 struct tuple_item {
1120  using key_type = size_t;
1121 
1123  static object get(handle obj, const IdxType &index) {
1124  PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index));
1125  if (!result) {
1126  throw error_already_set();
1127  }
1128  return reinterpret_borrow<object>(result);
1129  }
1130 
1132  static void set(handle obj, const IdxType &index, handle val) {
1133  // PyTuple_SetItem steals a reference to 'val'
1134  if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
1135  throw error_already_set();
1136  }
1137  }
1138 };
1140 
1141 template <typename Policy>
1143 class generic_iterator : public Policy {
1145 
1146 public:
1148  using iterator_category = typename Policy::iterator_category;
1149  using value_type = typename Policy::value_type;
1150  using reference = typename Policy::reference;
1151  using pointer = typename Policy::pointer;
1152 
1153  generic_iterator() = default;
1154  generic_iterator(handle seq, ssize_t index) : Policy(seq, index) {}
1155 
1156  // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1157  reference operator*() const { return Policy::dereference(); }
1158  // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1159  reference operator[](difference_type n) const { return *(*this + n); }
1160  pointer operator->() const { return **this; }
1161 
1163  Policy::increment();
1164  return *this;
1165  }
1167  auto copy = *this;
1168  Policy::increment();
1169  return copy;
1170  }
1172  Policy::decrement();
1173  return *this;
1174  }
1176  auto copy = *this;
1177  Policy::decrement();
1178  return copy;
1179  }
1181  Policy::advance(n);
1182  return *this;
1183  }
1185  Policy::advance(-n);
1186  return *this;
1187  }
1188 
1189  friend It operator+(const It &a, difference_type n) {
1190  auto copy = a;
1191  return copy += n;
1192  }
1193  friend It operator+(difference_type n, const It &b) { return b + n; }
1194  friend It operator-(const It &a, difference_type n) {
1195  auto copy = a;
1196  return copy -= n;
1197  }
1198  friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); }
1199 
1200  friend bool operator==(const It &a, const It &b) { return a.equal(b); }
1201  friend bool operator!=(const It &a, const It &b) { return !(a == b); }
1202  friend bool operator<(const It &a, const It &b) { return b - a > 0; }
1203  friend bool operator>(const It &a, const It &b) { return b < a; }
1204  friend bool operator>=(const It &a, const It &b) { return !(a < b); }
1205  friend bool operator<=(const It &a, const It &b) { return !(a > b); }
1206 };
1207 
1208 PYBIND11_NAMESPACE_BEGIN(iterator_policies)
1210 template <typename T>
1211 struct arrow_proxy {
1213 
1214  // NOLINTNEXTLINE(google-explicit-constructor)
1215  arrow_proxy(T &&value) noexcept : value(std::move(value)) {}
1216  T *operator->() const { return &value; }
1217 };
1218 
1221 protected:
1222  using iterator_category = std::random_access_iterator_tag;
1224  using reference = const handle; // PR #3263
1226 
1227  sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) {}
1228 
1229  // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1230  reference dereference() const { return *ptr; }
1231  void increment() { ++ptr; }
1232  void decrement() { --ptr; }
1233  void advance(ssize_t n) { ptr += n; }
1234  bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; }
1235  ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; }
1236 
1237 private:
1238  PyObject **ptr;
1239 };
1240 
1243 protected:
1244  using iterator_category = std::random_access_iterator_tag;
1248 
1249  sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) {}
1250 
1251  reference dereference() const { return {obj, static_cast<size_t>(index)}; }
1252  void increment() { ++index; }
1253  void decrement() { --index; }
1254  void advance(ssize_t n) { index += n; }
1255  bool equal(const sequence_slow_readwrite &b) const { return index == b.index; }
1256  ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; }
1257 
1258 private:
1261 };
1262 
1265 protected:
1266  using iterator_category = std::forward_iterator_tag;
1267  using value_type = std::pair<handle, handle>;
1268  using reference = const value_type; // PR #3263
1270 
1271  dict_readonly() = default;
1272  dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }
1273 
1274  // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1275  reference dereference() const { return {key, value}; }
1276  void increment() {
1277  if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) {
1278  pos = -1;
1279  }
1280  }
1281  bool equal(const dict_readonly &b) const { return pos == b.pos; }
1282 
1283 private:
1285  PyObject *key = nullptr, *value = nullptr;
1286  ssize_t pos = -1;
1287 };
1288 PYBIND11_NAMESPACE_END(iterator_policies)
1289 
1290 #if !defined(PYPY_VERSION)
1293 #else
1296 #endif
1297 
1300 
1301 inline bool PyIterable_Check(PyObject *obj) {
1302  PyObject *iter = PyObject_GetIter(obj);
1303  if (iter) {
1304  Py_DECREF(iter);
1305  return true;
1306  }
1307  PyErr_Clear();
1308  return false;
1309 }
1310 
1311 inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
1312 inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }
1313 
1314 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
1315 inline bool PyUnicode_Check_Permissive(PyObject *o) {
1316  return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o);
1317 }
1318 # define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive
1319 #else
1320 # define PYBIND11_STR_CHECK_FUN PyUnicode_Check
1321 #endif
1322 
1323 inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; }
1324 
1325 class kwargs_proxy : public handle {
1326 public:
1327  explicit kwargs_proxy(handle h) : handle(h) {}
1328 };
1329 
1330 class args_proxy : public handle {
1331 public:
1332  explicit args_proxy(handle h) : handle(h) {}
1333  kwargs_proxy operator*() const { return kwargs_proxy(*this); }
1334 };
1335 
1337 template <typename T>
1338 using is_keyword = std::is_base_of<arg, T>;
1339 template <typename T>
1340 using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking
1341 template <typename T>
1342 using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking
1343 template <typename T>
1345 template <typename T>
1347 
1348 // Call argument collector forward declarations
1349 template <return_value_policy policy = return_value_policy::automatic_reference>
1350 class simple_collector;
1351 template <return_value_policy policy = return_value_policy::automatic_reference>
1352 class unpacking_collector;
1353 
1355 
1356 // TODO: After the deprecated constructors are removed, this macro can be simplified by
1357 // inheriting ctors: `using Parent::Parent`. It's not an option right now because
1358 // the `using` statement triggers the parent deprecation warning even if the ctor
1359 // isn't even used.
1360 #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1361 public: \
1362  PYBIND11_DEPRECATED("Use reinterpret_borrow<" #Name ">() or reinterpret_steal<" #Name ">()") \
1363  Name(handle h, bool is_borrowed) \
1364  : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {} \
1365  Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {} \
1366  Name(handle h, stolen_t) : Parent(h, stolen_t{}) {} \
1367  PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
1368  bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \
1369  static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \
1370  template <typename Policy_> /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1371  Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) {}
1372 
1373 #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1374  PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1375  /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
1376  /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1377  Name(const object &o) \
1378  : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1379  if (!m_ptr) \
1380  throw ::pybind11::error_already_set(); \
1381  } \
1382  /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1383  Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1384  if (!m_ptr) \
1385  throw ::pybind11::error_already_set(); \
1386  }
1387 
1388 #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \
1389  PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1390  Name() = default;
1391 
1392 #define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \
1393  ::pybind11::type_error("Object of type '" \
1394  + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) \
1395  + "' is not an instance of '" #Name "'")
1396 
1397 #define PYBIND11_OBJECT(Name, Parent, CheckFun) \
1398  PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1399  /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
1400  /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1401  Name(const object &o) : Parent(o) { \
1402  if (m_ptr && !check_(m_ptr)) \
1403  throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1404  } \
1405  /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1406  Name(object &&o) : Parent(std::move(o)) { \
1407  if (m_ptr && !check_(m_ptr)) \
1408  throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1409  }
1410 
1411 #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
1412  PYBIND11_OBJECT(Name, Parent, CheckFun) \
1413  Name() = default;
1414 
1417 
1426 class iterator : public object {
1427 public:
1428  using iterator_category = std::input_iterator_tag;
1431  using reference = const handle; // PR #3263
1432  using pointer = const handle *;
1433 
1434  PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)
1435 
1436  iterator &operator++() {
1437  advance();
1438  return *this;
1439  }
1440 
1442  auto rv = *this;
1443  advance();
1444  return rv;
1445  }
1446 
1447  // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1449  if (m_ptr && !value.ptr()) {
1450  auto &self = const_cast<iterator &>(*this);
1451  self.advance();
1452  }
1453  return value;
1454  }
1455 
1457  operator*();
1458  return &value;
1459  }
1460 
1474  static iterator sentinel() { return {}; }
1475 
1476  friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); }
1477  friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); }
1478 
1479 private:
1480  void advance() {
1481  value = reinterpret_steal<object>(PyIter_Next(m_ptr));
1482  if (value.ptr() == nullptr && PyErr_Occurred()) {
1483  throw error_already_set();
1484  }
1485  }
1486 
1487 private:
1488  object value = {};
1489 };
1490 
1491 class type : public object {
1492 public:
1493  PYBIND11_OBJECT(type, object, PyType_Check)
1494 
1495 
1496  static handle handle_of(handle h) { return handle((PyObject *) Py_TYPE(h.ptr())); }
1497 
1499  static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); }
1500 
1501  // Defined in pybind11/cast.h
1505  template <typename T>
1506  static handle handle_of();
1507 
1511  template <typename T>
1512  static type of() {
1513  return type(type::handle_of<T>(), borrowed_t{});
1514  }
1515 };
1516 
1517 class iterable : public object {
1518 public:
1520 };
1521 
1522 class bytes;
1523 
1524 class str : public object {
1525 public:
1527 
1529  str(const char *c, const SzType &n)
1530  : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1531  if (!m_ptr) {
1532  if (PyErr_Occurred()) {
1533  throw error_already_set();
1534  }
1535  pybind11_fail("Could not allocate string object!");
1536  }
1537  }
1538 
1539  // 'explicit' is explicitly omitted from the following constructors to allow implicit
1540  // conversion to py::str from C++ string-like objects
1541  // NOLINTNEXTLINE(google-explicit-constructor)
1542  str(const char *c = "") : object(PyUnicode_FromString(c), stolen_t{}) {
1543  if (!m_ptr) {
1544  if (PyErr_Occurred()) {
1545  throw error_already_set();
1546  }
1547  pybind11_fail("Could not allocate string object!");
1548  }
1549  }
1550 
1551  // NOLINTNEXTLINE(google-explicit-constructor)
1552  str(const std::string &s) : str(s.data(), s.size()) {}
1553 
1554 #ifdef PYBIND11_HAS_STRING_VIEW
1555  // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
1557  // NOLINTNEXTLINE(google-explicit-constructor)
1558  str(T s) : str(s.data(), s.size()) {}
1559 
1560 # ifdef PYBIND11_HAS_U8STRING
1561  // reinterpret_cast here is safe (C++20 guarantees char8_t has the same size/alignment as char)
1562  // NOLINTNEXTLINE(google-explicit-constructor)
1563  str(std::u8string_view s) : str(reinterpret_cast<const char *>(s.data()), s.size()) {}
1564 # endif
1565 
1566 #endif
1567 
1568  explicit str(const bytes &b);
1569 
1574  explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) {
1575  if (!m_ptr) {
1576  throw error_already_set();
1577  }
1578  }
1579 
1580  // NOLINTNEXTLINE(google-explicit-constructor)
1581  operator std::string() const {
1582  object temp = *this;
1583  if (PyUnicode_Check(m_ptr)) {
1584  temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
1585  if (!temp) {
1586  throw error_already_set();
1587  }
1588  }
1589  char *buffer = nullptr;
1590  ssize_t length = 0;
1591  if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {
1592  throw error_already_set();
1593  }
1594  return std::string(buffer, (size_t) length);
1595  }
1596 
1597  template <typename... Args>
1598  str format(Args &&...args) const {
1599  return attr("format")(std::forward<Args>(args)...);
1600  }
1601 
1602 private:
1604  static PyObject *raw_str(PyObject *op) {
1605  PyObject *str_value = PyObject_Str(op);
1606  return str_value;
1607  }
1608 };
1610 
1611 inline namespace literals {
1615 inline str operator"" _s(const char *s, size_t size) { return {s, size}; }
1616 } // namespace literals
1617 
1620 class bytes : public object {
1621 public:
1623 
1624  // Allow implicit conversion:
1625  // NOLINTNEXTLINE(google-explicit-constructor)
1626  bytes(const char *c = "") : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) {
1627  if (!m_ptr) {
1628  pybind11_fail("Could not allocate bytes object!");
1629  }
1630  }
1631 
1633  bytes(const char *c, const SzType &n)
1635  if (!m_ptr) {
1636  pybind11_fail("Could not allocate bytes object!");
1637  }
1638  }
1639 
1640  // Allow implicit conversion:
1641  // NOLINTNEXTLINE(google-explicit-constructor)
1642  bytes(const std::string &s) : bytes(s.data(), s.size()) {}
1643 
1644  explicit bytes(const pybind11::str &s);
1645 
1646  // NOLINTNEXTLINE(google-explicit-constructor)
1647  operator std::string() const { return string_op<std::string>(); }
1648 
1649 #ifdef PYBIND11_HAS_STRING_VIEW
1650  // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
1652  // NOLINTNEXTLINE(google-explicit-constructor)
1653  bytes(T s) : bytes(s.data(), s.size()) {}
1654 
1655  // Obtain a string view that views the current `bytes` buffer value. Note that this is only
1656  // valid so long as the `bytes` instance remains alive and so generally should not outlive the
1657  // lifetime of the `bytes` instance.
1658  // NOLINTNEXTLINE(google-explicit-constructor)
1659  operator std::string_view() const { return string_op<std::string_view>(); }
1660 #endif
1661 private:
1662  template <typename T>
1663  T string_op() const {
1664  char *buffer = nullptr;
1665  ssize_t length = 0;
1666  if (PyBytes_AsStringAndSize(m_ptr, &buffer, &length) != 0) {
1667  throw error_already_set();
1668  }
1669  return {buffer, static_cast<size_t>(length)};
1670  }
1671 };
1672 // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1673 // are included in the doxygen group; close here and reopen after as a workaround
1675 
1676 inline bytes::bytes(const pybind11::str &s) {
1677  object temp = s;
1678  if (PyUnicode_Check(s.ptr())) {
1679  temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));
1680  if (!temp) {
1681  throw error_already_set();
1682  }
1683  }
1684  char *buffer = nullptr;
1685  ssize_t length = 0;
1686  if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {
1687  throw error_already_set();
1688  }
1689  auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));
1690  if (!obj) {
1691  pybind11_fail("Could not allocate bytes object!");
1692  }
1693  m_ptr = obj.release().ptr();
1694 }
1695 
1696 inline str::str(const bytes &b) {
1697  char *buffer = nullptr;
1698  ssize_t length = 0;
1699  if (PyBytes_AsStringAndSize(b.ptr(), &buffer, &length) != 0) {
1700  throw error_already_set();
1701  }
1702  auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, length));
1703  if (!obj) {
1704  if (PyErr_Occurred()) {
1705  throw error_already_set();
1706  }
1707  pybind11_fail("Could not allocate string object!");
1708  }
1709  m_ptr = obj.release().ptr();
1710 }
1711 
1714 class bytearray : public object {
1715 public:
1716  PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject)
1717 
1719  bytearray(const char *c, const SzType &n)
1720  : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1721  if (!m_ptr) {
1722  pybind11_fail("Could not allocate bytearray object!");
1723  }
1724  }
1725 
1726  bytearray() : bytearray("", 0) {}
1727 
1728  explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) {}
1729 
1730  size_t size() const { return static_cast<size_t>(PyByteArray_Size(m_ptr)); }
1731 
1732  explicit operator std::string() const {
1733  char *buffer = PyByteArray_AS_STRING(m_ptr);
1734  ssize_t size = PyByteArray_GET_SIZE(m_ptr);
1735  return std::string(buffer, static_cast<size_t>(size));
1736  }
1737 };
1738 // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1739 // are included in the doxygen group; close here and reopen after as a workaround
1741 
1744 class none : public object {
1745 public:
1747  none() : object(Py_None, borrowed_t{}) {}
1748 };
1749 
1750 class ellipsis : public object {
1751 public:
1753  ellipsis() : object(Py_Ellipsis, borrowed_t{}) {}
1754 };
1755 
1756 class bool_ : public object {
1757 public:
1758  PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool)
1759  bool_() : object(Py_False, borrowed_t{}) {}
1760  // Allow implicit conversion from and to `bool`:
1761  // NOLINTNEXTLINE(google-explicit-constructor)
1762  bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) {}
1763  // NOLINTNEXTLINE(google-explicit-constructor)
1764  operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; }
1765 
1766 private:
1768  static PyObject *raw_bool(PyObject *op) {
1769  const auto value = PyObject_IsTrue(op);
1770  if (value == -1) {
1771  return nullptr;
1772  }
1773  return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr();
1774  }
1775 };
1776 
1778 // Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1;
1779 // otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned).
1780 // (The distinction is critically important when casting a returned -1 error value to some other
1781 // unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes).
1782 template <typename Unsigned>
1783 Unsigned as_unsigned(PyObject *o) {
1784  if (sizeof(Unsigned) <= sizeof(unsigned long)) {
1785  unsigned long v = PyLong_AsUnsignedLong(o);
1786  return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1787  }
1788  unsigned long long v = PyLong_AsUnsignedLongLong(o);
1789  return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1790 }
1792 
1793 class int_ : public object {
1794 public:
1795  PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long)
1796  int_() : object(PyLong_FromLong(0), stolen_t{}) {}
1797  // Allow implicit conversion from C++ integral types:
1799  // NOLINTNEXTLINE(google-explicit-constructor)
1801  if (sizeof(T) <= sizeof(long)) {
1803  m_ptr = PyLong_FromLong((long) value);
1804  } else {
1805  m_ptr = PyLong_FromUnsignedLong((unsigned long) value);
1806  }
1807  } else {
1809  m_ptr = PyLong_FromLongLong((long long) value);
1810  } else {
1811  m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value);
1812  }
1813  }
1814  if (!m_ptr) {
1815  pybind11_fail("Could not allocate int object!");
1816  }
1817  }
1818 
1820  // NOLINTNEXTLINE(google-explicit-constructor)
1821  operator T() const {
1822  return std::is_unsigned<T>::value ? detail::as_unsigned<T>(m_ptr)
1823  : sizeof(T) <= sizeof(long) ? (T) PyLong_AsLong(m_ptr)
1824  : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
1825  }
1826 };
1827 
1828 class float_ : public object {
1829 public:
1830  PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)
1831  // Allow implicit conversion from float/double:
1832  // NOLINTNEXTLINE(google-explicit-constructor)
1833  float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1834  if (!m_ptr) {
1835  pybind11_fail("Could not allocate float object!");
1836  }
1837  }
1838  // NOLINTNEXTLINE(google-explicit-constructor)
1839  float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1840  if (!m_ptr) {
1841  pybind11_fail("Could not allocate float object!");
1842  }
1843  }
1844  // NOLINTNEXTLINE(google-explicit-constructor)
1845  operator float() const { return (float) PyFloat_AsDouble(m_ptr); }
1846  // NOLINTNEXTLINE(google-explicit-constructor)
1847  operator double() const { return (double) PyFloat_AsDouble(m_ptr); }
1848 };
1849 
1850 class weakref : public object {
1851 public:
1852  PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref)
1853  explicit weakref(handle obj, handle callback = {})
1854  : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) {
1855  if (!m_ptr) {
1856  if (PyErr_Occurred()) {
1857  throw error_already_set();
1858  }
1859  pybind11_fail("Could not allocate weak reference!");
1860  }
1861  }
1862 
1863 private:
1864  static PyObject *raw_weakref(PyObject *o) { return PyWeakref_NewRef(o, nullptr); }
1865 };
1866 
1867 class slice : public object {
1868 public:
1869  PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check)
1871  : object(PySlice_New(start.ptr(), stop.ptr(), step.ptr()), stolen_t{}) {
1872  if (!m_ptr) {
1873  pybind11_fail("Could not allocate slice object!");
1874  }
1875  }
1876 
1877 #ifdef PYBIND11_HAS_OPTIONAL
1878  slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t> step)
1879  : slice(index_to_object(start), index_to_object(stop), index_to_object(step)) {}
1880 #else
1881  slice(ssize_t start_, ssize_t stop_, ssize_t step_)
1882  : slice(int_(start_), int_(stop_), int_(step_)) {}
1883 #endif
1884 
1885  bool
1886  compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const {
1887  return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1888  (ssize_t) length,
1889  (ssize_t *) start,
1890  (ssize_t *) stop,
1891  (ssize_t *) step,
1892  (ssize_t *) slicelength)
1893  == 0;
1894  }
1895  bool compute(
1896  ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const {
1897  return PySlice_GetIndicesEx(
1898  (PYBIND11_SLICE_OBJECT *) m_ptr, length, start, stop, step, slicelength)
1899  == 0;
1900  }
1901 
1902 private:
1903  template <typename T>
1904  static object index_to_object(T index) {
1905  return index ? object(int_(*index)) : object(none());
1906  }
1907 };
1908 
1909 class capsule : public object {
1910 public:
1911  PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact)
1912  PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()")
1913  capsule(PyObject *ptr, bool is_borrowed)
1914  : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) {}
1915 
1916  explicit capsule(const void *value,
1917  const char *name = nullptr,
1918  PyCapsule_Destructor destructor = nullptr)
1919  : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) {
1920  if (!m_ptr) {
1921  throw error_already_set();
1922  }
1923  }
1924 
1925  PYBIND11_DEPRECATED("Please use the ctor with value, name, destructor args")
1926  capsule(const void *value, PyCapsule_Destructor destructor)
1927  : object(PyCapsule_New(const_cast<void *>(value), nullptr, destructor), stolen_t{}) {
1928  if (!m_ptr) {
1929  throw error_already_set();
1930  }
1931  }
1932 
1934  capsule(const void *value, void (*destructor)(void *)) {
1935  initialize_with_void_ptr_destructor(value, nullptr, destructor);
1936  }
1937 
1938  capsule(const void *value, const char *name, void (*destructor)(void *)) {
1939  initialize_with_void_ptr_destructor(value, name, destructor);
1940  }
1941 
1942  explicit capsule(void (*destructor)()) {
1943  m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) {
1944  const char *name = get_name_in_error_scope(o);
1945  auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, name));
1946  if (destructor == nullptr) {
1947  throw error_already_set();
1948  }
1949  destructor();
1950  });
1951 
1952  if (!m_ptr) {
1953  throw error_already_set();
1954  }
1955  }
1956 
1957  template <typename T>
1958  operator T *() const { // NOLINT(google-explicit-constructor)
1959  return get_pointer<T>();
1960  }
1961 
1963  template <typename T = void>
1964  T *get_pointer() const {
1965  const auto *name = this->name();
1966  T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));
1967  if (!result) {
1968  throw error_already_set();
1969  }
1970  return result;
1971  }
1972 
1974  void set_pointer(const void *value) {
1975  if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0) {
1976  throw error_already_set();
1977  }
1978  }
1979 
1980  const char *name() const {
1981  const char *name = PyCapsule_GetName(m_ptr);
1982  if ((name == nullptr) && PyErr_Occurred()) {
1983  throw error_already_set();
1984  }
1985  return name;
1986  }
1987 
1989  void set_name(const char *new_name) {
1990  if (PyCapsule_SetName(m_ptr, new_name) != 0) {
1991  throw error_already_set();
1992  }
1993  }
1994 
1995 private:
1996  static const char *get_name_in_error_scope(PyObject *o) {
1997  error_scope error_guard;
1998 
1999  const char *name = PyCapsule_GetName(o);
2000  if ((name == nullptr) && PyErr_Occurred()) {
2001  // write out and consume error raised by call to PyCapsule_GetName
2002  PyErr_WriteUnraisable(o);
2003  }
2004 
2005  return name;
2006  }
2007 
2008  void initialize_with_void_ptr_destructor(const void *value,
2009  const char *name,
2010  void (*destructor)(void *)) {
2011  m_ptr = PyCapsule_New(const_cast<void *>(value), name, [](PyObject *o) {
2012  // guard if destructor called while err indicator is set
2013  error_scope error_guard;
2014  auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o));
2015  if (destructor == nullptr && PyErr_Occurred()) {
2016  throw error_already_set();
2017  }
2018  const char *name = get_name_in_error_scope(o);
2019  void *ptr = PyCapsule_GetPointer(o, name);
2020  if (ptr == nullptr) {
2021  throw error_already_set();
2022  }
2023 
2024  if (destructor != nullptr) {
2025  destructor(ptr);
2026  }
2027  });
2028 
2029  if (!m_ptr || PyCapsule_SetContext(m_ptr, reinterpret_cast<void *>(destructor)) != 0) {
2030  throw error_already_set();
2031  }
2032  }
2033 };
2034 
2035 class tuple : public object {
2036 public:
2037  PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple)
2038  template <typename SzType = ssize_t,
2040  // Some compilers generate link errors when using `const SzType &` here:
2041  explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) {
2042  if (!m_ptr) {
2043  pybind11_fail("Could not allocate tuple object!");
2044  }
2045  }
2046  size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
2047  bool empty() const { return size() == 0; }
2048  detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }
2051  return object::operator[](std::forward<T>(o));
2052  }
2053  detail::tuple_iterator begin() const { return {*this, 0}; }
2054  detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }
2055 };
2056 
2057 // We need to put this into a separate function because the Intel compiler
2058 // fails to compile enable_if_t<all_of<is_keyword_or_ds<Args>...>::value> part below
2059 // (tested with ICC 2021.1 Beta 20200827).
2060 template <typename... Args>
2061 constexpr bool args_are_all_keyword_or_ds() {
2062  return detail::all_of<detail::is_keyword_or_ds<Args>...>::value;
2063 }
2064 
2065 class dict : public object {
2066 public:
2067  PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)
2068  dict() : object(PyDict_New(), stolen_t{}) {
2069  if (!m_ptr) {
2070  pybind11_fail("Could not allocate dict object!");
2071  }
2072  }
2073  template <typename... Args,
2074  typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>,
2075  // MSVC workaround: it can't compile an out-of-line definition, so defer the
2076  // collector
2077  typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
2078  explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) {}
2079 
2080  size_t size() const { return (size_t) PyDict_Size(m_ptr); }
2081  bool empty() const { return size() == 0; }
2082  detail::dict_iterator begin() const { return {*this, 0}; }
2083  detail::dict_iterator end() const { return {}; }
2084  void clear() /* py-non-const */ { PyDict_Clear(ptr()); }
2085  template <typename T>
2086  bool contains(T &&key) const {
2087  auto result = PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr());
2088  if (result == -1) {
2089  throw error_already_set();
2090  }
2091  return result == 1;
2092  }
2093 
2094 private:
2096  static PyObject *raw_dict(PyObject *op) {
2097  if (PyDict_Check(op)) {
2098  return handle(op).inc_ref().ptr();
2099  }
2100  return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
2101  }
2102 };
2103 
2104 class sequence : public object {
2105 public:
2106  PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)
2107  size_t size() const {
2108  ssize_t result = PySequence_Size(m_ptr);
2109  if (result == -1) {
2110  throw error_already_set();
2111  }
2112  return (size_t) result;
2113  }
2114  bool empty() const { return size() == 0; }
2115  detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
2118  return object::operator[](std::forward<T>(o));
2119  }
2120  detail::sequence_iterator begin() const { return {*this, 0}; }
2121  detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; }
2122 };
2123 
2124 class list : public object {
2125 public:
2126  PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
2127  template <typename SzType = ssize_t,
2129  // Some compilers generate link errors when using `const SzType &` here:
2130  explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) {
2131  if (!m_ptr) {
2132  pybind11_fail("Could not allocate list object!");
2133  }
2134  }
2135  size_t size() const { return (size_t) PyList_Size(m_ptr); }
2136  bool empty() const { return size() == 0; }
2137  detail::list_accessor operator[](size_t index) const { return {*this, index}; }
2140  return object::operator[](std::forward<T>(o));
2141  }
2142  detail::list_iterator begin() const { return {*this, 0}; }
2143  detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
2144  template <typename T>
2145  void append(T &&val) /* py-non-const */ {
2146  if (PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) != 0) {
2147  throw error_already_set();
2148  }
2149  }
2150  template <typename IdxType,
2151  typename ValType,
2153  void insert(const IdxType &index, ValType &&val) /* py-non-const */ {
2154  if (PyList_Insert(m_ptr,
2155  ssize_t_cast(index),
2156  detail::object_or_cast(std::forward<ValType>(val)).ptr())
2157  != 0) {
2158  throw error_already_set();
2159  }
2160  }
2161 };
2162 
2163 class args : public tuple {
2164  PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check)
2165 };
2166 class kwargs : public dict {
2167  PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check)
2168 };
2169 
2170 class anyset : public object {
2171 public:
2172  PYBIND11_OBJECT(anyset, object, PyAnySet_Check)
2173  size_t size() const { return static_cast<size_t>(PySet_Size(m_ptr)); }
2174  bool empty() const { return size() == 0; }
2175  template <typename T>
2176  bool contains(T &&val) const {
2177  auto result = PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
2178  if (result == -1) {
2179  throw error_already_set();
2180  }
2181  return result == 1;
2182  }
2183 };
2184 
2185 class set : public anyset {
2186 public:
2187  PYBIND11_OBJECT_CVT(set, anyset, PySet_Check, PySet_New)
2188  set() : anyset(PySet_New(nullptr), stolen_t{}) {
2189  if (!m_ptr) {
2190  pybind11_fail("Could not allocate set object!");
2191  }
2192  }
2193  template <typename T>
2194  bool add(T &&val) /* py-non-const */ {
2195  return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
2196  }
2197  void clear() /* py-non-const */ { PySet_Clear(m_ptr); }
2198 };
2199 
2200 class frozenset : public anyset {
2201 public:
2202  PYBIND11_OBJECT_CVT(frozenset, anyset, PyFrozenSet_Check, PyFrozenSet_New)
2203 };
2204 
2205 class function : public object {
2206 public:
2207  PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)
2209  handle fun = detail::get_function(m_ptr);
2210  if (fun && PyCFunction_Check(fun.ptr())) {
2211  return fun;
2212  }
2213  return handle();
2214  }
2215  bool is_cpp_function() const { return (bool) cpp_function(); }
2216 };
2217 
2218 class staticmethod : public object {
2219 public:
2220  PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)
2221 };
2222 
2223 class buffer : public object {
2224 public:
2225  PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)
2226 
2227  buffer_info request(bool writable = false) const {
2228  int flags = PyBUF_STRIDES | PyBUF_FORMAT;
2229  if (writable) {
2230  flags |= PyBUF_WRITABLE;
2231  }
2232  auto *view = new Py_buffer();
2233  if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
2234  delete view;
2235  throw error_already_set();
2236  }
2237  return buffer_info(view);
2238  }
2239 };
2240 
2241 class memoryview : public object {
2242 public:
2243  PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
2244 
2245 
2254  explicit memoryview(const buffer_info &info) {
2255  if (!info.view()) {
2256  pybind11_fail("Prohibited to create memoryview without Py_buffer");
2257  }
2258  // Note: PyMemoryView_FromBuffer never increments obj reference.
2259  m_ptr = (info.view()->obj) ? PyMemoryView_FromObject(info.view()->obj)
2260  : PyMemoryView_FromBuffer(info.view());
2261  if (!m_ptr) {
2262  pybind11_fail("Unable to create memoryview from buffer descriptor");
2263  }
2264  }
2265 
2290  static memoryview from_buffer(void *ptr,
2291  ssize_t itemsize,
2292  const char *format,
2293  detail::any_container<ssize_t> shape,
2294  detail::any_container<ssize_t> strides,
2295  bool readonly = false);
2296 
2297  static memoryview from_buffer(const void *ptr,
2298  ssize_t itemsize,
2299  const char *format,
2300  detail::any_container<ssize_t> shape,
2301  detail::any_container<ssize_t> strides) {
2302  return memoryview::from_buffer(
2303  const_cast<void *>(ptr), itemsize, format, std::move(shape), std::move(strides), true);
2304  }
2305 
2306  template <typename T>
2307  static memoryview from_buffer(T *ptr,
2308  detail::any_container<ssize_t> shape,
2309  detail::any_container<ssize_t> strides,
2310  bool readonly = false) {
2311  return memoryview::from_buffer(reinterpret_cast<void *>(ptr),
2312  sizeof(T),
2314  std::move(shape),
2315  std::move(strides),
2316  readonly);
2317  }
2318 
2319  template <typename T>
2320  static memoryview from_buffer(const T *ptr,
2321  detail::any_container<ssize_t> shape,
2322  detail::any_container<ssize_t> strides) {
2323  return memoryview::from_buffer(
2324  const_cast<T *>(ptr), std::move(shape), std::move(strides), true);
2325  }
2326 
2339  static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) {
2340  PyObject *ptr = PyMemoryView_FromMemory(
2341  reinterpret_cast<char *>(mem), size, (readonly) ? PyBUF_READ : PyBUF_WRITE);
2342  if (!ptr) {
2343  pybind11_fail("Could not allocate memoryview object!");
2344  }
2345  return memoryview(object(ptr, stolen_t{}));
2346  }
2347 
2348  static memoryview from_memory(const void *mem, ssize_t size) {
2349  return memoryview::from_memory(const_cast<void *>(mem), size, true);
2350  }
2351 
2352 #ifdef PYBIND11_HAS_STRING_VIEW
2353  static memoryview from_memory(std::string_view mem) {
2354  return from_memory(const_cast<char *>(mem.data()), static_cast<ssize_t>(mem.size()), true);
2355  }
2356 #endif
2357 };
2358 
2360 inline memoryview memoryview::from_buffer(void *ptr,
2361  ssize_t itemsize,
2362  const char *format,
2363  detail::any_container<ssize_t> shape,
2364  detail::any_container<ssize_t> strides,
2365  bool readonly) {
2366  size_t ndim = shape->size();
2367  if (ndim != strides->size()) {
2368  pybind11_fail("memoryview: shape length doesn't match strides length");
2369  }
2370  ssize_t size = ndim != 0u ? 1 : 0;
2371  for (size_t i = 0; i < ndim; ++i) {
2372  size *= (*shape)[i];
2373  }
2374  Py_buffer view;
2375  view.buf = ptr;
2376  view.obj = nullptr;
2377  view.len = size * itemsize;
2378  view.readonly = static_cast<int>(readonly);
2379  view.itemsize = itemsize;
2380  view.format = const_cast<char *>(format);
2381  view.ndim = static_cast<int>(ndim);
2382  view.shape = shape->data();
2383  view.strides = strides->data();
2384  view.suboffsets = nullptr;
2385  view.internal = nullptr;
2386  PyObject *obj = PyMemoryView_FromBuffer(&view);
2387  if (!obj) {
2388  throw error_already_set();
2389  }
2390  return memoryview(object(obj, stolen_t{}));
2391 }
2394 
2397 
2399 inline size_t len(handle h) {
2400  ssize_t result = PyObject_Length(h.ptr());
2401  if (result < 0) {
2402  throw error_already_set();
2403  }
2404  return (size_t) result;
2405 }
2406 
2409 inline size_t len_hint(handle h) {
2410  ssize_t result = PyObject_LengthHint(h.ptr(), 0);
2411  if (result < 0) {
2412  // Sometimes a length can't be determined at all (eg generators)
2413  // In which case simply return 0
2414  PyErr_Clear();
2415  return 0;
2416  }
2417  return (size_t) result;
2418 }
2419 
2420 inline str repr(handle h) {
2421  PyObject *str_value = PyObject_Repr(h.ptr());
2422  if (!str_value) {
2423  throw error_already_set();
2424  }
2425  return reinterpret_steal<str>(str_value);
2426 }
2427 
2428 inline iterator iter(handle obj) {
2429  PyObject *result = PyObject_GetIter(obj.ptr());
2430  if (!result) {
2431  throw error_already_set();
2432  }
2433  return reinterpret_steal<iterator>(result);
2434 }
2436 
2438 template <typename D>
2440  return iter(derived());
2441 }
2442 template <typename D>
2444  return iterator::sentinel();
2445 }
2446 template <typename D>
2448  return {derived(), reinterpret_borrow<object>(key)};
2449 }
2450 template <typename D>
2452  return {derived(), std::move(key)};
2453 }
2454 template <typename D>
2456  return {derived(), pybind11::str(key)};
2457 }
2458 template <typename D>
2460  return {derived(), reinterpret_borrow<object>(key)};
2461 }
2462 template <typename D>
2464  return {derived(), std::move(key)};
2465 }
2466 template <typename D>
2468  return {derived(), key};
2469 }
2470 template <typename D>
2472  return args_proxy(derived().ptr());
2473 }
2474 template <typename D>
2475 template <typename T>
2476 bool object_api<D>::contains(T &&item) const {
2477  return attr("__contains__")(std::forward<T>(item)).template cast<bool>();
2478 }
2479 
2480 template <typename D>
2482  return pybind11::str(derived());
2483 }
2484 
2485 template <typename D>
2487  return attr("__doc__");
2488 }
2489 
2490 template <typename D>
2492  return type::handle_of(derived());
2493 }
2494 
2495 template <typename D>
2497  int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
2498  if (rv == -1) {
2499  throw error_already_set();
2500  }
2501  return rv == 1;
2502 }
2503 
2504 #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
2505  template <typename D> \
2506  object object_api<D>::op() const { \
2507  object result = reinterpret_steal<object>(fn(derived().ptr())); \
2508  if (!result.ptr()) \
2509  throw error_already_set(); \
2510  return result; \
2511  }
2512 
2513 #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
2514  template <typename D> \
2515  object object_api<D>::op(object_api const &other) const { \
2516  object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
2517  if (!result.ptr()) \
2518  throw error_already_set(); \
2519  return result; \
2520  }
2521 
2522 #define PYBIND11_MATH_OPERATOR_BINARY_INPLACE(iop, fn) \
2523  template <typename D> \
2524  object object_api<D>::iop(object_api const &other) { \
2525  object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
2526  if (!result.ptr()) \
2527  throw error_already_set(); \
2528  return result; \
2529  }
2530 
2531 PYBIND11_MATH_OPERATOR_UNARY(operator~, PyNumber_Invert)
2532 PYBIND11_MATH_OPERATOR_UNARY(operator-, PyNumber_Negative)
2533 PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)
2534 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator+=, PyNumber_InPlaceAdd)
2535 PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)
2536 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator-=, PyNumber_InPlaceSubtract)
2537 PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)
2538 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator*=, PyNumber_InPlaceMultiply)
2539 PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)
2540 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator/=, PyNumber_InPlaceTrueDivide)
2541 PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)
2542 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator|=, PyNumber_InPlaceOr)
2543 PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)
2544 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator&=, PyNumber_InPlaceAnd)
2545 PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)
2546 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator^=, PyNumber_InPlaceXor)
2547 PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)
2548 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator<<=, PyNumber_InPlaceLshift)
2549 PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)
2550 PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator>>=, PyNumber_InPlaceRshift)
2551 
2552 #undef PYBIND11_MATH_OPERATOR_UNARY
2553 #undef PYBIND11_MATH_OPERATOR_BINARY
2554 #undef PYBIND11_MATH_OPERATOR_BINARY_INPLACE
2555 
error_fetch_and_normalize::restore
void restore()
Definition: pytypes.h:688
generic_iterator::operator>
friend bool operator>(const It &a, const It &b)
Definition: pytypes.h:1203
sequence_fast_readonly::dereference
reference dereference() const
Definition: pytypes.h:1230
object_api::operator+=
object operator+=(object_api const &other)
PyNone_Check
bool PyNone_Check(PyObject *o)
Definition: pytypes.h:1311
int_
Definition: pytypes.h:1793
str_attr
Definition: pytypes.h:1053
slice::index_to_object
static object index_to_object(T index)
Definition: pytypes.h:1904
handle::check
bool check() const
Definition: pytypes.h:294
object_api::derived
const Derived & derived() const
Definition: pytypes.h:80
type::of
static type of(handle h)
Return a type object from a handle or an object.
Definition: pytypes.h:1499
error_already_set::error_already_set
error_already_set()
Definition: pytypes.h:726
format_descriptor
Definition: wrap/pybind11/include/pybind11/detail/common.h:1023
generic_iterator::difference_type
ssize_t difference_type
Definition: pytypes.h:1147
return_value_policy::move
@ move
str::str
str(const std::string &s)
Definition: pytypes.h:1552
setup.stderr
stderr
Definition: wrap/pybind11/setup.py:139
error_scope
RAII wrapper that temporarily clears any Python error state.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1076
generic_iterator::operator-
friend It operator-(const It &a, difference_type n)
Definition: pytypes.h:1194
error_already_set::matches
bool matches(handle exc) const
Definition: pytypes.h:764
error_already_set::m_fetched_error
std::shared_ptr< detail::error_fetch_and_normalize > m_fetched_error
Definition: pytypes.h:771
bytearray::bytearray
bytearray()
Definition: pytypes.h:1726
dict_readonly::increment
void increment()
Definition: pytypes.h:1276
PYBIND11_OBJECT_CVT_DEFAULT
#define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun)
Definition: pytypes.h:1388
object_api::operator>>=
object operator>>=(object_api const &other)
list::end
detail::list_iterator end() const
Definition: pytypes.h:2143
object::object
object(const object &o)
Copy constructor; always increases the reference count.
Definition: pytypes.h:357
name
Annotation for function names.
Definition: attr.h:51
generic_iterator::operator<=
friend bool operator<=(const It &a, const It &b)
Definition: pytypes.h:1205
setattr
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:905
is_s_unpacking
std::is_same< args_proxy, T > is_s_unpacking
Definition: pytypes.h:1340
isinstance_generic
bool isinstance_generic(handle obj, const std::type_info &tp)
Definition: type_caster_base.h:465
sequence_item::set
static void set(handle obj, const IdxType &index, handle val)
Definition: pytypes.h:1090
generic_iterator::pointer
typename Policy::pointer pointer
Definition: pytypes.h:1151
dict::dict
dict(Args &&...args)
Definition: pytypes.h:2078
object_api::rich_compare
bool rich_compare(object_api const &other, int value) const
Definition: pytypes.h:2496
list::operator[]
detail::item_accessor operator[](T &&o) const
Definition: pytypes.h:2139
error_fetch_and_normalize::error_string
const std::string & error_string() const
Definition: pytypes.h:680
bytes
Definition: pytypes.h:1620
format
std::string format(const std::string &str, const std::vector< std::string > &find, const std::vector< std::string > &replace)
Definition: openglsupport.cpp:226
set
Definition: pytypes.h:2185
Eigen::internal::strides
EIGEN_ALWAYS_INLINE DSizes< IndexType, NumDims > strides(const DSizes< IndexType, NumDims > &dimensions)
Definition: TensorBlock.h:26
generic_iterator::iterator_category
typename Policy::iterator_category iterator_category
Definition: pytypes.h:1148
dict_readonly
Python's dictionary protocol permits this to be a forward iterator.
Definition: pytypes.h:1264
gtsam.examples.DogLegOptimizerExample.type
type
Definition: DogLegOptimizerExample.py:111
ssize_t
Py_ssize_t ssize_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:475
error_fetch_and_normalize::m_restore_called
bool m_restore_called
Definition: pytypes.h:709
PYBIND11_OBJECT
#define PYBIND11_OBJECT(Name, Parent, CheckFun)
Definition: pytypes.h:1397
function::is_cpp_function
bool is_cpp_function() const
Definition: pytypes.h:2215
error_already_set
Definition: pytypes.h:722
object::stolen_t
Definition: pytypes.h:421
generic_iterator::operator+=
It & operator+=(difference_type n)
Definition: pytypes.h:1180
type_info
Definition: internals.h:226
object_api::operator-=
object operator-=(object_api const &other)
kwargs
Definition: pytypes.h:2166
object_api::operator<<
object operator<<(object_api const &other) const
s
RealScalar s
Definition: level1_cplx_impl.h:126
sequence_slow_readwrite::increment
void increment()
Definition: pytypes.h:1252
list_accessor
accessor< accessor_policies::list_item > list_accessor
Definition: pytypes.h:66
object_api::is_none
bool is_none() const
Equivalent to obj is None in Python.
Definition: pytypes.h:148
tuple_item::key_type
size_t key_type
Definition: pytypes.h:1120
error_already_set::trace
const object & trace() const
Definition: pytypes.h:768
staticmethod
Definition: pytypes.h:2218
return_value_policy
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
Definition: wrap/pybind11/include/pybind11/detail/common.h:485
str_attr::get
static object get(handle obj, const char *key)
Definition: pytypes.h:1055
generic_item
Definition: pytypes.h:1059
sequence_fast_readonly::distance_to
ssize_t distance_to(const sequence_fast_readonly &b) const
Definition: pytypes.h:1235
list
Definition: pytypes.h:2124
generic_iterator::operator++
It & operator++()
Definition: pytypes.h:1162
bytes::bytes
bytes(const char *c="")
Definition: pytypes.h:1626
error_string
std::string error_string()
Definition: pytypes.h:712
str_attr::set
static void set(handle obj, const char *key, handle val)
Definition: pytypes.h:1056
object_api
Definition: pytypes.h:79
c
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
b
Scalar * b
Definition: benchVecAdd.cpp:17
str::format
str format(Args &&...args) const
Definition: pytypes.h:1598
PYBIND11_OBJECT_CVT
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)
Definition: pytypes.h:1373
bytes::bytes
bytes(const char *c, const SzType &n)
Definition: pytypes.h:1633
dict_readonly::value_type
std::pair< handle, handle > value_type
Definition: pytypes.h:1267
is_pyobj_ptr_or_nullptr_t
detail::any_of< std::is_same< T, PyObject * >, std::is_same< T, PyObject *const >, std::is_same< T, std::nullptr_t > > is_pyobj_ptr_or_nullptr_t
Definition: pytypes.h:198
type::of
static type of()
Definition: pytypes.h:1512
literals
Definition: cast.h:1376
deferred_t
typename deferred_type< T, Us... >::type deferred_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:883
dict_readonly::equal
bool equal(const dict_readonly &b) const
Definition: pytypes.h:1281
handle::inc_ref
const handle & inc_ref() const &
Definition: pytypes.h:249
sequence_accessor
accessor< accessor_policies::sequence_item > sequence_accessor
Definition: pytypes.h:65
object_api::operator>=
bool operator>=(object_api const &other) const
Definition: pytypes.h:155
obj_attr
Definition: pytypes.h:1047
PYBIND11_STR_CHECK_FUN
#define PYBIND11_STR_CHECK_FUN
Definition: pytypes.h:1320
PYBIND11_WARNING_POP
PYBIND11_WARNING_PUSH PYBIND11_WARNING_POP
Definition: tensor.h:30
error_fetch_and_normalize::m_lazy_error_string
std::string m_lazy_error_string
Definition: pytypes.h:707
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:80
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:853
PYBIND11_BYTES_FROM_STRING
#define PYBIND11_BYTES_FROM_STRING
Definition: wrap/pybind11/include/pybind11/detail/common.h:350
capsule
Definition: pytypes.h:1909
object_api::str
pybind11::str str() const
Definition: pytypes.h:2481
object_api::operator<
bool operator<(object_api const &other) const
Definition: pytypes.h:152
arrow_proxy
Quick proxy class needed to implement operator-> for iterators which can't return pointers.
Definition: pytypes.h:1211
generic_iterator::reference
typename Policy::reference reference
Definition: pytypes.h:1150
object_api::contains
bool contains(T &&item) const
Check if the given item is contained within this object, i.e. item in obj.
Definition: pytypes.h:2476
object_api::operator*=
object operator*=(object_api const &other)
object_api::operator&
object operator&(object_api const &other) const
type
Definition: pytypes.h:1491
dict::end
detail::dict_iterator end() const
Definition: pytypes.h:2083
slice::slice
slice(ssize_t start_, ssize_t stop_, ssize_t step_)
Definition: pytypes.h:1881
getattr
object getattr(handle obj, handle name)
Definition: pytypes.h:873
iterator::difference_type
ssize_t difference_type
Definition: pytypes.h:1429
T
Eigen::Triplet< double > T
Definition: Tutorial_sparse_example.cpp:6
handle::m_ptr
PyObject * m_ptr
Definition: pytypes.h:297
object_api::operator()
object operator()(Args &&...args) const
Definition: cast.h:1666
object_api::operator^=
object operator^=(object_api const &other)
error_fetch_and_normalize::m_trace
object m_trace
Definition: pytypes.h:703
detail
Definition: testSerializationNonlinear.cpp:70
generic_iterator::operator--
It operator--(int)
Definition: pytypes.h:1175
object_api::not_equal
bool not_equal(object_api const &other) const
Definition: pytypes.h:151
buffer
Definition: pytypes.h:2223
dict_getitemstring
PyObject * dict_getitemstring(PyObject *v, const char *key)
Definition: pytypes.h:943
sequence_slow_readwrite::iterator_category
std::random_access_iterator_tag iterator_category
Definition: pytypes.h:1244
memoryview::from_buffer
static memoryview from_buffer(const T *ptr, detail::any_container< ssize_t > shape, detail::any_container< ssize_t > strides)
Definition: pytypes.h:2320
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:76
object_api::begin
iterator begin() const
Definition: pytypes.h:2439
iterator
Definition: pytypes.h:1426
memoryview::from_memory
static memoryview from_memory(const void *mem, ssize_t size)
Definition: pytypes.h:2348
h
const double h
Definition: testSimpleHelicopter.cpp:19
isinstance< handle >
bool isinstance< handle >(handle)=delete
sequence_slow_readwrite::index
ssize_t index
Definition: pytypes.h:1260
result
Values result
Definition: OdometryOptimize.cpp:8
error_already_set::restore
void restore()
Definition: pytypes.h:740
tuple::empty
bool empty() const
Definition: pytypes.h:2047
sequence_slow_readwrite::obj
handle obj
Definition: pytypes.h:1259
sequence_fast_readonly
Lightweight iterator policy using just a simple pointer: see PySequence_Fast_ITEMS
Definition: pytypes.h:1220
PYBIND11_FROM_STRING
#define PYBIND11_FROM_STRING
Definition: wrap/pybind11/include/pybind11/detail/common.h:362
object_api::operator/
object operator/(object_api const &other) const
weakref
Definition: pytypes.h:1850
object::PYBIND11_DEPRECATED
PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()") object(handle h
PYBIND11_LONG_AS_LONGLONG
#define PYBIND11_LONG_AS_LONGLONG(o)
Definition: wrap/pybind11/include/pybind11/detail/common.h:356
hash
ssize_t hash(handle obj)
Definition: pytypes.h:917
as_unsigned
Unsigned as_unsigned(PyObject *o)
Definition: pytypes.h:1783
name
static char name[]
Definition: rgamma.c:72
generic_iterator::operator==
friend bool operator==(const It &a, const It &b)
Definition: pytypes.h:1200
list_item::key_type
size_t key_type
Definition: pytypes.h:1099
object_api::equal
bool equal(object_api const &other) const
Equivalent to obj == other in Python.
Definition: pytypes.h:150
size
Scalar Scalar int size
Definition: benchVecAdd.cpp:17
sequence_fast_readonly::equal
bool equal(const sequence_fast_readonly &b) const
Definition: pytypes.h:1234
bool_
Definition: pytypes.h:1756
object_api::operator>
bool operator>(object_api const &other) const
Definition: pytypes.h:154
generic_iterator::operator-=
It & operator-=(difference_type n)
Definition: pytypes.h:1184
object::~object
~object()
Destructor; automatically calls handle::dec_ref()
Definition: pytypes.h:361
n
int n
Definition: BiCGSTAB_simple.cpp:1
bool_::raw_bool
static PyObject * raw_bool(PyObject *op)
Return the truth value of an object – always returns a new reference.
Definition: pytypes.h:1768
view
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy y set format x g set format y g set format x2 g set format y2 g set format z g set angles radians set nogrid set key title set key left top Right noreverse box linetype linewidth samplen spacing width set nolabel set noarrow set nologscale set logscale x set set pointsize set encoding default set nopolar set noparametric set view
Definition: gnuplot_common_settings.hh:27
slice
Definition: pytypes.h:1867
object
Definition: pytypes.h:347
error_fetch_and_normalize::m_lazy_error_string_completed
bool m_lazy_error_string_completed
Definition: pytypes.h:708
error_already_set::value
const object & value() const
Definition: pytypes.h:767
generic_item::get
static object get(handle obj, handle key)
Definition: pytypes.h:1062
doc
Annotation for documentation.
Definition: attr.h:45
list::size
size_t size() const
Definition: pytypes.h:2135
error_already_set::discard_as_unraisable
void discard_as_unraisable(const char *err_context)
Definition: pytypes.h:753
generic_iterator
STL iterator template used for tuple, list, sequence and dict.
Definition: pytypes.h:1143
tuple::begin
detail::tuple_iterator begin() const
Definition: pytypes.h:2053
generic_iterator::operator>=
friend bool operator>=(const It &a, const It &b)
Definition: pytypes.h:1204
sequence::empty
bool empty() const
Definition: pytypes.h:2114
PYBIND11_LONG_CHECK
#define PYBIND11_LONG_CHECK(o)
Definition: wrap/pybind11/include/pybind11/detail/common.h:355
sequence_slow_readwrite::decrement
void decrement()
Definition: pytypes.h:1253
list_item::set
static void set(handle obj, const IdxType &index, handle val)
Definition: pytypes.h:1111
dict
Definition: pytypes.h:2065
dict_readonly::reference
const value_type reference
Definition: pytypes.h:1268
raise_from
void raise_from(PyObject *type, const char *message)
Definition: pytypes.h:780
object_api::operator|=
object operator|=(object_api const &other)
isinstance
bool isinstance(handle obj)
Definition: pytypes.h:825
data
int data[]
Definition: Map_placement_new.cpp:1
sequence_fast_readonly::increment
void increment()
Definition: pytypes.h:1231
bytearray::bytearray
bytearray(const char *c, const SzType &n)
Definition: pytypes.h:1719
sequence::begin
detail::sequence_iterator begin() const
Definition: pytypes.h:2120
handle
Definition: pytypes.h:217
generic_iterator::generic_iterator
generic_iterator(handle seq, ssize_t index)
Definition: pytypes.h:1154
arrow_proxy::value
T value
Definition: pytypes.h:1212
tuple::tuple
tuple(SzType size=0)
Definition: pytypes.h:2041
sequence
Definition: pytypes.h:2104
sequence_item::key_type
size_t key_type
Definition: pytypes.h:1078
handle::cast
T cast() const
Definition: cast.h:1110
tuple_accessor
accessor< accessor_policies::tuple_item > tuple_accessor
Definition: pytypes.h:67
tuple::operator[]
detail::item_accessor operator[](T &&o) const
Definition: pytypes.h:2050
type::handle_of
static handle handle_of()
Definition: cast.h:1684
reinterpret_borrow
T reinterpret_borrow(handle h)
Definition: pytypes.h:450
delattr
void delattr(handle obj, handle name)
Definition: pytypes.h:861
arg_v
Definition: cast.h:1304
error_fetch_and_normalize::error_fetch_and_normalize
error_fetch_and_normalize(const char *called)
Definition: pytypes.h:497
iterator::iterator_category
std::input_iterator_tag iterator_category
Definition: pytypes.h:1428
sequence_fast_readonly::decrement
void decrement()
Definition: pytypes.h:1232
object_api::operator<<=
object operator<<=(object_api const &other)
error_fetch_and_normalize
Definition: pytypes.h:487
PyStaticMethod_Check
bool PyStaticMethod_Check(PyObject *o)
Definition: pytypes.h:1323
return_value_policy::copy
@ copy
args_are_all_keyword_or_ds
constexpr bool args_are_all_keyword_or_ds()
Definition: pytypes.h:2061
args_proxy::operator*
kwargs_proxy operator*() const
Definition: pytypes.h:1333
handle::inc_ref_counter
static std::size_t inc_ref_counter(std::size_t add)
Definition: pytypes.h:326
object::object
object()=default
PYBIND11_EXPORT_EXCEPTION
#define PYBIND11_EXPORT_EXCEPTION
Definition: wrap/pybind11/include/pybind11/detail/common.h:163
object::release
handle release()
Definition: pytypes.h:368
error_fetch_and_normalize::m_type
object m_type
Definition: pytypes.h:703
list_item
Definition: pytypes.h:1098
memoryview::from_buffer
static memoryview from_buffer(const void *ptr, ssize_t itemsize, const char *format, detail::any_container< ssize_t > shape, detail::any_container< ssize_t > strides)
Definition: pytypes.h:2297
memoryview::from_buffer
static memoryview from_buffer(T *ptr, detail::any_container< ssize_t > shape, detail::any_container< ssize_t > strides, bool readonly=false)
Definition: pytypes.h:2307
dict::clear
void clear()
Definition: pytypes.h:2084
get_function
handle get_function(handle value)
Definition: pytypes.h:928
str::str
str(const char *c="")
Definition: pytypes.h:1542
generic_iterator::operator--
It & operator--()
Definition: pytypes.h:1171
handle::handle
handle(T ptr)
Definition: pytypes.h:227
add
graph add(PriorFactor< Pose2 >(1, priorMean, priorNoise))
arg
Definition: cast.h:1277
iterator::operator!=
friend bool operator!=(const iterator &a, const iterator &b)
Definition: pytypes.h:1477
anyset::contains
bool contains(T &&val) const
Definition: pytypes.h:2176
list::insert
void insert(const IdxType &index, ValType &&val)
Definition: pytypes.h:2153
object_api::operator>>
object operator>>(object_api const &other) const
object_api::get_type
handle get_type() const
Definition: pytypes.h:2491
slice::compute
bool compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const
Definition: pytypes.h:1886
negation
Definition: wrap/pybind11/include/pybind11/detail/common.h:699
gtsam::utils.visual_isam.step
def step(data, isam, result, truth, currPoseIndex, isamArgs=())
Definition: visual_isam.py:82
sequence_slow_readwrite::sequence_slow_readwrite
sequence_slow_readwrite(handle obj, ssize_t index)
Definition: pytypes.h:1249
arrow_proxy::arrow_proxy
arrow_proxy(T &&value) noexcept
Definition: pytypes.h:1215
info
else if n * info
Definition: 3rdparty/Eigen/lapack/cholesky.cpp:18
generic_iterator::operator<
friend bool operator<(const It &a, const It &b)
Definition: pytypes.h:1202
bytearray
Definition: pytypes.h:1714
object_or_cast
auto object_or_cast(T &&o) -> decltype(std::forward< T >(o))
Definition: pytypes.h:970
dict::size
size_t size() const
Definition: pytypes.h:2080
object::borrowed_t
Definition: pytypes.h:420
object_api::operator~
object operator~() const
memoryview
Definition: pytypes.h:2241
sequence::operator[]
detail::item_accessor operator[](T &&o) const
Definition: pytypes.h:2117
is_ds_unpacking
std::is_same< kwargs_proxy, T > is_ds_unpacking
Definition: pytypes.h:1342
PYBIND11_NAMESPACE
Definition: test_custom_type_casters.cpp:24
object_api::is
bool is(object_api const &other) const
Equivalent to obj is other in Python.
Definition: pytypes.h:146
Eigen::Triplet
A small structure to hold a non zero as a triplet (i,j,value).
Definition: SparseUtil.h:162
int_::int_
int_(T value)
Definition: pytypes.h:1800
cpp_function
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
Definition: pybind11.h:82
common.h
args_proxy::args_proxy
args_proxy(handle h)
Definition: pytypes.h:1332
handle::inc_ref_counter
static std::size_t inc_ref_counter()
Definition: pytypes.h:333
dict_getitem
PyObject * dict_getitem(PyObject *v, PyObject *key)
Definition: pytypes.h:958
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1013
str::str
str(const char *c, const SzType &n)
Definition: pytypes.h:1529
simple_collector
Definition: cast.h:1489
kwargs_proxy
Definition: pytypes.h:1325
size_t
std::size_t size_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:476
bool_::bool_
bool_(bool value)
Definition: pytypes.h:1762
buffer_info.h
set::add
bool add(T &&val)
Definition: pytypes.h:2194
bytearray::size
size_t size() const
Definition: pytypes.h:1730
tuple::operator[]
detail::tuple_accessor operator[](size_t index) const
Definition: pytypes.h:2048
object::object
object(object &&other) noexcept
Move constructor; steals the object from other and preserves its reference count.
Definition: pytypes.h:359
generic_iterator::operator->
pointer operator->() const
Definition: pytypes.h:1160
PYBIND11_INPLACE_OP
#define PYBIND11_INPLACE_OP(iop)
Definition: pytypes.h:397
PYBIND11_MATH_OPERATOR_UNARY
#define PYBIND11_MATH_OPERATOR_UNARY(op, fn)
Definition: pytypes.h:2504
is_keyword
std::is_base_of< arg, T > is_keyword
Python argument categories (using PEP 448 terms)
Definition: pytypes.h:1338
tuple_item::set
static void set(handle obj, const IdxType &index, handle val)
Definition: pytypes.h:1132
str
Definition: pytypes.h:1524
key
const gtsam::Symbol key('X', 0)
set
void set(Container &c, Position position, const Value &value)
Definition: stdlist_overload.cpp:37
bytearray::bytearray
bytearray(const std::string &s)
Definition: pytypes.h:1728
dict_readonly::obj
handle obj
Definition: pytypes.h:1284
object::operator=
object & operator=(object &&other) noexcept
Definition: pytypes.h:387
tuple_item
Definition: pytypes.h:1119
unpacking_collector
Helper class which collects positional, keyword, * and ** arguments for a Python function call.
Definition: cast.h:1515
handle::handle
handle(T &obj)
Enable implicit conversion through T::operator PyObject *().
Definition: pytypes.h:238
object_api::ref_count
int ref_count() const
Return the object's current reference count.
Definition: pytypes.h:185
set::clear
void clear()
Definition: pytypes.h:2197
a
ArrayXXi a
Definition: Array_initializer_list_23_cxx11.cpp:1
isinstance< object >
bool isinstance< object >(handle obj)
Definition: pytypes.h:837
PYBIND11_OBJECT_DEFAULT
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
Definition: pytypes.h:1411
object_api::operator-
object operator-() const
tuple_iterator
generic_iterator< iterator_policies::sequence_fast_readonly > tuple_iterator
Definition: pytypes.h:1291
accessor
Definition: pytypes.h:53
tuple::end
detail::tuple_iterator end() const
Definition: pytypes.h:2054
iterator::operator->
pointer operator->() const
Definition: pytypes.h:1456
object_api::operator/=
object operator/=(object_api const &other)
generic_iterator::operator++
It operator++(int)
Definition: pytypes.h:1166
dict_readonly::iterator_category
std::forward_iterator_tag iterator_category
Definition: pytypes.h:1266
sequence_slow_readwrite::advance
void advance(ssize_t n)
Definition: pytypes.h:1254
dict::contains
bool contains(T &&key) const
Definition: pytypes.h:2086
handle::ptr
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:241
tuple::size
size_t size() const
Definition: pytypes.h:2046
tuple_item::get
static object get(handle obj, const IdxType &index)
Definition: pytypes.h:1123
iterator::advance
void advance()
Definition: pytypes.h:1480
generic_iterator::operator+
friend It operator+(difference_type n, const It &b)
Definition: pytypes.h:1193
memoryview::from_buffer
static memoryview from_buffer(void *ptr, ssize_t itemsize, const char *format, detail::any_container< ssize_t > shape, detail::any_container< ssize_t > strides, bool readonly=false)
dict_readonly::dict_readonly
dict_readonly(handle obj, ssize_t pos)
Definition: pytypes.h:1272
sequence_fast_readonly::iterator_category
std::random_access_iterator_tag iterator_category
Definition: pytypes.h:1222
iterator::operator==
friend bool operator==(const iterator &a, const iterator &b)
Definition: pytypes.h:1476
error_already_set::type
const object & type() const
Definition: pytypes.h:766
sequence_item
Definition: pytypes.h:1077
arrow_proxy::operator->
T * operator->() const
Definition: pytypes.h:1216
PYBIND11_WARNING_DISABLE_MSVC
PYBIND11_WARNING_PUSH PYBIND11_WARNING_DISABLE_MSVC(5054) PYBIND11_WARNING_POP static_assert(EIGEN_VERSION_AT_LEAST(3
sequence::operator[]
detail::sequence_accessor operator[](size_t index) const
Definition: pytypes.h:2115
handle::handle
handle()=default
The default constructor creates a handle with a nullptr-valued pointer.
ssize_t_cast
ssize_t ssize_t_cast(const IntType &val)
Definition: wrap/pybind11/include/pybind11/detail/common.h:479
dict::empty
bool empty() const
Definition: pytypes.h:2081
obj_attr::get
static object get(handle obj, handle key)
Definition: pytypes.h:1049
iter
iterator iter(handle obj)
Definition: pytypes.h:2428
iterable
Definition: pytypes.h:1517
list::list
list(SzType size=0)
Definition: pytypes.h:2130
object::object
object(handle h, borrowed_t)
Definition: pytypes.h:432
float_::float_
float_(double value=.0)
Definition: pytypes.h:1839
handle::throw_gilstate_error
void throw_gilstate_error(const std::string &function_name) const
Definition: pytypes.h:301
str::str
str(handle h)
Definition: pytypes.h:1574
std
Definition: BFloat16.h:88
item_accessor
accessor< accessor_policies::generic_item > item_accessor
Definition: pytypes.h:64
dict::begin
detail::dict_iterator begin() const
Definition: pytypes.h:2082
args
Definition: pytypes.h:2163
error_fetch_and_normalize::format_value_and_trace
std::string format_value_and_trace() const
Definition: pytypes.h:557
buffer_info
Information record describing a Python buffer object.
Definition: buffer_info.h:46
Eigen::array::size
EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE std::size_t size()
Definition: EmulateArray.h:44
args_proxy
Definition: pytypes.h:1330
sequence_fast_readonly::sequence_fast_readonly
sequence_fast_readonly(handle obj, ssize_t n)
Definition: pytypes.h:1227
sequence_item::get
static object get(handle obj, const IdxType &index)
Definition: pytypes.h:1081
generic_iterator::value_type
typename Policy::value_type value_type
Definition: pytypes.h:1149
sequence_slow_readwrite
Full read and write access using the sequence protocol: see detail::sequence_accessor
Definition: pytypes.h:1242
str_attr::key_type
const char * key_type
Definition: pytypes.h:1054
tuple
Definition: pytypes.h:2035
generic_iterator::operator*
reference operator*() const
Definition: pytypes.h:1157
is_pyobject
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
Definition: pytypes.h:72
list::operator[]
detail::list_accessor operator[](size_t index) const
Definition: pytypes.h:2137
memoryview::from_memory
static memoryview from_memory(void *mem, ssize_t size, bool readonly=false)
Definition: pytypes.h:2339
object_api::doc
str_attr_accessor doc() const
Get or set the object's docstring, i.e. obj.__doc__.
Definition: pytypes.h:2486
v
Array< int, Dynamic, 1 > v
Definition: Array_initializer_list_vector_cxx11.cpp:1
float_
Definition: pytypes.h:1828
handle::dec_ref
const handle & dec_ref() const &
Definition: pytypes.h:267
object::object
object(handle h, stolen_t)
Definition: pytypes.h:433
list::append
void append(T &&val)
Definition: pytypes.h:2145
object_api::operator<=
bool operator<=(object_api const &other) const
Definition: pytypes.h:153
iterator::operator++
iterator operator++(int)
Definition: pytypes.h:1441
list_iterator
generic_iterator< iterator_policies::sequence_fast_readonly > list_iterator
Definition: pytypes.h:1292
PyIterable_Check
bool PyIterable_Check(PyObject *obj)
Definition: pytypes.h:1301
sequence_slow_readwrite::equal
bool equal(const sequence_slow_readwrite &b) const
Definition: pytypes.h:1255
object_api::operator&=
object operator&=(object_api const &other)
str::raw_str
static PyObject * raw_str(PyObject *op)
Return string representation – always returns a new reference, even if already a str.
Definition: pytypes.h:1604
accessor_policies
Definition: pytypes.h:54
PYBIND11_MATH_OPERATOR_BINARY
#define PYBIND11_MATH_OPERATOR_BINARY(op, fn)
Definition: pytypes.h:2513
object_api::operator[]
item_accessor operator[](handle key) const
Definition: pytypes.h:2447
pybind11
Definition: wrap/pybind11/pybind11/__init__.py:1
function
Definition: pytypes.h:2205
gtsam.examples.DogLegOptimizerExample.float
float
Definition: DogLegOptimizerExample.py:113
generic_item::set
static void set(handle obj, handle key, handle val)
Definition: pytypes.h:1070
PYBIND11_MATH_OPERATOR_BINARY_INPLACE
#define PYBIND11_MATH_OPERATOR_BINARY_INPLACE(iop, fn)
Definition: pytypes.h:2522
object_api::attr
obj_attr_accessor attr(handle key) const
Definition: pytypes.h:2459
error_already_set::discard_as_unraisable
void discard_as_unraisable(object err_context)
Definition: pytypes.h:746
object::operator=
object & operator=(const object &other)
Definition: pytypes.h:374
len_hint
size_t len_hint(handle h)
Definition: pytypes.h:2409
weakref::raw_weakref
static PyObject * raw_weakref(PyObject *o)
Definition: pytypes.h:1864
len
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2399
dict::raw_dict
static PyObject * raw_dict(PyObject *op)
Call the dict Python type – always returns a new reference.
Definition: pytypes.h:2096
PYBIND11_DEPRECATED
PYBIND11_DEPRECATED("make_simple_namespace should be replaced with " "py::module_::import(\"types\").attr(\"SimpleNamespace\") ") object make_simple_namespace(Args &&...args_)
Definition: pybind11.h:1293
object::cast
T cast() const &
Definition: cast.h:1169
handle::ptr
PyObject *& ptr()
Definition: pytypes.h:242
bytes::string_op
T string_op() const
Definition: pytypes.h:1663
object_api::operator|
object operator|(object_api const &other) const
none
Definition: pytypes.h:1744
pyobject_tag
Tag and check to identify a class which implements the Python object API.
Definition: pytypes.h:70
object_api::operator+
object operator+(object_api const &other) const
pos
Definition: example-NearestNeighbor.cpp:32
anyset::empty
bool empty() const
Definition: pytypes.h:2174
gtsam.examples.DogLegOptimizerExample.default
default
Definition: DogLegOptimizerExample.py:111
error_fetch_and_normalize::matches
bool matches(handle exc) const
Definition: pytypes.h:698
sequence_iterator
generic_iterator< iterator_policies::sequence_slow_readwrite > sequence_iterator
Definition: pytypes.h:1298
sequence_fast_readonly::ptr
PyObject ** ptr
Definition: pytypes.h:1238
PYBIND11_BYTES_FROM_STRING_AND_SIZE
#define PYBIND11_BYTES_FROM_STRING_AND_SIZE
Definition: wrap/pybind11/include/pybind11/detail/common.h:351
generic_iterator::operator!=
friend bool operator!=(const It &a, const It &b)
Definition: pytypes.h:1201
frozenset
Definition: pytypes.h:2200
object_api::operator^
object operator^(object_api const &other) const
return_value_policy::automatic_reference
@ automatic_reference
dict_readonly::dereference
reference dereference() const
Definition: pytypes.h:1275
reinterpret_steal
T reinterpret_steal(handle h)
Definition: pytypes.h:463
object_api::operator*
args_proxy operator*() const
Definition: pytypes.h:2471
dict_iterator
generic_iterator< iterator_policies::dict_readonly > dict_iterator
Definition: pytypes.h:1299
kwargs_proxy::kwargs_proxy
kwargs_proxy(handle h)
Definition: pytypes.h:1327
list::empty
bool empty() const
Definition: pytypes.h:2136
PyEllipsis_Check
bool PyEllipsis_Check(PyObject *o)
Definition: pytypes.h:1312
gtsam.examples.ShonanAveragingCLI.str
str
Definition: ShonanAveragingCLI.py:115
PYBIND11_SLICE_OBJECT
#define PYBIND11_SLICE_OBJECT
Definition: wrap/pybind11/include/pybind11/detail/common.h:361
Eigen::seq
internal::enable_if<!(symbolic::is_symbolic< FirstType >::value||symbolic::is_symbolic< LastType >::value), ArithmeticSequence< typename internal::cleanup_index_type< FirstType >::type, Index > >::type seq(FirstType f, LastType l)
Definition: ArithmeticSequence.h:234
PYBIND11_BYTES_CHECK
#define PYBIND11_BYTES_CHECK
Definition: wrap/pybind11/include/pybind11/detail/common.h:349
get
Container::iterator get(Container &c, Position position)
Definition: stdlist_overload.cpp:29
slice::compute
bool compute(ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const
Definition: pytypes.h:1895
enable_if_t
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
Definition: wrap/pybind11/include/pybind11/detail/common.h:640
list_item::get
static object get(handle obj, const IdxType &index)
Definition: pytypes.h:1102
generic_iterator::operator[]
reference operator[](difference_type n) const
Definition: pytypes.h:1159
generic_iterator::operator-
friend difference_type operator-(const It &a, const It &b)
Definition: pytypes.h:1198
sequence_slow_readwrite::distance_to
ssize_t distance_to(const sequence_slow_readwrite &b) const
Definition: pytypes.h:1256
test_callbacks.value
value
Definition: test_callbacks.py:158
error_fetch_and_normalize::m_value
object m_value
Definition: pytypes.h:703
object::is_borrowed
bool is_borrowed
Definition: pytypes.h:353
i
int i
Definition: BiCGSTAB_step_by_step.cpp:9
obj_class_name
const char * obj_class_name(PyObject *obj)
Definition: pytypes.h:470
pybind_wrapper_test_script.other
other
Definition: pybind_wrapper_test_script.py:42
generic_iterator::operator+
friend It operator+(const It &a, difference_type n)
Definition: pytypes.h:1189
sequence_slow_readwrite::dereference
reference dereference() const
Definition: pytypes.h:1251
Eigen::internal::cast
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
Definition: Eigen/src/Core/MathFunctions.h:460
iterator::operator*
reference operator*() const
Definition: pytypes.h:1448
object_api::PYBIND11_DEPRECATED
PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)") object call(Args &&...args) const
operator*
Vector3_ operator*(const Double_ &s, const Vector3_ &v)
Definition: InverseKinematicsExampleExpressions.cpp:42
obj_attr::set
static void set(handle obj, handle key, handle val)
Definition: pytypes.h:1050
iterator::sentinel
static iterator sentinel()
Definition: pytypes.h:1474
ellipsis
Definition: pytypes.h:1750
sequence_fast_readonly::advance
void advance(ssize_t n)
Definition: pytypes.h:1233
bytes::bytes
bytes(const std::string &s)
Definition: pytypes.h:1642
object_api::end
iterator end() const
Return a sentinel which ends iteration.
Definition: pytypes.h:2443
sequence::end
detail::sequence_iterator end() const
Definition: pytypes.h:2121
pybind11.msg
msg
Definition: wrap/pybind11/pybind11/__init__.py:4
anyset
Definition: pytypes.h:2170
repr
str repr(handle h)
Definition: pytypes.h:2420
list::begin
detail::list_iterator begin() const
Definition: pytypes.h:2142


gtsam
Author(s):
autogenerated on Wed May 15 2024 15:21:24