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 
36 /* A few forward declarations */
37 class handle;
38 class object;
39 class str;
40 class iterator;
41 class type;
42 struct arg;
43 struct arg_v;
44 
46 class args_proxy;
47 bool isinstance_generic(handle obj, const std::type_info &tp);
48 
49 // Accessor forward declarations
50 template <typename Policy>
51 class accessor;
52 namespace accessor_policies {
53 struct obj_attr;
54 struct str_attr;
55 struct generic_item;
56 struct sequence_item;
57 struct list_item;
58 struct tuple_item;
59 } // namespace accessor_policies
66 
68 class pyobject_tag {};
69 template <typename T>
70 using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
71 
76 template <typename Derived>
77 class object_api : public pyobject_tag {
78  const Derived &derived() const { return static_cast<const Derived &>(*this); }
79 
80 public:
85  iterator begin() const;
87  iterator end() const;
88 
95  item_accessor operator[](handle key) const;
97  item_accessor operator[](object &&key) const;
99  item_accessor operator[](const char *key) const;
100 
107  obj_attr_accessor attr(handle key) const;
109  obj_attr_accessor attr(object &&key) const;
111  str_attr_accessor attr(const char *key) const;
112 
119  args_proxy operator*() const;
120 
122  template <typename T>
123  bool contains(T &&item) const;
124 
136  typename... Args>
137  object operator()(Args &&...args) const;
139  typename... Args>
140  PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)")
141  object call(Args &&...args) const;
142 
144  bool is(object_api const &other) const { return derived().ptr() == other.derived().ptr(); }
146  bool is_none() const { return derived().ptr() == Py_None; }
148  bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); }
149  bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); }
150  bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); }
151  bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); }
152  bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); }
153  bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); }
154 
155  object operator-() const;
156  object operator~() const;
157  object operator+(object_api const &other) const;
158  object operator+=(object_api const &other) const;
159  object operator-(object_api const &other) const;
160  object operator-=(object_api const &other) const;
161  object operator*(object_api const &other) const;
162  object operator*=(object_api const &other) const;
163  object operator/(object_api const &other) const;
164  object operator/=(object_api const &other) const;
165  object operator|(object_api const &other) const;
166  object operator|=(object_api const &other) const;
167  object operator&(object_api const &other) const;
168  object operator&=(object_api const &other) const;
169  object operator^(object_api const &other) const;
170  object operator^=(object_api const &other) const;
171  object operator<<(object_api const &other) const;
172  object operator<<=(object_api const &other) const;
173  object operator>>(object_api const &other) const;
174  object operator>>=(object_api const &other) const;
175 
176  PYBIND11_DEPRECATED("Use py::str(obj) instead")
177  pybind11::str str() const;
178 
180  str_attr_accessor doc() const;
181 
183  int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); }
184 
185  // TODO PYBIND11_DEPRECATED(
186  // "Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()")
187  handle get_type() const;
188 
189 private:
190  bool rich_compare(object_api const &other, int value) const;
191 };
192 
193 template <typename T>
194 using is_pyobj_ptr_or_nullptr_t = detail::any_of<std::is_same<T, PyObject *>,
195  std::is_same<T, PyObject *const>,
196  std::is_same<T, std::nullptr_t>>;
197 
199 
200 #if !defined(PYBIND11_HANDLE_REF_DEBUG) && !defined(NDEBUG)
201 # define PYBIND11_HANDLE_REF_DEBUG
202 #endif
203 
215 class handle : public detail::object_api<handle> {
216 public:
218  handle() = default;
219 
222  template <typename T,
224  // NOLINTNEXTLINE(google-explicit-constructor)
225  handle(T ptr) : m_ptr(ptr) {}
226 
228  template <
229  typename T,
230  detail::enable_if_t<detail::all_of<detail::none_of<std::is_base_of<handle, T>,
231  detail::is_pyobj_ptr_or_nullptr_t<T>>,
232  std::is_convertible<T, PyObject *>>::value,
233  int> = 0>
234  // NOLINTNEXTLINE(google-explicit-constructor)
235  handle(T &obj) : m_ptr(obj) {}
236 
238  PyObject *ptr() const { return m_ptr; }
239  PyObject *&ptr() { return m_ptr; }
240 
246  const handle &inc_ref() const & {
247 #ifdef PYBIND11_HANDLE_REF_DEBUG
248  inc_ref_counter(1);
249 #endif
250  Py_XINCREF(m_ptr);
251  return *this;
252  }
253 
259  const handle &dec_ref() const & {
260  Py_XDECREF(m_ptr);
261  return *this;
262  }
263 
268  template <typename T>
269  T cast() const;
271  explicit operator bool() const { return m_ptr != nullptr; }
276  PYBIND11_DEPRECATED("Use obj1.is(obj2) instead")
277  bool operator==(const handle &h) const { return m_ptr == h.m_ptr; }
278  PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead")
279  bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }
280  PYBIND11_DEPRECATED("Use handle::operator bool() instead")
281  bool check() const { return m_ptr != nullptr; }
282 
283 protected:
284  PyObject *m_ptr = nullptr;
285 
286 #ifdef PYBIND11_HANDLE_REF_DEBUG
287 private:
289  thread_local std::size_t counter = 0;
290  counter += add;
291  return counter;
292  }
293 
294 public:
296 #endif
297 };
298 
309 class object : public handle {
310 public:
311  object() = default;
312  PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()")
313  object(handle h, bool is_borrowed) : handle(h) {
314  if (is_borrowed) {
315  inc_ref();
316  }
317  }
319  object(const object &o) : handle(o) { inc_ref(); }
321  object(object &&other) noexcept : handle(other) { other.m_ptr = nullptr; }
323  ~object() { dec_ref(); }
324 
331  PyObject *tmp = m_ptr;
332  m_ptr = nullptr;
333  return handle(tmp);
334  }
335 
336  object &operator=(const object &other) {
337  other.inc_ref();
338  // Use temporary variable to ensure `*this` remains valid while
339  // `Py_XDECREF` executes, in case `*this` is accessible from Python.
340  handle temp(m_ptr);
341  m_ptr = other.m_ptr;
342  temp.dec_ref();
343  return *this;
344  }
345 
346  object &operator=(object &&other) noexcept {
347  if (this != &other) {
348  handle temp(m_ptr);
349  m_ptr = other.m_ptr;
350  other.m_ptr = nullptr;
351  temp.dec_ref();
352  }
353  return *this;
354  }
355 
356  // Calling cast() on an object lvalue just copies (via handle::cast)
357  template <typename T>
358  T cast() const &;
359  // Calling on an object rvalue does a move, if needed and/or possible
360  template <typename T>
361  T cast() &&;
362 
363 protected:
364  // Tags for choosing constructors from raw PyObject *
365  struct borrowed_t {};
366  struct stolen_t {};
367 
369  template <typename T>
370  friend T reinterpret_borrow(handle);
371  template <typename T>
372  friend T reinterpret_steal(handle);
374 
375 public:
376  // Only accessible from derived classes and the reinterpret_* functions
377  object(handle h, borrowed_t) : handle(h) { inc_ref(); }
379 };
380 
394 template <typename T>
396  return {h, object::borrowed_t{}};
397 }
398 
407 template <typename T>
409  return {h, object::stolen_t{}};
410 }
411 
413 
414 // Equivalent to obj.__class__.__name__ (or obj.__name__ if obj is a class).
415 inline const char *obj_class_name(PyObject *obj) {
416  if (Py_TYPE(obj) == &PyType_Type) {
417  return reinterpret_cast<PyTypeObject *>(obj)->tp_name;
418  }
419  return Py_TYPE(obj)->tp_name;
420 }
421 
422 std::string error_string();
423 
425  // Immediate normalization is long-established behavior (starting with
426  // https://github.com/pybind/pybind11/commit/135ba8deafb8bf64a15b24d1513899eb600e2011
427  // from Sep 2016) and safest. Normalization could be deferred, but this could mask
428  // errors elsewhere, the performance gain is very minor in typical situations
429  // (usually the dominant bottleneck is EH unwinding), and the implementation here
430  // would be more complex.
431  explicit error_fetch_and_normalize(const char *called) {
432  PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
433  if (!m_type) {
434  pybind11_fail("Internal error: " + std::string(called)
435  + " called while "
436  "Python error indicator not set.");
437  }
438  const char *exc_type_name_orig = detail::obj_class_name(m_type.ptr());
439  if (exc_type_name_orig == nullptr) {
440  pybind11_fail("Internal error: " + std::string(called)
441  + " failed to obtain the name "
442  "of the original active exception type.");
443  }
444  m_lazy_error_string = exc_type_name_orig;
445  // PyErr_NormalizeException() may change the exception type if there are cascading
446  // failures. This can potentially be extremely confusing.
447  PyErr_NormalizeException(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
448  if (m_type.ptr() == nullptr) {
449  pybind11_fail("Internal error: " + std::string(called)
450  + " failed to normalize the "
451  "active exception.");
452  }
453  const char *exc_type_name_norm = detail::obj_class_name(m_type.ptr());
454  if (exc_type_name_orig == nullptr) {
455  pybind11_fail("Internal error: " + std::string(called)
456  + " failed to obtain the name "
457  "of the normalized active exception type.");
458  }
459  if (exc_type_name_norm != m_lazy_error_string) {
460  std::string msg = std::string(called)
461  + ": MISMATCH of original and normalized "
462  "active exception types: ";
463  msg += "ORIGINAL ";
464  msg += m_lazy_error_string;
465  msg += " REPLACED BY ";
466  msg += exc_type_name_norm;
467  msg += ": " + format_value_and_trace();
468  pybind11_fail(msg);
469  }
470  }
471 
474 
475  std::string format_value_and_trace() const {
476  std::string result;
477  std::string message_error_string;
478  if (m_value) {
479  auto value_str = reinterpret_steal<object>(PyObject_Str(m_value.ptr()));
480  if (!value_str) {
481  message_error_string = detail::error_string();
482  result = "<MESSAGE UNAVAILABLE DUE TO ANOTHER EXCEPTION>";
483  } else {
484  result = value_str.cast<std::string>();
485  }
486  } else {
487  result = "<MESSAGE UNAVAILABLE>";
488  }
489  if (result.empty()) {
490  result = "<EMPTY MESSAGE>";
491  }
492 
493  bool have_trace = false;
494  if (m_trace) {
495 #if !defined(PYPY_VERSION)
496  auto *tb = reinterpret_cast<PyTracebackObject *>(m_trace.ptr());
497 
498  // Get the deepest trace possible.
499  while (tb->tb_next) {
500  tb = tb->tb_next;
501  }
502 
503  PyFrameObject *frame = tb->tb_frame;
504  Py_XINCREF(frame);
505  result += "\n\nAt:\n";
506  while (frame) {
507 # if PY_VERSION_HEX >= 0x030900B1
508  PyCodeObject *f_code = PyFrame_GetCode(frame);
509 # else
510  PyCodeObject *f_code = frame->f_code;
511  Py_INCREF(f_code);
512 # endif
513  int lineno = PyFrame_GetLineNumber(frame);
514  result += " ";
515  result += handle(f_code->co_filename).cast<std::string>();
516  result += '(';
517  result += std::to_string(lineno);
518  result += "): ";
519  result += handle(f_code->co_name).cast<std::string>();
520  result += '\n';
521  Py_DECREF(f_code);
522 # if PY_VERSION_HEX >= 0x030900B1
523  auto *b_frame = PyFrame_GetBack(frame);
524 # else
525  auto *b_frame = frame->f_back;
526  Py_XINCREF(b_frame);
527 # endif
528  Py_DECREF(frame);
529  frame = b_frame;
530  }
531 
532  have_trace = true;
533 #endif
534  }
535 
536  if (!message_error_string.empty()) {
537  if (!have_trace) {
538  result += '\n';
539  }
540  result += "\nMESSAGE UNAVAILABLE DUE TO EXCEPTION: " + message_error_string;
541  }
542 
543  return result;
544  }
545 
546  std::string const &error_string() const {
547  if (!m_lazy_error_string_completed) {
548  m_lazy_error_string += ": " + format_value_and_trace();
549  m_lazy_error_string_completed = true;
550  }
551  return m_lazy_error_string;
552  }
553 
554  void restore() {
555  if (m_restore_called) {
556  pybind11_fail("Internal error: pybind11::detail::error_fetch_and_normalize::restore() "
557  "called a second time. ORIGINAL ERROR: "
558  + error_string());
559  }
560  PyErr_Restore(m_type.inc_ref().ptr(), m_value.inc_ref().ptr(), m_trace.inc_ref().ptr());
561  m_restore_called = true;
562  }
563 
564  bool matches(handle exc) const {
565  return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0);
566  }
567 
568  // Not protecting these for simplicity.
569  object m_type, m_value, m_trace;
570 
571 private:
572  // Only protecting invariants.
573  mutable std::string m_lazy_error_string;
574  mutable bool m_lazy_error_string_completed = false;
575  mutable bool m_restore_called = false;
576 };
577 
578 inline std::string error_string() {
579  return error_fetch_and_normalize("pybind11::detail::error_string").error_string();
580 }
581 
583 
584 #if defined(_MSC_VER)
585 # pragma warning(push)
586 # pragma warning(disable : 4275 4251)
587 // warning C4275: An exported class was derived from a class that wasn't exported.
588 // Can be ignored when derived from a STL class.
589 #endif
590 class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::exception {
595 public:
599  : m_fetched_error{new detail::error_fetch_and_normalize("pybind11::error_already_set"),
600  m_fetched_error_deleter} {}
601 
605  const char *what() const noexcept override;
606 
612  void restore() { m_fetched_error->restore(); }
613 
618  void discard_as_unraisable(object err_context) {
619  restore();
620  PyErr_WriteUnraisable(err_context.ptr());
621  }
625  void discard_as_unraisable(const char *err_context) {
626  discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context)));
627  }
628 
629  // Does nothing; provided for backwards compatibility.
630  PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated")
631  void clear() {}
632 
636  bool matches(handle exc) const { return m_fetched_error->matches(exc); }
637 
638  const object &type() const { return m_fetched_error->m_type; }
639  const object &value() const { return m_fetched_error->m_value; }
640  const object &trace() const { return m_fetched_error->m_trace; }
641 
642 private:
643  std::shared_ptr<detail::error_fetch_and_normalize> m_fetched_error;
644 
647  static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr);
648 };
649 #if defined(_MSC_VER)
650 # pragma warning(pop)
651 #endif
652 
655 inline void raise_from(PyObject *type, const char *message) {
656  // Based on _PyErr_FormatVFromCause:
657  // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405
658  // See https://github.com/pybind/pybind11/pull/2112 for details.
659  PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr;
660 
661  assert(PyErr_Occurred());
662  PyErr_Fetch(&exc, &val, &tb);
663  PyErr_NormalizeException(&exc, &val, &tb);
664  if (tb != nullptr) {
665  PyException_SetTraceback(val, tb);
666  Py_DECREF(tb);
667  }
668  Py_DECREF(exc);
669  assert(!PyErr_Occurred());
670 
671  PyErr_SetString(type, message);
672 
673  PyErr_Fetch(&exc, &val2, &tb);
674  PyErr_NormalizeException(&exc, &val2, &tb);
675  Py_INCREF(val);
676  PyException_SetCause(val2, val);
677  PyException_SetContext(val2, val);
678  PyErr_Restore(exc, val2, tb);
679 }
680 
684 inline void raise_from(error_already_set &err, PyObject *type, const char *message) {
685  err.restore();
686  raise_from(type, message);
687 }
688 
700 bool isinstance(handle obj) {
701  return T::check_(obj);
702 }
703 
705 bool isinstance(handle obj) {
706  return detail::isinstance_generic(obj, typeid(T));
707 }
708 
709 template <>
710 inline bool isinstance<handle>(handle) = delete;
711 template <>
712 inline bool isinstance<object>(handle obj) {
713  return obj.ptr() != nullptr;
714 }
715 
718 inline bool isinstance(handle obj, handle type) {
719  const auto result = PyObject_IsInstance(obj.ptr(), type.ptr());
720  if (result == -1) {
721  throw error_already_set();
722  }
723  return result != 0;
724 }
725 
728 inline bool hasattr(handle obj, handle name) {
729  return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1;
730 }
731 
732 inline bool hasattr(handle obj, const char *name) {
733  return PyObject_HasAttrString(obj.ptr(), name) == 1;
734 }
735 
736 inline void delattr(handle obj, handle name) {
737  if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) {
738  throw error_already_set();
739  }
740 }
741 
742 inline void delattr(handle obj, const char *name) {
743  if (PyObject_DelAttrString(obj.ptr(), name) != 0) {
744  throw error_already_set();
745  }
746 }
747 
748 inline object getattr(handle obj, handle name) {
749  PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr());
750  if (!result) {
751  throw error_already_set();
752  }
753  return reinterpret_steal<object>(result);
754 }
755 
756 inline object getattr(handle obj, const char *name) {
757  PyObject *result = PyObject_GetAttrString(obj.ptr(), name);
758  if (!result) {
759  throw error_already_set();
760  }
761  return reinterpret_steal<object>(result);
762 }
763 
764 inline object getattr(handle obj, handle name, handle default_) {
765  if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) {
766  return reinterpret_steal<object>(result);
767  }
768  PyErr_Clear();
769  return reinterpret_borrow<object>(default_);
770 }
771 
772 inline object getattr(handle obj, const char *name, handle default_) {
773  if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) {
774  return reinterpret_steal<object>(result);
775  }
776  PyErr_Clear();
777  return reinterpret_borrow<object>(default_);
778 }
779 
780 inline void setattr(handle obj, handle name, handle value) {
781  if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) {
782  throw error_already_set();
783  }
784 }
785 
786 inline void setattr(handle obj, const char *name, handle value) {
787  if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) {
788  throw error_already_set();
789  }
790 }
791 
792 inline ssize_t hash(handle obj) {
793  auto h = PyObject_Hash(obj.ptr());
794  if (h == -1) {
795  throw error_already_set();
796  }
797  return h;
798 }
799 
801 
804  if (value) {
805  if (PyInstanceMethod_Check(value.ptr())) {
806  value = PyInstanceMethod_GET_FUNCTION(value.ptr());
807  } else if (PyMethod_Check(value.ptr())) {
808  value = PyMethod_GET_FUNCTION(value.ptr());
809  }
810  }
811  return value;
812 }
813 
814 // Reimplementation of python's dict helper functions to ensure that exceptions
815 // aren't swallowed (see #2862)
816 
817 // copied from cpython _PyDict_GetItemStringWithError
818 inline PyObject *dict_getitemstring(PyObject *v, const char *key) {
819  PyObject *kv = nullptr, *rv = nullptr;
820  kv = PyUnicode_FromString(key);
821  if (kv == nullptr) {
822  throw error_already_set();
823  }
824 
825  rv = PyDict_GetItemWithError(v, kv);
826  Py_DECREF(kv);
827  if (rv == nullptr && PyErr_Occurred()) {
828  throw error_already_set();
829  }
830  return rv;
831 }
832 
833 inline PyObject *dict_getitem(PyObject *v, PyObject *key) {
834  PyObject *rv = PyDict_GetItemWithError(v, key);
835  if (rv == nullptr && PyErr_Occurred()) {
836  throw error_already_set();
837  }
838  return rv;
839 }
840 
841 // Helper aliases/functions to support implicit casting of values given to python
842 // accessors/methods. When given a pyobject, this simply returns the pyobject as-is; for other C++
843 // type, the value goes through pybind11::cast(obj) to convert it to an `object`.
845 auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) {
846  return std::forward<T>(o);
847 }
848 // The following casting version is implemented in cast.h:
850 object object_or_cast(T &&o);
851 // Match a PyObject*, which we want to convert directly to handle via its converting constructor
852 inline handle object_or_cast(PyObject *ptr) { return ptr; }
853 
854 #if defined(_MSC_VER) && _MSC_VER < 1920
855 # pragma warning(push)
856 # pragma warning(disable : 4522) // warning C4522: multiple assignment operators specified
857 #endif
858 template <typename Policy>
859 class accessor : public object_api<accessor<Policy>> {
860  using key_type = typename Policy::key_type;
861 
862 public:
863  accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) {}
864  accessor(const accessor &) = default;
865  accessor(accessor &&) noexcept = default;
866 
867  // accessor overload required to override default assignment operator (templates are not
868  // allowed to replace default compiler-generated assignments).
869  void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); }
870  void operator=(const accessor &a) & { operator=(handle(a)); }
871 
872  template <typename T>
873  void operator=(T &&value) && {
874  Policy::set(obj, key, object_or_cast(std::forward<T>(value)));
875  }
876  template <typename T>
877  void operator=(T &&value) & {
878  get_cache() = ensure_object(object_or_cast(std::forward<T>(value)));
879  }
880 
881  template <typename T = Policy>
883  "Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
884  explicit
885  operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value
886  || std::is_same<T, accessor_policies::obj_attr>::value,
887  bool>() const {
888  return hasattr(obj, key);
889  }
890  template <typename T = Policy>
891  PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
892  explicit
894  return obj.contains(key);
895  }
896 
897  // NOLINTNEXTLINE(google-explicit-constructor)
898  operator object() const { return get_cache(); }
899  PyObject *ptr() const { return get_cache().ptr(); }
900  template <typename T>
901  T cast() const {
902  return get_cache().template cast<T>();
903  }
904 
905 private:
906  static object ensure_object(object &&o) { return std::move(o); }
907  static object ensure_object(handle h) { return reinterpret_borrow<object>(h); }
908 
909  object &get_cache() const {
910  if (!cache) {
911  cache = Policy::get(obj, key);
912  }
913  return cache;
914  }
915 
916 private:
919  mutable object cache;
920 };
921 #if defined(_MSC_VER) && _MSC_VER < 1920
922 # pragma warning(pop)
923 #endif
924 
926 struct obj_attr {
927  using key_type = object;
928  static object get(handle obj, handle key) { return getattr(obj, key); }
929  static void set(handle obj, handle key, handle val) { setattr(obj, key, val); }
930 };
931 
932 struct str_attr {
933  using key_type = const char *;
934  static object get(handle obj, const char *key) { return getattr(obj, key); }
935  static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); }
936 };
937 
938 struct generic_item {
939  using key_type = object;
940 
941  static object get(handle obj, handle key) {
942  PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr());
943  if (!result) {
944  throw error_already_set();
945  }
946  return reinterpret_steal<object>(result);
947  }
948 
949  static void set(handle obj, handle key, handle val) {
950  if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) {
951  throw error_already_set();
952  }
953  }
954 };
955 
957  using key_type = size_t;
958 
960  static object get(handle obj, const IdxType &index) {
961  PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index));
962  if (!result) {
963  throw error_already_set();
964  }
965  return reinterpret_steal<object>(result);
966  }
967 
969  static void set(handle obj, const IdxType &index, handle val) {
970  // PySequence_SetItem does not steal a reference to 'val'
971  if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) {
972  throw error_already_set();
973  }
974  }
975 };
976 
977 struct list_item {
978  using key_type = size_t;
979 
981  static object get(handle obj, const IdxType &index) {
982  PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index));
983  if (!result) {
984  throw error_already_set();
985  }
986  return reinterpret_borrow<object>(result);
987  }
988 
990  static void set(handle obj, const IdxType &index, handle val) {
991  // PyList_SetItem steals a reference to 'val'
992  if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
993  throw error_already_set();
994  }
995  }
996 };
997 
998 struct tuple_item {
999  using key_type = size_t;
1000 
1002  static object get(handle obj, const IdxType &index) {
1003  PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index));
1004  if (!result) {
1005  throw error_already_set();
1006  }
1007  return reinterpret_borrow<object>(result);
1008  }
1009 
1011  static void set(handle obj, const IdxType &index, handle val) {
1012  // PyTuple_SetItem steals a reference to 'val'
1013  if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
1014  throw error_already_set();
1015  }
1016  }
1017 };
1019 
1020 template <typename Policy>
1022 class generic_iterator : public Policy {
1024 
1025 public:
1027  using iterator_category = typename Policy::iterator_category;
1028  using value_type = typename Policy::value_type;
1029  using reference = typename Policy::reference;
1030  using pointer = typename Policy::pointer;
1031 
1032  generic_iterator() = default;
1033  generic_iterator(handle seq, ssize_t index) : Policy(seq, index) {}
1034 
1035  // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1036  reference operator*() const { return Policy::dereference(); }
1037  // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1038  reference operator[](difference_type n) const { return *(*this + n); }
1039  pointer operator->() const { return **this; }
1040 
1042  Policy::increment();
1043  return *this;
1044  }
1046  auto copy = *this;
1047  Policy::increment();
1048  return copy;
1049  }
1051  Policy::decrement();
1052  return *this;
1053  }
1055  auto copy = *this;
1056  Policy::decrement();
1057  return copy;
1058  }
1060  Policy::advance(n);
1061  return *this;
1062  }
1064  Policy::advance(-n);
1065  return *this;
1066  }
1067 
1068  friend It operator+(const It &a, difference_type n) {
1069  auto copy = a;
1070  return copy += n;
1071  }
1072  friend It operator+(difference_type n, const It &b) { return b + n; }
1073  friend It operator-(const It &a, difference_type n) {
1074  auto copy = a;
1075  return copy -= n;
1076  }
1077  friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); }
1078 
1079  friend bool operator==(const It &a, const It &b) { return a.equal(b); }
1080  friend bool operator!=(const It &a, const It &b) { return !(a == b); }
1081  friend bool operator<(const It &a, const It &b) { return b - a > 0; }
1082  friend bool operator>(const It &a, const It &b) { return b < a; }
1083  friend bool operator>=(const It &a, const It &b) { return !(a < b); }
1084  friend bool operator<=(const It &a, const It &b) { return !(a > b); }
1085 };
1086 
1087 PYBIND11_NAMESPACE_BEGIN(iterator_policies)
1089 template <typename T>
1090 struct arrow_proxy {
1092 
1093  // NOLINTNEXTLINE(google-explicit-constructor)
1094  arrow_proxy(T &&value) noexcept : value(std::move(value)) {}
1095  T *operator->() const { return &value; }
1096 };
1097 
1100 protected:
1101  using iterator_category = std::random_access_iterator_tag;
1103  using reference = const handle; // PR #3263
1105 
1106  sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) {}
1107 
1108  // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1109  reference dereference() const { return *ptr; }
1110  void increment() { ++ptr; }
1111  void decrement() { --ptr; }
1112  void advance(ssize_t n) { ptr += n; }
1113  bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; }
1114  ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; }
1115 
1116 private:
1117  PyObject **ptr;
1118 };
1119 
1122 protected:
1123  using iterator_category = std::random_access_iterator_tag;
1127 
1128  sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) {}
1129 
1130  reference dereference() const { return {obj, static_cast<size_t>(index)}; }
1131  void increment() { ++index; }
1132  void decrement() { --index; }
1133  void advance(ssize_t n) { index += n; }
1134  bool equal(const sequence_slow_readwrite &b) const { return index == b.index; }
1135  ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; }
1136 
1137 private:
1140 };
1141 
1144 protected:
1145  using iterator_category = std::forward_iterator_tag;
1146  using value_type = std::pair<handle, handle>;
1147  using reference = const value_type; // PR #3263
1149 
1150  dict_readonly() = default;
1151  dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }
1152 
1153  // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1154  reference dereference() const { return {key, value}; }
1155  void increment() {
1156  if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) {
1157  pos = -1;
1158  }
1159  }
1160  bool equal(const dict_readonly &b) const { return pos == b.pos; }
1161 
1162 private:
1164  PyObject *key = nullptr, *value = nullptr;
1165  ssize_t pos = -1;
1166 };
1167 PYBIND11_NAMESPACE_END(iterator_policies)
1168 
1169 #if !defined(PYPY_VERSION)
1172 #else
1175 #endif
1176 
1179 
1180 inline bool PyIterable_Check(PyObject *obj) {
1181  PyObject *iter = PyObject_GetIter(obj);
1182  if (iter) {
1183  Py_DECREF(iter);
1184  return true;
1185  }
1186  PyErr_Clear();
1187  return false;
1188 }
1189 
1190 inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
1191 inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }
1192 
1193 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
1194 inline bool PyUnicode_Check_Permissive(PyObject *o) {
1195  return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o);
1196 }
1197 # define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive
1198 #else
1199 # define PYBIND11_STR_CHECK_FUN PyUnicode_Check
1200 #endif
1201 
1202 inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; }
1203 
1204 class kwargs_proxy : public handle {
1205 public:
1206  explicit kwargs_proxy(handle h) : handle(h) {}
1207 };
1208 
1209 class args_proxy : public handle {
1210 public:
1211  explicit args_proxy(handle h) : handle(h) {}
1212  kwargs_proxy operator*() const { return kwargs_proxy(*this); }
1213 };
1214 
1216 template <typename T>
1217 using is_keyword = std::is_base_of<arg, T>;
1218 template <typename T>
1219 using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking
1220 template <typename T>
1221 using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking
1222 template <typename T>
1224 template <typename T>
1226 
1227 // Call argument collector forward declarations
1228 template <return_value_policy policy = return_value_policy::automatic_reference>
1229 class simple_collector;
1230 template <return_value_policy policy = return_value_policy::automatic_reference>
1231 class unpacking_collector;
1232 
1234 
1235 // TODO: After the deprecated constructors are removed, this macro can be simplified by
1236 // inheriting ctors: `using Parent::Parent`. It's not an option right now because
1237 // the `using` statement triggers the parent deprecation warning even if the ctor
1238 // isn't even used.
1239 #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1240 public: \
1241  PYBIND11_DEPRECATED("Use reinterpret_borrow<" #Name ">() or reinterpret_steal<" #Name ">()") \
1242  Name(handle h, bool is_borrowed) \
1243  : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {} \
1244  Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {} \
1245  Name(handle h, stolen_t) : Parent(h, stolen_t{}) {} \
1246  PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
1247  bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \
1248  static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \
1249  template <typename Policy_> /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1250  Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) {}
1251 
1252 #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1253  PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1254  /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
1255  /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1256  Name(const object &o) \
1257  : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1258  if (!m_ptr) \
1259  throw ::pybind11::error_already_set(); \
1260  } \
1261  /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1262  Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1263  if (!m_ptr) \
1264  throw ::pybind11::error_already_set(); \
1265  }
1266 
1267 #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \
1268  PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1269  Name() : Parent() {}
1270 
1271 #define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \
1272  ::pybind11::type_error("Object of type '" \
1273  + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) \
1274  + "' is not an instance of '" #Name "'")
1275 
1276 #define PYBIND11_OBJECT(Name, Parent, CheckFun) \
1277  PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1278  /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
1279  /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1280  Name(const object &o) : Parent(o) { \
1281  if (m_ptr && !check_(m_ptr)) \
1282  throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1283  } \
1284  /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1285  Name(object &&o) : Parent(std::move(o)) { \
1286  if (m_ptr && !check_(m_ptr)) \
1287  throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1288  }
1289 
1290 #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
1291  PYBIND11_OBJECT(Name, Parent, CheckFun) \
1292  Name() : Parent() {}
1293 
1296 
1305 class iterator : public object {
1306 public:
1307  using iterator_category = std::input_iterator_tag;
1310  using reference = const handle; // PR #3263
1311  using pointer = const handle *;
1312 
1313  PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)
1314 
1315  iterator &operator++() {
1316  advance();
1317  return *this;
1318  }
1319 
1321  auto rv = *this;
1322  advance();
1323  return rv;
1324  }
1325 
1326  // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1328  if (m_ptr && !value.ptr()) {
1329  auto &self = const_cast<iterator &>(*this);
1330  self.advance();
1331  }
1332  return value;
1333  }
1334 
1336  operator*();
1337  return &value;
1338  }
1339 
1353  static iterator sentinel() { return {}; }
1354 
1355  friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); }
1356  friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); }
1357 
1358 private:
1359  void advance() {
1360  value = reinterpret_steal<object>(PyIter_Next(m_ptr));
1361  if (PyErr_Occurred()) {
1362  throw error_already_set();
1363  }
1364  }
1365 
1366 private:
1367  object value = {};
1368 };
1369 
1370 class type : public object {
1371 public:
1372  PYBIND11_OBJECT(type, object, PyType_Check)
1373 
1374 
1375  static handle handle_of(handle h) { return handle((PyObject *) Py_TYPE(h.ptr())); }
1376 
1378  static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); }
1379 
1380  // Defined in pybind11/cast.h
1384  template <typename T>
1385  static handle handle_of();
1386 
1390  template <typename T>
1391  static type of() {
1392  return type(type::handle_of<T>(), borrowed_t{});
1393  }
1394 };
1395 
1396 class iterable : public object {
1397 public:
1399 };
1400 
1401 class bytes;
1402 
1403 class str : public object {
1404 public:
1406 
1408  str(const char *c, const SzType &n)
1409  : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1410  if (!m_ptr) {
1411  pybind11_fail("Could not allocate string object!");
1412  }
1413  }
1414 
1415  // 'explicit' is explicitly omitted from the following constructors to allow implicit
1416  // conversion to py::str from C++ string-like objects
1417  // NOLINTNEXTLINE(google-explicit-constructor)
1418  str(const char *c = "") : object(PyUnicode_FromString(c), stolen_t{}) {
1419  if (!m_ptr) {
1420  pybind11_fail("Could not allocate string object!");
1421  }
1422  }
1423 
1424  // NOLINTNEXTLINE(google-explicit-constructor)
1425  str(const std::string &s) : str(s.data(), s.size()) {}
1426 
1427 #ifdef PYBIND11_HAS_STRING_VIEW
1428  // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
1430  // NOLINTNEXTLINE(google-explicit-constructor)
1431  str(T s) : str(s.data(), s.size()) {}
1432 
1433 # ifdef PYBIND11_HAS_U8STRING
1434  // reinterpret_cast here is safe (C++20 guarantees char8_t has the same size/alignment as char)
1435  // NOLINTNEXTLINE(google-explicit-constructor)
1436  str(std::u8string_view s) : str(reinterpret_cast<const char *>(s.data()), s.size()) {}
1437 # endif
1438 
1439 #endif
1440 
1441  explicit str(const bytes &b);
1442 
1447  explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) {
1448  if (!m_ptr) {
1449  throw error_already_set();
1450  }
1451  }
1452 
1453  // NOLINTNEXTLINE(google-explicit-constructor)
1454  operator std::string() const {
1455  object temp = *this;
1456  if (PyUnicode_Check(m_ptr)) {
1457  temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
1458  if (!temp) {
1459  throw error_already_set();
1460  }
1461  }
1462  char *buffer = nullptr;
1463  ssize_t length = 0;
1464  if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {
1465  throw error_already_set();
1466  }
1467  return std::string(buffer, (size_t) length);
1468  }
1469 
1470  template <typename... Args>
1471  str format(Args &&...args) const {
1472  return attr("format")(std::forward<Args>(args)...);
1473  }
1474 
1475 private:
1477  static PyObject *raw_str(PyObject *op) {
1478  PyObject *str_value = PyObject_Str(op);
1479  return str_value;
1480  }
1481 };
1483 
1484 inline namespace literals {
1488 inline str operator"" _s(const char *s, size_t size) { return {s, size}; }
1489 } // namespace literals
1490 
1493 class bytes : public object {
1494 public:
1496 
1497  // Allow implicit conversion:
1498  // NOLINTNEXTLINE(google-explicit-constructor)
1499  bytes(const char *c = "") : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) {
1500  if (!m_ptr) {
1501  pybind11_fail("Could not allocate bytes object!");
1502  }
1503  }
1504 
1506  bytes(const char *c, const SzType &n)
1508  if (!m_ptr) {
1509  pybind11_fail("Could not allocate bytes object!");
1510  }
1511  }
1512 
1513  // Allow implicit conversion:
1514  // NOLINTNEXTLINE(google-explicit-constructor)
1515  bytes(const std::string &s) : bytes(s.data(), s.size()) {}
1516 
1517  explicit bytes(const pybind11::str &s);
1518 
1519  // NOLINTNEXTLINE(google-explicit-constructor)
1520  operator std::string() const { return string_op<std::string>(); }
1521 
1522 #ifdef PYBIND11_HAS_STRING_VIEW
1523  // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
1525  // NOLINTNEXTLINE(google-explicit-constructor)
1526  bytes(T s) : bytes(s.data(), s.size()) {}
1527 
1528  // Obtain a string view that views the current `bytes` buffer value. Note that this is only
1529  // valid so long as the `bytes` instance remains alive and so generally should not outlive the
1530  // lifetime of the `bytes` instance.
1531  // NOLINTNEXTLINE(google-explicit-constructor)
1532  operator std::string_view() const { return string_op<std::string_view>(); }
1533 #endif
1534 private:
1535  template <typename T>
1536  T string_op() const {
1537  char *buffer = nullptr;
1538  ssize_t length = 0;
1539  if (PyBytes_AsStringAndSize(m_ptr, &buffer, &length) != 0) {
1540  throw error_already_set();
1541  }
1542  return {buffer, static_cast<size_t>(length)};
1543  }
1544 };
1545 // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1546 // are included in the doxygen group; close here and reopen after as a workaround
1548 
1549 inline bytes::bytes(const pybind11::str &s) {
1550  object temp = s;
1551  if (PyUnicode_Check(s.ptr())) {
1552  temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));
1553  if (!temp) {
1554  throw error_already_set();
1555  }
1556  }
1557  char *buffer = nullptr;
1558  ssize_t length = 0;
1559  if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {
1560  throw error_already_set();
1561  }
1562  auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));
1563  if (!obj) {
1564  pybind11_fail("Could not allocate bytes object!");
1565  }
1566  m_ptr = obj.release().ptr();
1567 }
1568 
1569 inline str::str(const bytes &b) {
1570  char *buffer = nullptr;
1571  ssize_t length = 0;
1572  if (PyBytes_AsStringAndSize(b.ptr(), &buffer, &length) != 0) {
1573  throw error_already_set();
1574  }
1575  auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, length));
1576  if (!obj) {
1577  pybind11_fail("Could not allocate string object!");
1578  }
1579  m_ptr = obj.release().ptr();
1580 }
1581 
1584 class bytearray : public object {
1585 public:
1586  PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject)
1587 
1589  bytearray(const char *c, const SzType &n)
1590  : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1591  if (!m_ptr) {
1592  pybind11_fail("Could not allocate bytearray object!");
1593  }
1594  }
1595 
1596  bytearray() : bytearray("", 0) {}
1597 
1598  explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) {}
1599 
1600  size_t size() const { return static_cast<size_t>(PyByteArray_Size(m_ptr)); }
1601 
1602  explicit operator std::string() const {
1603  char *buffer = PyByteArray_AS_STRING(m_ptr);
1604  ssize_t size = PyByteArray_GET_SIZE(m_ptr);
1605  return std::string(buffer, static_cast<size_t>(size));
1606  }
1607 };
1608 // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1609 // are included in the doxygen group; close here and reopen after as a workaround
1611 
1614 class none : public object {
1615 public:
1617  none() : object(Py_None, borrowed_t{}) {}
1618 };
1619 
1620 class ellipsis : public object {
1621 public:
1623  ellipsis() : object(Py_Ellipsis, borrowed_t{}) {}
1624 };
1625 
1626 class bool_ : public object {
1627 public:
1628  PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool)
1629  bool_() : object(Py_False, borrowed_t{}) {}
1630  // Allow implicit conversion from and to `bool`:
1631  // NOLINTNEXTLINE(google-explicit-constructor)
1632  bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) {}
1633  // NOLINTNEXTLINE(google-explicit-constructor)
1634  operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; }
1635 
1636 private:
1638  static PyObject *raw_bool(PyObject *op) {
1639  const auto value = PyObject_IsTrue(op);
1640  if (value == -1) {
1641  return nullptr;
1642  }
1643  return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr();
1644  }
1645 };
1646 
1648 // Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1;
1649 // otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned).
1650 // (The distinction is critically important when casting a returned -1 error value to some other
1651 // unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes).
1652 template <typename Unsigned>
1653 Unsigned as_unsigned(PyObject *o) {
1654  if (PYBIND11_SILENCE_MSVC_C4127(sizeof(Unsigned) <= sizeof(unsigned long))) {
1655  unsigned long v = PyLong_AsUnsignedLong(o);
1656  return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1657  }
1658  unsigned long long v = PyLong_AsUnsignedLongLong(o);
1659  return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1660 }
1662 
1663 class int_ : public object {
1664 public:
1665  PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long)
1666  int_() : object(PyLong_FromLong(0), stolen_t{}) {}
1667  // Allow implicit conversion from C++ integral types:
1669  // NOLINTNEXTLINE(google-explicit-constructor)
1671  if (PYBIND11_SILENCE_MSVC_C4127(sizeof(T) <= sizeof(long))) {
1673  m_ptr = PyLong_FromLong((long) value);
1674  } else {
1675  m_ptr = PyLong_FromUnsignedLong((unsigned long) value);
1676  }
1677  } else {
1679  m_ptr = PyLong_FromLongLong((long long) value);
1680  } else {
1681  m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value);
1682  }
1683  }
1684  if (!m_ptr) {
1685  pybind11_fail("Could not allocate int object!");
1686  }
1687  }
1688 
1690  // NOLINTNEXTLINE(google-explicit-constructor)
1691  operator T() const {
1692  return std::is_unsigned<T>::value ? detail::as_unsigned<T>(m_ptr)
1693  : sizeof(T) <= sizeof(long) ? (T) PyLong_AsLong(m_ptr)
1694  : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
1695  }
1696 };
1697 
1698 class float_ : public object {
1699 public:
1700  PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)
1701  // Allow implicit conversion from float/double:
1702  // NOLINTNEXTLINE(google-explicit-constructor)
1703  float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1704  if (!m_ptr) {
1705  pybind11_fail("Could not allocate float object!");
1706  }
1707  }
1708  // NOLINTNEXTLINE(google-explicit-constructor)
1709  float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1710  if (!m_ptr) {
1711  pybind11_fail("Could not allocate float object!");
1712  }
1713  }
1714  // NOLINTNEXTLINE(google-explicit-constructor)
1715  operator float() const { return (float) PyFloat_AsDouble(m_ptr); }
1716  // NOLINTNEXTLINE(google-explicit-constructor)
1717  operator double() const { return (double) PyFloat_AsDouble(m_ptr); }
1718 };
1719 
1720 class weakref : public object {
1721 public:
1722  PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref)
1723  explicit weakref(handle obj, handle callback = {})
1724  : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) {
1725  if (!m_ptr) {
1726  if (PyErr_Occurred()) {
1727  throw error_already_set();
1728  }
1729  pybind11_fail("Could not allocate weak reference!");
1730  }
1731  }
1732 
1733 private:
1734  static PyObject *raw_weakref(PyObject *o) { return PyWeakref_NewRef(o, nullptr); }
1735 };
1736 
1737 class slice : public object {
1738 public:
1739  PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check)
1741  : object(PySlice_New(start.ptr(), stop.ptr(), step.ptr()), stolen_t{}) {
1742  if (!m_ptr) {
1743  pybind11_fail("Could not allocate slice object!");
1744  }
1745  }
1746 
1747 #ifdef PYBIND11_HAS_OPTIONAL
1748  slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t> step)
1749  : slice(index_to_object(start), index_to_object(stop), index_to_object(step)) {}
1750 #else
1751  slice(ssize_t start_, ssize_t stop_, ssize_t step_)
1752  : slice(int_(start_), int_(stop_), int_(step_)) {}
1753 #endif
1754 
1755  bool
1756  compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const {
1757  return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1758  (ssize_t) length,
1759  (ssize_t *) start,
1760  (ssize_t *) stop,
1761  (ssize_t *) step,
1762  (ssize_t *) slicelength)
1763  == 0;
1764  }
1765  bool compute(
1766  ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const {
1767  return PySlice_GetIndicesEx(
1768  (PYBIND11_SLICE_OBJECT *) m_ptr, length, start, stop, step, slicelength)
1769  == 0;
1770  }
1771 
1772 private:
1773  template <typename T>
1774  static object index_to_object(T index) {
1775  return index ? object(int_(*index)) : object(none());
1776  }
1777 };
1778 
1779 class capsule : public object {
1780 public:
1781  PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact)
1782  PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()")
1783  capsule(PyObject *ptr, bool is_borrowed)
1784  : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) {}
1785 
1786  explicit capsule(const void *value,
1787  const char *name = nullptr,
1788  void (*destructor)(PyObject *) = nullptr)
1789  : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) {
1790  if (!m_ptr) {
1791  throw error_already_set();
1792  }
1793  }
1794 
1795  PYBIND11_DEPRECATED("Please pass a destructor that takes a void pointer as input")
1796  capsule(const void *value, void (*destruct)(PyObject *))
1797  : object(PyCapsule_New(const_cast<void *>(value), nullptr, destruct), stolen_t{}) {
1798  if (!m_ptr) {
1799  throw error_already_set();
1800  }
1801  }
1802 
1803  capsule(const void *value, void (*destructor)(void *)) {
1804  m_ptr = PyCapsule_New(const_cast<void *>(value), nullptr, [](PyObject *o) {
1805  // guard if destructor called while err indicator is set
1806  error_scope error_guard;
1807  auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o));
1808  if (destructor == nullptr) {
1809  if (PyErr_Occurred()) {
1810  throw error_already_set();
1811  }
1812  pybind11_fail("Unable to get capsule context");
1813  }
1814  const char *name = get_name_in_error_scope(o);
1815  void *ptr = PyCapsule_GetPointer(o, name);
1816  if (ptr == nullptr) {
1817  throw error_already_set();
1818  }
1819  destructor(ptr);
1820  });
1821 
1822  if (!m_ptr || PyCapsule_SetContext(m_ptr, (void *) destructor) != 0) {
1823  throw error_already_set();
1824  }
1825  }
1826 
1827  explicit capsule(void (*destructor)()) {
1828  m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) {
1829  const char *name = get_name_in_error_scope(o);
1830  auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, name));
1831  if (destructor == nullptr) {
1832  throw error_already_set();
1833  }
1834  destructor();
1835  });
1836 
1837  if (!m_ptr) {
1838  throw error_already_set();
1839  }
1840  }
1841 
1842  template <typename T>
1843  operator T *() const { // NOLINT(google-explicit-constructor)
1844  return get_pointer<T>();
1845  }
1846 
1848  template <typename T = void>
1849  T *get_pointer() const {
1850  const auto *name = this->name();
1851  T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));
1852  if (!result) {
1853  throw error_already_set();
1854  }
1855  return result;
1856  }
1857 
1859  void set_pointer(const void *value) {
1860  if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0) {
1861  throw error_already_set();
1862  }
1863  }
1864 
1865  const char *name() const {
1866  const char *name = PyCapsule_GetName(m_ptr);
1867  if ((name == nullptr) && PyErr_Occurred()) {
1868  throw error_already_set();
1869  }
1870  return name;
1871  }
1872 
1874  void set_name(const char *new_name) {
1875  if (PyCapsule_SetName(m_ptr, new_name) != 0) {
1876  throw error_already_set();
1877  }
1878  }
1879 
1880 private:
1881  static const char *get_name_in_error_scope(PyObject *o) {
1882  error_scope error_guard;
1883 
1884  const char *name = PyCapsule_GetName(o);
1885  if ((name == nullptr) && PyErr_Occurred()) {
1886  // write out and consume error raised by call to PyCapsule_GetName
1887  PyErr_WriteUnraisable(o);
1888  }
1889 
1890  return name;
1891  }
1892 };
1893 
1894 class tuple : public object {
1895 public:
1896  PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple)
1897  template <typename SzType = ssize_t,
1899  // Some compilers generate link errors when using `const SzType &` here:
1900  explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) {
1901  if (!m_ptr) {
1902  pybind11_fail("Could not allocate tuple object!");
1903  }
1904  }
1905  size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
1906  bool empty() const { return size() == 0; }
1907  detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }
1910  return object::operator[](std::forward<T>(o));
1911  }
1912  detail::tuple_iterator begin() const { return {*this, 0}; }
1913  detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }
1914 };
1915 
1916 // We need to put this into a separate function because the Intel compiler
1917 // fails to compile enable_if_t<all_of<is_keyword_or_ds<Args>...>::value> part below
1918 // (tested with ICC 2021.1 Beta 20200827).
1919 template <typename... Args>
1920 constexpr bool args_are_all_keyword_or_ds() {
1921  return detail::all_of<detail::is_keyword_or_ds<Args>...>::value;
1922 }
1923 
1924 class dict : public object {
1925 public:
1926  PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)
1927  dict() : object(PyDict_New(), stolen_t{}) {
1928  if (!m_ptr) {
1929  pybind11_fail("Could not allocate dict object!");
1930  }
1931  }
1932  template <typename... Args,
1933  typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>,
1934  // MSVC workaround: it can't compile an out-of-line definition, so defer the
1935  // collector
1936  typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
1937  explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) {}
1938 
1939  size_t size() const { return (size_t) PyDict_Size(m_ptr); }
1940  bool empty() const { return size() == 0; }
1941  detail::dict_iterator begin() const { return {*this, 0}; }
1942  detail::dict_iterator end() const { return {}; }
1943  void clear() /* py-non-const */ { PyDict_Clear(ptr()); }
1944  template <typename T>
1945  bool contains(T &&key) const {
1946  return PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr()) == 1;
1947  }
1948 
1949 private:
1951  static PyObject *raw_dict(PyObject *op) {
1952  if (PyDict_Check(op)) {
1953  return handle(op).inc_ref().ptr();
1954  }
1955  return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
1956  }
1957 };
1958 
1959 class sequence : public object {
1960 public:
1961  PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)
1962  size_t size() const {
1963  ssize_t result = PySequence_Size(m_ptr);
1964  if (result == -1) {
1965  throw error_already_set();
1966  }
1967  return (size_t) result;
1968  }
1969  bool empty() const { return size() == 0; }
1970  detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
1973  return object::operator[](std::forward<T>(o));
1974  }
1975  detail::sequence_iterator begin() const { return {*this, 0}; }
1976  detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; }
1977 };
1978 
1979 class list : public object {
1980 public:
1981  PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
1982  template <typename SzType = ssize_t,
1984  // Some compilers generate link errors when using `const SzType &` here:
1985  explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) {
1986  if (!m_ptr) {
1987  pybind11_fail("Could not allocate list object!");
1988  }
1989  }
1990  size_t size() const { return (size_t) PyList_Size(m_ptr); }
1991  bool empty() const { return size() == 0; }
1992  detail::list_accessor operator[](size_t index) const { return {*this, index}; }
1995  return object::operator[](std::forward<T>(o));
1996  }
1997  detail::list_iterator begin() const { return {*this, 0}; }
1998  detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
1999  template <typename T>
2000  void append(T &&val) /* py-non-const */ {
2001  PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
2002  }
2003  template <typename IdxType,
2004  typename ValType,
2006  void insert(const IdxType &index, ValType &&val) /* py-non-const */ {
2007  PyList_Insert(
2008  m_ptr, ssize_t_cast(index), detail::object_or_cast(std::forward<ValType>(val)).ptr());
2009  }
2010 };
2011 
2012 class args : public tuple {
2013  PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check)
2014 };
2015 class kwargs : public dict {
2016  PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check)
2017 };
2018 
2019 class anyset : public object {
2020 public:
2021  PYBIND11_OBJECT(anyset, object, PyAnySet_Check)
2022  size_t size() const { return static_cast<size_t>(PySet_Size(m_ptr)); }
2023  bool empty() const { return size() == 0; }
2024  template <typename T>
2025  bool contains(T &&val) const {
2026  return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1;
2027  }
2028 };
2029 
2030 class set : public anyset {
2031 public:
2032  PYBIND11_OBJECT_CVT(set, anyset, PySet_Check, PySet_New)
2033  set() : anyset(PySet_New(nullptr), stolen_t{}) {
2034  if (!m_ptr) {
2035  pybind11_fail("Could not allocate set object!");
2036  }
2037  }
2038  template <typename T>
2039  bool add(T &&val) /* py-non-const */ {
2040  return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
2041  }
2042  void clear() /* py-non-const */ { PySet_Clear(m_ptr); }
2043 };
2044 
2045 class frozenset : public anyset {
2046 public:
2047  PYBIND11_OBJECT_CVT(frozenset, anyset, PyFrozenSet_Check, PyFrozenSet_New)
2048 };
2049 
2050 class function : public object {
2051 public:
2052  PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)
2054  handle fun = detail::get_function(m_ptr);
2055  if (fun && PyCFunction_Check(fun.ptr())) {
2056  return fun;
2057  }
2058  return handle();
2059  }
2060  bool is_cpp_function() const { return (bool) cpp_function(); }
2061 };
2062 
2063 class staticmethod : public object {
2064 public:
2065  PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)
2066 };
2067 
2068 class buffer : public object {
2069 public:
2070  PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)
2071 
2072  buffer_info request(bool writable = false) const {
2073  int flags = PyBUF_STRIDES | PyBUF_FORMAT;
2074  if (writable) {
2075  flags |= PyBUF_WRITABLE;
2076  }
2077  auto *view = new Py_buffer();
2078  if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
2079  delete view;
2080  throw error_already_set();
2081  }
2082  return buffer_info(view);
2083  }
2084 };
2085 
2086 class memoryview : public object {
2087 public:
2088  PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
2089 
2090 
2099  explicit memoryview(const buffer_info &info) {
2100  if (!info.view()) {
2101  pybind11_fail("Prohibited to create memoryview without Py_buffer");
2102  }
2103  // Note: PyMemoryView_FromBuffer never increments obj reference.
2104  m_ptr = (info.view()->obj) ? PyMemoryView_FromObject(info.view()->obj)
2105  : PyMemoryView_FromBuffer(info.view());
2106  if (!m_ptr) {
2107  pybind11_fail("Unable to create memoryview from buffer descriptor");
2108  }
2109  }
2110 
2135  static memoryview from_buffer(void *ptr,
2136  ssize_t itemsize,
2137  const char *format,
2138  detail::any_container<ssize_t> shape,
2139  detail::any_container<ssize_t> strides,
2140  bool readonly = false);
2141 
2142  static memoryview from_buffer(const void *ptr,
2143  ssize_t itemsize,
2144  const char *format,
2145  detail::any_container<ssize_t> shape,
2146  detail::any_container<ssize_t> strides) {
2147  return memoryview::from_buffer(
2148  const_cast<void *>(ptr), itemsize, format, std::move(shape), std::move(strides), true);
2149  }
2150 
2151  template <typename T>
2152  static memoryview from_buffer(T *ptr,
2153  detail::any_container<ssize_t> shape,
2154  detail::any_container<ssize_t> strides,
2155  bool readonly = false) {
2156  return memoryview::from_buffer(reinterpret_cast<void *>(ptr),
2157  sizeof(T),
2159  std::move(shape),
2160  std::move(strides),
2161  readonly);
2162  }
2163 
2164  template <typename T>
2165  static memoryview from_buffer(const T *ptr,
2166  detail::any_container<ssize_t> shape,
2167  detail::any_container<ssize_t> strides) {
2168  return memoryview::from_buffer(
2169  const_cast<T *>(ptr), std::move(shape), std::move(strides), true);
2170  }
2171 
2184  static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) {
2185  PyObject *ptr = PyMemoryView_FromMemory(
2186  reinterpret_cast<char *>(mem), size, (readonly) ? PyBUF_READ : PyBUF_WRITE);
2187  if (!ptr) {
2188  pybind11_fail("Could not allocate memoryview object!");
2189  }
2190  return memoryview(object(ptr, stolen_t{}));
2191  }
2192 
2193  static memoryview from_memory(const void *mem, ssize_t size) {
2194  return memoryview::from_memory(const_cast<void *>(mem), size, true);
2195  }
2196 
2197 #ifdef PYBIND11_HAS_STRING_VIEW
2198  static memoryview from_memory(std::string_view mem) {
2199  return from_memory(const_cast<char *>(mem.data()), static_cast<ssize_t>(mem.size()), true);
2200  }
2201 #endif
2202 };
2203 
2205 inline memoryview memoryview::from_buffer(void *ptr,
2206  ssize_t itemsize,
2207  const char *format,
2208  detail::any_container<ssize_t> shape,
2209  detail::any_container<ssize_t> strides,
2210  bool readonly) {
2211  size_t ndim = shape->size();
2212  if (ndim != strides->size()) {
2213  pybind11_fail("memoryview: shape length doesn't match strides length");
2214  }
2215  ssize_t size = ndim != 0u ? 1 : 0;
2216  for (size_t i = 0; i < ndim; ++i) {
2217  size *= (*shape)[i];
2218  }
2219  Py_buffer view;
2220  view.buf = ptr;
2221  view.obj = nullptr;
2222  view.len = size * itemsize;
2223  view.readonly = static_cast<int>(readonly);
2224  view.itemsize = itemsize;
2225  view.format = const_cast<char *>(format);
2226  view.ndim = static_cast<int>(ndim);
2227  view.shape = shape->data();
2228  view.strides = strides->data();
2229  view.suboffsets = nullptr;
2230  view.internal = nullptr;
2231  PyObject *obj = PyMemoryView_FromBuffer(&view);
2232  if (!obj) {
2233  throw error_already_set();
2234  }
2235  return memoryview(object(obj, stolen_t{}));
2236 }
2239 
2242 
2244 inline size_t len(handle h) {
2245  ssize_t result = PyObject_Length(h.ptr());
2246  if (result < 0) {
2247  throw error_already_set();
2248  }
2249  return (size_t) result;
2250 }
2251 
2254 inline size_t len_hint(handle h) {
2255  ssize_t result = PyObject_LengthHint(h.ptr(), 0);
2256  if (result < 0) {
2257  // Sometimes a length can't be determined at all (eg generators)
2258  // In which case simply return 0
2259  PyErr_Clear();
2260  return 0;
2261  }
2262  return (size_t) result;
2263 }
2264 
2265 inline str repr(handle h) {
2266  PyObject *str_value = PyObject_Repr(h.ptr());
2267  if (!str_value) {
2268  throw error_already_set();
2269  }
2270  return reinterpret_steal<str>(str_value);
2271 }
2272 
2273 inline iterator iter(handle obj) {
2274  PyObject *result = PyObject_GetIter(obj.ptr());
2275  if (!result) {
2276  throw error_already_set();
2277  }
2278  return reinterpret_steal<iterator>(result);
2279 }
2281 
2283 template <typename D>
2285  return iter(derived());
2286 }
2287 template <typename D>
2289  return iterator::sentinel();
2290 }
2291 template <typename D>
2293  return {derived(), reinterpret_borrow<object>(key)};
2294 }
2295 template <typename D>
2297  return {derived(), std::move(key)};
2298 }
2299 template <typename D>
2301  return {derived(), pybind11::str(key)};
2302 }
2303 template <typename D>
2305  return {derived(), reinterpret_borrow<object>(key)};
2306 }
2307 template <typename D>
2309  return {derived(), std::move(key)};
2310 }
2311 template <typename D>
2313  return {derived(), key};
2314 }
2315 template <typename D>
2317  return args_proxy(derived().ptr());
2318 }
2319 template <typename D>
2320 template <typename T>
2321 bool object_api<D>::contains(T &&item) const {
2322  return attr("__contains__")(std::forward<T>(item)).template cast<bool>();
2323 }
2324 
2325 template <typename D>
2327  return pybind11::str(derived());
2328 }
2329 
2330 template <typename D>
2332  return attr("__doc__");
2333 }
2334 
2335 template <typename D>
2337  return type::handle_of(derived());
2338 }
2339 
2340 template <typename D>
2342  int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
2343  if (rv == -1) {
2344  throw error_already_set();
2345  }
2346  return rv == 1;
2347 }
2348 
2349 #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
2350  template <typename D> \
2351  object object_api<D>::op() const { \
2352  object result = reinterpret_steal<object>(fn(derived().ptr())); \
2353  if (!result.ptr()) \
2354  throw error_already_set(); \
2355  return result; \
2356  }
2357 
2358 #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
2359  template <typename D> \
2360  object object_api<D>::op(object_api const &other) const { \
2361  object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
2362  if (!result.ptr()) \
2363  throw error_already_set(); \
2364  return result; \
2365  }
2366 
2367 PYBIND11_MATH_OPERATOR_UNARY(operator~, PyNumber_Invert)
2368 PYBIND11_MATH_OPERATOR_UNARY(operator-, PyNumber_Negative)
2369 PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)
2370 PYBIND11_MATH_OPERATOR_BINARY(operator+=, PyNumber_InPlaceAdd)
2371 PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)
2372 PYBIND11_MATH_OPERATOR_BINARY(operator-=, PyNumber_InPlaceSubtract)
2373 PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)
2374 PYBIND11_MATH_OPERATOR_BINARY(operator*=, PyNumber_InPlaceMultiply)
2375 PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)
2376 PYBIND11_MATH_OPERATOR_BINARY(operator/=, PyNumber_InPlaceTrueDivide)
2377 PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)
2378 PYBIND11_MATH_OPERATOR_BINARY(operator|=, PyNumber_InPlaceOr)
2379 PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)
2380 PYBIND11_MATH_OPERATOR_BINARY(operator&=, PyNumber_InPlaceAnd)
2381 PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)
2382 PYBIND11_MATH_OPERATOR_BINARY(operator^=, PyNumber_InPlaceXor)
2383 PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)
2384 PYBIND11_MATH_OPERATOR_BINARY(operator<<=, PyNumber_InPlaceLshift)
2385 PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)
2386 PYBIND11_MATH_OPERATOR_BINARY(operator>>=, PyNumber_InPlaceRshift)
2387 
2388 #undef PYBIND11_MATH_OPERATOR_UNARY
2389 #undef PYBIND11_MATH_OPERATOR_BINARY
2390 
bytearray(const char *c, const SzType &n)
Definition: pytypes.h:1589
detail::list_iterator end() const
Definition: pytypes.h:1998
const gtsam::Symbol key('X', 0)
bool empty() const
Definition: pytypes.h:1969
Quick proxy class needed to implement operator-> for iterators which can&#39;t return pointers...
Definition: pytypes.h:1090
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:196
ssize_t hash(handle obj)
Definition: pytypes.h:792
Vector3_ operator*(const Double_ &s, const Vector3_ &v)
PyObject *& ptr()
Definition: pytypes.h:239
typename Policy::pointer pointer
Definition: pytypes.h:1030
def step(data, isam, result, truth, currPoseIndex)
Definition: visual_isam.py:82
detail::sequence_accessor operator[](size_t index) const
Definition: pytypes.h:1970
void advance(ssize_t n)
Definition: pytypes.h:1133
static iterator sentinel()
Definition: pytypes.h:1353
slice(ssize_t start_, ssize_t stop_, ssize_t step_)
Definition: pytypes.h:1751
bool equal(const sequence_fast_readonly &b) const
Definition: pytypes.h:1113
static type of()
Definition: pytypes.h:1391
generic_iterator< iterator_policies::sequence_slow_readwrite > sequence_iterator
Definition: pytypes.h:1177
const object & value() const
Definition: pytypes.h:639
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bfloat16 & operator+=(bfloat16 &a, const bfloat16 &b)
Definition: BFloat16.h:184
static handle handle_of()
Definition: cast.h:1645
accessor< accessor_policies::list_item > list_accessor
Definition: pytypes.h:64
bool PyNone_Check(PyObject *o)
Definition: pytypes.h:1190
typename Policy::reference reference
Definition: pytypes.h:1029
bool hasattr(handle obj, handle name)
Definition: pytypes.h:728
void discard_as_unraisable(const char *err_context)
Definition: pytypes.h:625
handle obj
Definition: pytypes.h:1163
detail::item_accessor operator[](T &&o) const
Definition: pytypes.h:1972
friend It operator+(const It &a, difference_type n)
Definition: pytypes.h:1068
Scalar * b
Definition: benchVecAdd.cpp:17
reference operator[](difference_type n) const
Definition: pytypes.h:1038
friend It operator-(const It &a, difference_type n)
Definition: pytypes.h:1073
iterator begin() const
Definition: pytypes.h:2284
bool contains(T &&item) const
Check if the given item is contained within this object, i.e. item in obj.
Definition: pytypes.h:2321
pointer operator->() const
Definition: pytypes.h:1335
ssize_t pos
Definition: pytypes.h:1165
bytes(const std::string &s)
Definition: pytypes.h:1515
std::is_same< args_proxy, T > is_s_unpacking
Definition: pytypes.h:1219
bool operator>(object_api const &other) const
Definition: pytypes.h:152
EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE std::size_t size()
Definition: EmulateArray.h:44
PyObject * dict_getitemstring(PyObject *v, const char *key)
Definition: pytypes.h:818
pybind11::str str() const
Definition: pytypes.h:2326
EIGEN_DEVICE_FUNC const CwiseBinaryOp< internal::scalar_boolean_xor_op, const Derived, const OtherDerived > operator^(const EIGEN_CURRENT_STORAGE_BASE_CLASS< OtherDerived > &other) const
iterator end() const
Return a sentinel which ends iteration.
Definition: pytypes.h:2288
void clear()
Definition: pytypes.h:2042
bool isinstance_generic(handle obj, const std::type_info &tp)
bool isinstance< handle >(handle)=delete
static PyObject * raw_bool(PyObject *op)
Return the truth value of an object – always returns a new reference.
Definition: pytypes.h:1638
object(handle h, stolen_t)
Definition: pytypes.h:378
PYBIND11_DEPRECATED("make_simple_namespace should be replaced with " "py::module_::import(\ypes\.attr(\impleNamespace\ ") object make_simple_namespace(Args &&...args_)
Definition: pybind11.h:1276
accessor(handle obj, key_type key)
Definition: pytypes.h:863
object(handle h, borrowed_t)
Definition: pytypes.h:377
void restore()
Definition: pytypes.h:612
static PyObject * raw_weakref(PyObject *o)
Definition: pytypes.h:1734
bool matches(handle exc) const
Definition: pytypes.h:636
ssize_t difference_type
Definition: pytypes.h:1308
detail::list_accessor operator[](size_t index) const
Definition: pytypes.h:1992
Definition: pytypes.h:2012
object(object &&other) noexcept
Move constructor; steals the object from other and preserves its reference count. ...
Definition: pytypes.h:321
Definition: cast.h:1265
#define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun)
Definition: pytypes.h:1267
std::string error_string()
Definition: pytypes.h:578
It operator--(int)
Definition: pytypes.h:1054
args_proxy operator*() const
Definition: pytypes.h:2316
#define PYBIND11_SILENCE_MSVC_C4127(...)
bool operator<=(object_api const &other) const
Definition: pytypes.h:151
int n
friend bool operator<=(const It &a, const It &b)
Definition: pytypes.h:1084
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
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
bytes(const char *c="")
Definition: pytypes.h:1499
sequence_slow_readwrite(handle obj, ssize_t index)
Definition: pytypes.h:1128
std::string m_lazy_error_string
Definition: pytypes.h:573
friend bool operator>=(const It &a, const It &b)
Definition: pytypes.h:1083
typename Policy::iterator_category iterator_category
Definition: pytypes.h:1027
void raise_from(PyObject *type, const char *message)
Definition: pytypes.h:655
handle obj
Definition: pytypes.h:917
void operator=(const accessor &a) &
Definition: pytypes.h:870
Definition: BFloat16.h:88
accessor< accessor_policies::sequence_item > sequence_accessor
Definition: pytypes.h:63
iterator iter(handle obj)
Definition: pytypes.h:2273
It & operator+=(difference_type n)
Definition: pytypes.h:1059
DiscreteKeys operator &(const DiscreteKey &key1, const DiscreteKey &key2)
Create a list from two keys.
Definition: DiscreteKey.cpp:45
#define PYBIND11_STR_CHECK_FUN
Definition: pytypes.h:1199
reference operator*() const
Definition: pytypes.h:1327
size_t size() const
Definition: pytypes.h:1990
bool operator>=(object_api const &other) const
Definition: pytypes.h:153
str_attr_accessor doc() const
Get or set the object&#39;s docstring, i.e. obj.__doc__.
Definition: pytypes.h:2331
friend bool operator!=(const iterator &a, const iterator &b)
Definition: pytypes.h:1356
tuple(SzType size=0)
Definition: pytypes.h:1900
T cast() const
Definition: cast.h:1071
It & operator++()
Definition: pytypes.h:1041
bytes(const char *c, const SzType &n)
Definition: pytypes.h:1506
STL iterator template used for tuple, list, sequence and dict.
Definition: pytypes.h:1022
reference dereference() const
Definition: pytypes.h:1130
bool isinstance(handle obj)
Definition: pytypes.h:700
Definition: cast.h:1238
void delattr(handle obj, handle name)
Definition: pytypes.h:736
detail::dict_iterator begin() const
Definition: pytypes.h:1941
str(const std::string &s)
Definition: pytypes.h:1425
bool PyStaticMethod_Check(PyObject *o)
Definition: pytypes.h:1202
friend bool operator==(const iterator &a, const iterator &b)
Definition: pytypes.h:1355
static std::size_t inc_ref_counter(std::size_t add)
Definition: pytypes.h:288
It & operator-=(difference_type n)
Definition: pytypes.h:1063
bool equal(const sequence_slow_readwrite &b) const
Definition: pytypes.h:1134
Definition: pytypes.h:1614
static object ensure_object(handle h)
Definition: pytypes.h:907
size_t key_type
Definition: pytypes.h:999
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)
Definition: pytypes.h:1252
handle(T ptr)
Definition: pytypes.h:225
static memoryview from_memory(void *mem, ssize_t size, bool readonly=false)
Definition: pytypes.h:2184
detail::tuple_iterator begin() const
Definition: pytypes.h:1912
detail::dict_iterator end() const
Definition: pytypes.h:1942
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)
generic_iterator(handle seq, ssize_t index)
Definition: pytypes.h:1033
PyExc_RuntimeError [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
static std::size_t inc_ref_counter()
Definition: pytypes.h:295
ssize_t distance_to(const sequence_fast_readonly &b) const
Definition: pytypes.h:1114
else if n * info
size_t key_type
Definition: pytypes.h:978
dict_readonly(handle obj, ssize_t pos)
Definition: pytypes.h:1151
const handle & inc_ref() const &
Definition: pytypes.h:246
T reinterpret_borrow(handle h)
Definition: pytypes.h:395
detail::enable_if_t<!detail::move_never< T >::value, T > move(object &&obj)
Definition: cast.h:1080
auto object_or_cast(T &&o) -> decltype(std::forward< T >(o))
Definition: pytypes.h:845
Scalar Scalar int size
Definition: benchVecAdd.cpp:17
accessor< accessor_policies::tuple_item > tuple_accessor
Definition: pytypes.h:65
reference dereference() const
Definition: pytypes.h:1154
std::ostream & operator<<(std::ostream &s, const Jet< T, N > &z)
Definition: jet.h:631
kwargs_proxy operator*() const
Definition: pytypes.h:1212
ssize_t ssize_t_cast(const IntType &val)
const char * key_type
Definition: pytypes.h:933
int ref_count() const
Return the object&#39;s current reference count.
Definition: pytypes.h:183
std::is_same< kwargs_proxy, T > is_ds_unpacking
Definition: pytypes.h:1221
PyObject * m_ptr
Definition: pytypes.h:284
istream & operator>>(istream &inputStream, Matrix &destinationMatrix)
Definition: Matrix.cpp:173
bool empty() const
Definition: pytypes.h:1906
Values result
item_accessor operator[](handle key) const
Definition: pytypes.h:2292
void operator=(T &&value) &
Definition: pytypes.h:877
error_fetch_and_normalize(const char *called)
Definition: pytypes.h:431
handle(T &obj)
Enable implicit conversion through T::operator PyObject *().
Definition: pytypes.h:235
size_t size() const
Definition: pytypes.h:1939
void append(T &&val)
Definition: pytypes.h:2000
object & operator=(const object &other)
Definition: pytypes.h:336
Definition: pytypes.h:1403
bool compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const
Definition: pytypes.h:1756
friend bool operator<(const It &a, const It &b)
Definition: pytypes.h:1081
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CwiseBinaryOp< internal::scalar_quotient_op< Scalar, typename OtherDerived::Scalar >, const Derived, const OtherDerived > operator/(const EIGEN_CURRENT_STORAGE_BASE_CLASS< OtherDerived > &other) const
friend bool operator==(const It &a, const It &b)
Definition: pytypes.h:1079
EIGEN_ALWAYS_INLINE DSizes< IndexType, NumDims > strides(const DSizes< IndexType, NumDims > &dimensions)
Definition: TensorBlock.h:26
float_(double value=.0)
Definition: pytypes.h:1709
std::random_access_iterator_tag iterator_category
Definition: pytypes.h:1101
static PyObject * raw_str(PyObject *op)
Return string representation – always returns a new reference, even if already a str...
Definition: pytypes.h:1477
bool equal(object_api const &other) const
Equivalent to obj == other in Python.
Definition: pytypes.h:148
Array< int, Dynamic, 1 > v
object cache
Definition: pytypes.h:919
void discard_as_unraisable(object err_context)
Definition: pytypes.h:618
int_(T value)
Definition: pytypes.h:1670
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
Eigen::Triplet< double > T
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
Definition: pytypes.h:1290
int data[]
std::string const & error_string() const
Definition: pytypes.h:546
bool is_cpp_function() const
Definition: pytypes.h:2060
bool rich_compare(object_api const &other, int value) const
Definition: pytypes.h:2341
size_t size() const
Definition: pytypes.h:1905
void operator=(T &&value) &&
Definition: pytypes.h:873
RealScalar s
str(handle h)
Definition: pytypes.h:1447
std::random_access_iterator_tag iterator_category
Definition: pytypes.h:1123
object(const object &o)
Copy constructor; always increases the reference count.
Definition: pytypes.h:319
std::is_base_of< arg, T > is_keyword
Python argument categories (using PEP 448 terms)
Definition: pytypes.h:1217
const handle & dec_ref() const &
Definition: pytypes.h:259
detail::item_accessor operator[](T &&o) const
Definition: pytypes.h:1909
str format(Args &&...args) const
Definition: pytypes.h:1471
void clear()
Definition: pytypes.h:1943
const object & type() const
Definition: pytypes.h:638
Unsigned as_unsigned(PyObject *o)
Definition: pytypes.h:1653
static PyObject * raw_dict(PyObject *op)
Call the dict Python type – always returns a new reference.
Definition: pytypes.h:1951
void set(Container &c, Position position, const Value &value)
handle get_function(handle value)
Definition: pytypes.h:803
ssize_t distance_to(const sequence_slow_readwrite &b) const
Definition: pytypes.h:1135
const object & trace() const
Definition: pytypes.h:640
bool operator<(object_api const &other) const
Definition: pytypes.h:150
PyObject * dict_getitem(PyObject *v, PyObject *key)
Definition: pytypes.h:833
bool not_equal(object_api const &other) const
Definition: pytypes.h:149
detail::list_iterator begin() const
Definition: pytypes.h:1997
void operator=(const accessor &a) &&
Definition: pytypes.h:869
void insert(const IdxType &index, ValType &&val)
Definition: pytypes.h:2006
const Derived & derived() const
Definition: pytypes.h:78
It & operator--()
Definition: pytypes.h:1050
iterator operator++(int)
Definition: pytypes.h:1320
str(const char *c, const SzType &n)
Definition: pytypes.h:1408
arrow_proxy(T &&value) noexcept
Definition: pytypes.h:1094
Python&#39;s dictionary protocol permits this to be a forward iterator.
Definition: pytypes.h:1143
It operator++(int)
Definition: pytypes.h:1045
bool_(bool value)
Definition: pytypes.h:1632
friend It operator+(difference_type n, const It &b)
Definition: pytypes.h:1072
static memoryview from_buffer(const T *ptr, detail::any_container< ssize_t > shape, detail::any_container< ssize_t > strides)
Definition: pytypes.h:2165
Full read and write access using the sequence protocol: see detail::sequence_accessor ...
Definition: pytypes.h:1121
Definition: pytypes.h:1979
str(const char *c="")
Definition: pytypes.h:1418
T * operator->() const
Definition: pytypes.h:1095
static type of(handle h)
Return a type object from a handle or an object.
Definition: pytypes.h:1378
void advance()
Definition: pytypes.h:1359
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)
bool add(T &&val)
Definition: pytypes.h:2039
Helper class which collects positional, keyword, * and ** arguments for a Python function call...
Definition: cast.h:1476
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bfloat16 & operator/=(bfloat16 &a, const bfloat16 &b)
Definition: BFloat16.h:196
key_type key
Definition: pytypes.h:918
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bfloat16 & operator*=(bfloat16 &a, const bfloat16 &b)
Definition: BFloat16.h:188
bool empty() const
Definition: pytypes.h:2023
Tag and check to identify a class which implements the Python object API.
Definition: pytypes.h:68
const double h
void check(bool b, bool ref)
Definition: fastmath.cpp:12
pointer operator->() const
Definition: pytypes.h:1039
object & get_cache() const
Definition: pytypes.h:909
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bfloat16 & operator-=(bfloat16 &a, const bfloat16 &b)
Definition: BFloat16.h:192
handle release()
Definition: pytypes.h:330
std::input_iterator_tag iterator_category
Definition: pytypes.h:1307
def doc()
Definition: conftest.py:157
Definition: pytypes.h:1663
detail::sequence_iterator end() const
Definition: pytypes.h:1976
void increment()
Definition: pytypes.h:1155
kwargs_proxy(handle h)
Definition: pytypes.h:1206
bool empty() const
Definition: pytypes.h:1940
void advance(ssize_t n)
Definition: pytypes.h:1112
std::pair< handle, handle > value_type
Definition: pytypes.h:1146
constexpr bool args_are_all_keyword_or_ds()
Definition: pytypes.h:1920
std::shared_ptr< detail::error_fetch_and_normalize > m_fetched_error
Definition: pytypes.h:643
reference operator*() const
Definition: pytypes.h:1036
generic_iterator< iterator_policies::sequence_fast_readonly > tuple_iterator
Definition: pytypes.h:1170
args_proxy(handle h)
Definition: pytypes.h:1211
object getattr(handle obj, handle name)
Definition: pytypes.h:748
bytearray()
Definition: pytypes.h:1596
RAII wrapper that temporarily clears any Python error state.
bool PyEllipsis_Check(PyObject *o)
Definition: pytypes.h:1191
bool PyIterable_Check(PyObject *obj)
Definition: pytypes.h:1180
reference dereference() const
Definition: pytypes.h:1109
size_t size() const
Definition: pytypes.h:1600
bytearray(const std::string &s)
Definition: pytypes.h:1598
typename deferred_type< T, Us... >::type deferred_t
static EIGEN_DEPRECATED const end_t end
std::string format(const std::string &str, const std::vector< std::string > &find, const std::vector< std::string > &replace)
friend difference_type operator-(const It &a, const It &b)
Definition: pytypes.h:1077
detail::tuple_accessor operator[](size_t index) const
Definition: pytypes.h:1907
#define PYBIND11_MATH_OPERATOR_BINARY(op, fn)
Definition: pytypes.h:2358
obj_attr_accessor attr(handle key) const
Definition: pytypes.h:2304
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
Definition: pybind11.h:81
bool empty() const
Definition: pytypes.h:1991
std::string format_value_and_trace() const
Definition: pytypes.h:475
size_t len_hint(handle h)
Definition: pytypes.h:2254
size_t key_type
Definition: pytypes.h:957
#define PYBIND11_MATH_OPERATOR_UNARY(op, fn)
Definition: pytypes.h:2349
static memoryview from_buffer(T *ptr, detail::any_container< ssize_t > shape, detail::any_container< ssize_t > strides, bool readonly=false)
Definition: pytypes.h:2152
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
Jet< T, N > operator-(const Jet< T, N > &f)
Definition: jet.h:258
object & operator=(object &&other) noexcept
Definition: pytypes.h:346
bool compute(ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const
Definition: pytypes.h:1765
graph add(PriorFactor< Pose2 >(1, priorMean, priorNoise))
typename Policy::value_type value_type
Definition: pytypes.h:1028
Definition: pytypes.h:1924
std::forward_iterator_tag iterator_category
Definition: pytypes.h:1145
T reinterpret_steal(handle h)
Definition: pytypes.h:408
bool isinstance< object >(handle obj)
Definition: pytypes.h:712
detail::tuple_iterator end() const
Definition: pytypes.h:1913
Annotation for function names.
Definition: attr.h:48
generic_iterator< iterator_policies::sequence_fast_readonly > list_iterator
Definition: pytypes.h:1171
friend bool operator>(const It &a, const It &b)
Definition: pytypes.h:1082
int EIGEN_BLAS_FUNC() copy(int *n, RealScalar *px, int *incx, RealScalar *py, int *incy)
Definition: level1_impl.h:29
generic_iterator< iterator_policies::dict_readonly > dict_iterator
Definition: pytypes.h:1178
str repr(handle h)
Definition: pytypes.h:2265
Signature operator|(const DiscreteKey &key, const DiscreteKey &parent)
Definition: Signature.cpp:129
Information record describing a Python buffer object.
Definition: buffer_info.h:43
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:238
bool equal(const dict_readonly &b) const
Definition: pytypes.h:1160
bool matches(handle exc) const
Definition: pytypes.h:564
Container::iterator get(Container &c, Position position)
list(SzType size=0)
Definition: pytypes.h:1985
accessor< accessor_policies::generic_item > item_accessor
Definition: pytypes.h:62
ssize_t difference_type
Definition: pytypes.h:1026
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2244
const value_type reference
Definition: pytypes.h:1147
typename Policy::key_type key_type
Definition: pytypes.h:860
internal::enable_if< internal::valid_indexed_view_overload< RowIndices, ColIndices >::value &&internal::traits< typename EIGEN_INDEXED_VIEW_METHOD_TYPE< RowIndices, ColIndices >::type >::ReturnAsIndexedView, typename EIGEN_INDEXED_VIEW_METHOD_TYPE< RowIndices, ColIndices >::type >::type operator()(const RowIndices &rowIndices, const ColIndices &colIndices) EIGEN_INDEXED_VIEW_METHOD_CONST
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:780
bool contains(T &&key) const
Definition: pytypes.h:1945
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
Definition: pytypes.h:2030
~object()
Destructor; automatically calls handle::dec_ref()
Definition: pytypes.h:323
static memoryview from_memory(const void *mem, ssize_t size)
Definition: pytypes.h:2193
static object index_to_object(T index)
Definition: pytypes.h:1774
Jet< T, N > const & operator+(const Jet< T, N > &f)
Definition: jet.h:249
detail::sequence_iterator begin() const
Definition: pytypes.h:1975
#define PYBIND11_NAMESPACE_END(name)
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:2142
bool contains(T &&val) const
Definition: pytypes.h:2025
friend bool operator!=(const It &a, const It &b)
Definition: pytypes.h:1080
#define PYBIND11_OBJECT(Name, Parent, CheckFun)
Definition: pytypes.h:1276
dict(Args &&...args)
Definition: pytypes.h:1937
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
Definition: pytypes.h:70
T string_op() const
Definition: pytypes.h:1536
Definition: pytypes.h:1370
bool is(object_api const &other) const
Equivalent to obj is other in Python.
Definition: pytypes.h:144
#define PYBIND11_NAMESPACE_BEGIN(name)
PYBIND11_DEPRECATED("Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)") explicit operator enable_if_t< std
Definition: pytypes.h:882
sequence_fast_readonly(handle obj, ssize_t n)
Definition: pytypes.h:1106
const char * obj_class_name(PyObject *obj)
Definition: pytypes.h:415
handle get_type() const
Definition: pytypes.h:2336
bool is_none() const
Equivalent to obj is None in Python.
Definition: pytypes.h:146
detail::item_accessor operator[](T &&o) const
Definition: pytypes.h:1994
Lightweight iterator policy using just a simple pointer: see PySequence_Fast_ITEMS ...
Definition: pytypes.h:1099


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:35:26