Scarab  2.8.1
Project 8 C++ Utility Library
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 #include <utility>
15 #include <type_traits>
16 
18 
19 /* A few forward declarations */
20 class handle; class object;
21 class str; class iterator;
22 struct arg; struct arg_v;
23 
24 NAMESPACE_BEGIN(detail)
25 class args_proxy;
26 inline bool isinstance_generic(handle obj, const std::type_info &tp);
27 
28 // Accessor forward declarations
29 template <typename Policy> class accessor;
30 namespace accessor_policies {
31  struct obj_attr;
32  struct str_attr;
33  struct generic_item;
34  struct sequence_item;
35  struct list_item;
36  struct tuple_item;
37 }
44 
46 class pyobject_tag { };
47 template <typename T> using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
48 
53 template <typename Derived>
54 class object_api : public pyobject_tag {
55  const Derived &derived() const { return static_cast<const Derived &>(*this); }
56 
57 public:
62  iterator begin() const;
64  iterator end() const;
65 
72  item_accessor operator[](handle key) const;
74  item_accessor operator[](const char *key) const;
75 
82  obj_attr_accessor attr(handle key) const;
84  str_attr_accessor attr(const char *key) const;
85 
92  args_proxy operator*() const;
93 
95  template <typename T> bool contains(T &&item) const;
96 
107  template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
108  object operator()(Args &&...args) const;
109  template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
110  PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)")
111  object call(Args&&... args) const;
112 
114  bool is(object_api const& other) const { return derived().ptr() == other.derived().ptr(); }
116  bool is_none() const { return derived().ptr() == Py_None; }
118  bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); }
119  bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); }
120  bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); }
121  bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); }
122  bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); }
123  bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); }
124 
125  object operator-() const;
126  object operator~() const;
127  object operator+(object_api const &other) const;
128  object operator+=(object_api const &other) const;
129  object operator-(object_api const &other) const;
130  object operator-=(object_api const &other) const;
131  object operator*(object_api const &other) const;
132  object operator*=(object_api const &other) const;
133  object operator/(object_api const &other) const;
134  object operator/=(object_api const &other) const;
135  object operator|(object_api const &other) const;
136  object operator|=(object_api const &other) const;
137  object operator&(object_api const &other) const;
138  object operator&=(object_api const &other) const;
139  object operator^(object_api const &other) const;
140  object operator^=(object_api const &other) const;
141  object operator<<(object_api const &other) const;
142  object operator<<=(object_api const &other) const;
143  object operator>>(object_api const &other) const;
144  object operator>>=(object_api const &other) const;
145 
146  PYBIND11_DEPRECATED("Use py::str(obj) instead")
147  pybind11::str str() const;
148 
150  str_attr_accessor doc() const;
151 
153  int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); }
155  handle get_type() const;
156 
157 private:
158  bool rich_compare(object_api const &other, int value) const;
159 };
160 
161 NAMESPACE_END(detail)
162 
163 
174 class handle : public detail::object_api<handle> {
175 public:
177  handle() = default;
179  handle(PyObject *ptr) : m_ptr(ptr) { } // Allow implicit conversion from PyObject*
180 
182  PyObject *ptr() const { return m_ptr; }
183  PyObject *&ptr() { return m_ptr; }
184 
190  const handle& inc_ref() const & { Py_XINCREF(m_ptr); return *this; }
191 
197  const handle& dec_ref() const & { Py_XDECREF(m_ptr); return *this; }
198 
203  template <typename T> T cast() const;
205  explicit operator bool() const { return m_ptr != nullptr; }
210  PYBIND11_DEPRECATED("Use obj1.is(obj2) instead")
211  bool operator==(const handle &h) const { return m_ptr == h.m_ptr; }
212  PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead")
213  bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }
214  PYBIND11_DEPRECATED("Use handle::operator bool() instead")
215  bool check() const { return m_ptr != nullptr; }
216 protected:
217  PyObject *m_ptr = nullptr;
218 };
219 
230 class object : public handle {
231 public:
232  object() = default;
233  PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()")
234  object(handle h, bool is_borrowed) : handle(h) { if (is_borrowed) inc_ref(); }
236  object(const object &o) : handle(o) { inc_ref(); }
238  object(object &&other) noexcept { m_ptr = other.m_ptr; other.m_ptr = nullptr; }
240  ~object() { dec_ref(); }
241 
248  PyObject *tmp = m_ptr;
249  m_ptr = nullptr;
250  return handle(tmp);
251  }
252 
253  object& operator=(const object &other) {
254  other.inc_ref();
255  dec_ref();
256  m_ptr = other.m_ptr;
257  return *this;
258  }
259 
260  object& operator=(object &&other) noexcept {
261  if (this != &other) {
262  handle temp(m_ptr);
263  m_ptr = other.m_ptr;
264  other.m_ptr = nullptr;
265  temp.dec_ref();
266  }
267  return *this;
268  }
269 
270  // Calling cast() on an object lvalue just copies (via handle::cast)
271  template <typename T> T cast() const &;
272  // Calling on an object rvalue does a move, if needed and/or possible
273  template <typename T> T cast() &&;
274 
275 protected:
276  // Tags for choosing constructors from raw PyObject *
277  struct borrowed_t { };
278  struct stolen_t { };
279 
280  template <typename T> friend T reinterpret_borrow(handle);
281  template <typename T> friend T reinterpret_steal(handle);
282 
283 public:
284  // Only accessible from derived classes and the reinterpret_* functions
285  object(handle h, borrowed_t) : handle(h) { inc_ref(); }
287 };
288 
302 template <typename T> T reinterpret_borrow(handle h) { return {h, object::borrowed_t{}}; }
303 
312 template <typename T> T reinterpret_steal(handle h) { return {h, object::stolen_t{}}; }
313 
314 NAMESPACE_BEGIN(detail)
315 inline std::string error_string();
316 NAMESPACE_END(detail)
317 
318 class error_already_set : public std::runtime_error {
323 public:
326  error_already_set() : std::runtime_error(detail::error_string()) {
327  PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
328  }
329 
330  error_already_set(const error_already_set &) = default;
331  error_already_set(error_already_set &&) = default;
332 
333  inline ~error_already_set();
334 
338  void restore() { PyErr_Restore(m_type.release().ptr(), m_value.release().ptr(), m_trace.release().ptr()); }
339 
340  // Does nothing; provided for backwards compatibility.
341  PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated")
342  void clear() {}
343 
347  bool matches(handle exc) const { return PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()); }
348 
349  const object& type() const { return m_type; }
350  const object& value() const { return m_value; }
351  const object& trace() const { return m_trace; }
352 
353 private:
354  object m_type, m_value, m_trace;
355 };
356 
368 bool isinstance(handle obj) { return T::check_(obj); }
369 
371 bool isinstance(handle obj) { return detail::isinstance_generic(obj, typeid(T)); }
372 
373 template <> inline bool isinstance<handle>(handle obj) = delete;
374 template <> inline bool isinstance<object>(handle obj) { return obj.ptr() != nullptr; }
375 
378 inline bool isinstance(handle obj, handle type) {
379  const auto result = PyObject_IsInstance(obj.ptr(), type.ptr());
380  if (result == -1)
381  throw error_already_set();
382  return result != 0;
383 }
384 
387 inline bool hasattr(handle obj, handle name) {
388  return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1;
389 }
390 
391 inline bool hasattr(handle obj, const char *name) {
392  return PyObject_HasAttrString(obj.ptr(), name) == 1;
393 }
394 
395 inline void delattr(handle obj, handle name) {
396  if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) { throw error_already_set(); }
397 }
398 
399 inline void delattr(handle obj, const char *name) {
400  if (PyObject_DelAttrString(obj.ptr(), name) != 0) { throw error_already_set(); }
401 }
402 
403 inline object getattr(handle obj, handle name) {
404  PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr());
405  if (!result) { throw error_already_set(); }
406  return reinterpret_steal<object>(result);
407 }
408 
409 inline object getattr(handle obj, const char *name) {
410  PyObject *result = PyObject_GetAttrString(obj.ptr(), name);
411  if (!result) { throw error_already_set(); }
412  return reinterpret_steal<object>(result);
413 }
414 
415 inline object getattr(handle obj, handle name, handle default_) {
416  if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) {
417  return reinterpret_steal<object>(result);
418  } else {
419  PyErr_Clear();
420  return reinterpret_borrow<object>(default_);
421  }
422 }
423 
424 inline object getattr(handle obj, const char *name, handle default_) {
425  if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) {
426  return reinterpret_steal<object>(result);
427  } else {
428  PyErr_Clear();
429  return reinterpret_borrow<object>(default_);
430  }
431 }
432 
433 inline void setattr(handle obj, handle name, handle value) {
434  if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) { throw error_already_set(); }
435 }
436 
437 inline void setattr(handle obj, const char *name, handle value) {
438  if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { throw error_already_set(); }
439 }
440 
441 inline ssize_t hash(handle obj) {
442  auto h = PyObject_Hash(obj.ptr());
443  if (h == -1) { throw error_already_set(); }
444  return h;
445 }
446 
448 
449 NAMESPACE_BEGIN(detail)
451  if (value) {
452 #if PY_MAJOR_VERSION >= 3
453  if (PyInstanceMethod_Check(value.ptr()))
454  value = PyInstanceMethod_GET_FUNCTION(value.ptr());
455  else
456 #endif
457  if (PyMethod_Check(value.ptr()))
458  value = PyMethod_GET_FUNCTION(value.ptr());
459  }
460  return value;
461 }
462 
463 // Helper aliases/functions to support implicit casting of values given to python accessors/methods.
464 // When given a pyobject, this simply returns the pyobject as-is; for other C++ type, the value goes
465 // through pybind11::cast(obj) to convert it to an `object`.
467 auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) { return std::forward<T>(o); }
468 // The following casting version is implemented in cast.h:
470 object object_or_cast(T &&o);
471 // Match a PyObject*, which we want to convert directly to handle via its converting constructor
472 inline handle object_or_cast(PyObject *ptr) { return ptr; }
473 
474 template <typename Policy>
475 class accessor : public object_api<accessor<Policy>> {
476  using key_type = typename Policy::key_type;
477 
478 public:
479  accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) { }
480  accessor(const accessor &) = default;
481  accessor(accessor &&) = default;
482 
483  // accessor overload required to override default assignment operator (templates are not allowed
484  // to replace default compiler-generated assignments).
485  void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); }
486  void operator=(const accessor &a) & { operator=(handle(a)); }
487 
488  template <typename T> void operator=(T &&value) && {
489  Policy::set(obj, key, object_or_cast(std::forward<T>(value)));
490  }
491  template <typename T> void operator=(T &&value) & {
492  get_cache() = reinterpret_borrow<object>(object_or_cast(std::forward<T>(value)));
493  }
494 
495  template <typename T = Policy>
496  PYBIND11_DEPRECATED("Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
497  explicit operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value ||
498  std::is_same<T, accessor_policies::obj_attr>::value, bool>() const {
499  return hasattr(obj, key);
500  }
501  template <typename T = Policy>
502  PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
504  return obj.contains(key);
505  }
506 
507  operator object() const { return get_cache(); }
508  PyObject *ptr() const { return get_cache().ptr(); }
509  template <typename T> T cast() const { return get_cache().template cast<T>(); }
510 
511 private:
512  object &get_cache() const {
513  if (!cache) { cache = Policy::get(obj, key); }
514  return cache;
515  }
516 
517 private:
518  handle obj;
519  key_type key;
520  mutable object cache;
521 };
522 
523 NAMESPACE_BEGIN(accessor_policies)
524 struct obj_attr {
525  using key_type = object;
526  static object get(handle obj, handle key) { return getattr(obj, key); }
527  static void set(handle obj, handle key, handle val) { setattr(obj, key, val); }
528 };
529 
530 struct str_attr {
531  using key_type = const char *;
532  static object get(handle obj, const char *key) { return getattr(obj, key); }
533  static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); }
534 };
535 
536 struct generic_item {
537  using key_type = object;
538 
539  static object get(handle obj, handle key) {
540  PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr());
541  if (!result) { throw error_already_set(); }
542  return reinterpret_steal<object>(result);
543  }
544 
545  static void set(handle obj, handle key, handle val) {
546  if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) { throw error_already_set(); }
547  }
548 };
549 
551  using key_type = size_t;
552 
553  static object get(handle obj, size_t index) {
554  PyObject *result = PySequence_GetItem(obj.ptr(), static_cast<ssize_t>(index));
555  if (!result) { throw error_already_set(); }
556  return reinterpret_steal<object>(result);
557  }
558 
559  static void set(handle obj, size_t index, handle val) {
560  // PySequence_SetItem does not steal a reference to 'val'
561  if (PySequence_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.ptr()) != 0) {
562  throw error_already_set();
563  }
564  }
565 };
566 
567 struct list_item {
568  using key_type = size_t;
569 
570  static object get(handle obj, size_t index) {
571  PyObject *result = PyList_GetItem(obj.ptr(), static_cast<ssize_t>(index));
572  if (!result) { throw error_already_set(); }
573  return reinterpret_borrow<object>(result);
574  }
575 
576  static void set(handle obj, size_t index, handle val) {
577  // PyList_SetItem steals a reference to 'val'
578  if (PyList_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.inc_ref().ptr()) != 0) {
579  throw error_already_set();
580  }
581  }
582 };
583 
584 struct tuple_item {
585  using key_type = size_t;
586 
587  static object get(handle obj, size_t index) {
588  PyObject *result = PyTuple_GetItem(obj.ptr(), static_cast<ssize_t>(index));
589  if (!result) { throw error_already_set(); }
590  return reinterpret_borrow<object>(result);
591  }
592 
593  static void set(handle obj, size_t index, handle val) {
594  // PyTuple_SetItem steals a reference to 'val'
595  if (PyTuple_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.inc_ref().ptr()) != 0) {
596  throw error_already_set();
597  }
598  }
599 };
600 NAMESPACE_END(accessor_policies)
601 
602 template <typename Policy>
604 class generic_iterator : public Policy {
606 
607 public:
609  using iterator_category = typename Policy::iterator_category;
610  using value_type = typename Policy::value_type;
611  using reference = typename Policy::reference;
612  using pointer = typename Policy::pointer;
613 
614  generic_iterator() = default;
615  generic_iterator(handle seq, ssize_t index) : Policy(seq, index) { }
616 
617  reference operator*() const { return Policy::dereference(); }
618  reference operator[](difference_type n) const { return *(*this + n); }
619  pointer operator->() const { return **this; }
620 
621  It &operator++() { Policy::increment(); return *this; }
622  It operator++(int) { auto copy = *this; Policy::increment(); return copy; }
623  It &operator--() { Policy::decrement(); return *this; }
624  It operator--(int) { auto copy = *this; Policy::decrement(); return copy; }
625  It &operator+=(difference_type n) { Policy::advance(n); return *this; }
626  It &operator-=(difference_type n) { Policy::advance(-n); return *this; }
627 
628  friend It operator+(const It &a, difference_type n) { auto copy = a; return copy += n; }
629  friend It operator+(difference_type n, const It &b) { return b + n; }
630  friend It operator-(const It &a, difference_type n) { auto copy = a; return copy -= n; }
631  friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); }
632 
633  friend bool operator==(const It &a, const It &b) { return a.equal(b); }
634  friend bool operator!=(const It &a, const It &b) { return !(a == b); }
635  friend bool operator< (const It &a, const It &b) { return b - a > 0; }
636  friend bool operator> (const It &a, const It &b) { return b < a; }
637  friend bool operator>=(const It &a, const It &b) { return !(a < b); }
638  friend bool operator<=(const It &a, const It &b) { return !(a > b); }
639 };
640 
641 NAMESPACE_BEGIN(iterator_policies)
643 template <typename T>
644 struct arrow_proxy {
645  T value;
646 
647  arrow_proxy(T &&value) : value(std::move(value)) { }
648  T *operator->() const { return &value; }
649 };
650 
653 protected:
654  using iterator_category = std::random_access_iterator_tag;
656  using reference = const handle;
658 
659  sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) { }
660 
661  reference dereference() const { return *ptr; }
662  void increment() { ++ptr; }
663  void decrement() { --ptr; }
664  void advance(ssize_t n) { ptr += n; }
665  bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; }
666  ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; }
667 
668 private:
669  PyObject **ptr;
670 };
671 
674 protected:
675  using iterator_category = std::random_access_iterator_tag;
679 
680  sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) { }
681 
682  reference dereference() const { return {obj, static_cast<size_t>(index)}; }
683  void increment() { ++index; }
684  void decrement() { --index; }
685  void advance(ssize_t n) { index += n; }
686  bool equal(const sequence_slow_readwrite &b) const { return index == b.index; }
687  ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; }
688 
689 private:
692 };
693 
696 protected:
697  using iterator_category = std::forward_iterator_tag;
698  using value_type = std::pair<handle, handle>;
699  using reference = const value_type;
701 
702  dict_readonly() = default;
703  dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }
704 
705  reference dereference() const { return {key, value}; }
706  void increment() { if (!PyDict_Next(obj.ptr(), &pos, &key, &value)) { pos = -1; } }
707  bool equal(const dict_readonly &b) const { return pos == b.pos; }
708 
709 private:
711  PyObject *key = nullptr, *value = nullptr;
712  ssize_t pos = -1;
713 };
714 NAMESPACE_END(iterator_policies)
715 
716 #if !defined(PYPY_VERSION)
719 #else
722 #endif
723 
726 
727 inline bool PyIterable_Check(PyObject *obj) {
728  PyObject *iter = PyObject_GetIter(obj);
729  if (iter) {
730  Py_DECREF(iter);
731  return true;
732  } else {
733  PyErr_Clear();
734  return false;
735  }
736 }
737 
738 inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
739 #if PY_MAJOR_VERSION >= 3
740 inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }
741 #endif
742 
743 inline bool PyUnicode_Check_Permissive(PyObject *o) { return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); }
744 
745 inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; }
746 
747 class kwargs_proxy : public handle {
748 public:
749  explicit kwargs_proxy(handle h) : handle(h) { }
750 };
751 
752 class args_proxy : public handle {
753 public:
754  explicit args_proxy(handle h) : handle(h) { }
755  kwargs_proxy operator*() const { return kwargs_proxy(*this); }
756 };
757 
759 template <typename T> using is_keyword = std::is_base_of<arg, T>;
760 template <typename T> using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking
761 template <typename T> using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking
762 template <typename T> using is_positional = satisfies_none_of<T,
764 >;
766 
767 // Call argument collector forward declarations
768 template <return_value_policy policy = return_value_policy::automatic_reference>
769 class simple_collector;
770 template <return_value_policy policy = return_value_policy::automatic_reference>
771 class unpacking_collector;
772 
773 NAMESPACE_END(detail)
774 
775 // TODO: After the deprecated constructors are removed, this macro can be simplified by
776 // inheriting ctors: `using Parent::Parent`. It's not an option right now because
777 // the `using` statement triggers the parent deprecation warning even if the ctor
778 // isn't even used.
779 #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
780  public: \
781  PYBIND11_DEPRECATED("Use reinterpret_borrow<"#Name">() or reinterpret_steal<"#Name">()") \
782  Name(handle h, bool is_borrowed) : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) { } \
783  Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) { } \
784  Name(handle h, stolen_t) : Parent(h, stolen_t{}) { } \
785  PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
786  bool check() const { return m_ptr != nullptr && (bool) CheckFun(m_ptr); } \
787  static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); }
788 
789 #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
790  PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
791  /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
792  Name(const object &o) \
793  : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) \
794  { if (!m_ptr) throw error_already_set(); } \
795  Name(object &&o) \
796  : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) \
797  { if (!m_ptr) throw error_already_set(); } \
798  template <typename Policy_> \
799  Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) { }
800 
801 #define PYBIND11_OBJECT(Name, Parent, CheckFun) \
802  PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
803  /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
804  Name(const object &o) : Parent(o) { } \
805  Name(object &&o) : Parent(std::move(o)) { }
806 
807 #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
808  PYBIND11_OBJECT(Name, Parent, CheckFun) \
809  Name() : Parent() { }
810 
813 
822 class iterator : public object {
823 public:
824  using iterator_category = std::input_iterator_tag;
827  using reference = const handle;
828  using pointer = const handle *;
829 
830  PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)
831 
832  iterator& operator++() {
833  advance();
834  return *this;
835  }
836 
837  iterator operator++(int) {
838  auto rv = *this;
839  advance();
840  return rv;
841  }
842 
843  reference operator*() const {
844  if (m_ptr && !value.ptr()) {
845  auto& self = const_cast<iterator &>(*this);
846  self.advance();
847  }
848  return value;
849  }
850 
851  pointer operator->() const { operator*(); return &value; }
852 
866  static iterator sentinel() { return {}; }
867 
868  friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); }
869  friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); }
870 
871 private:
872  void advance() {
873  value = reinterpret_steal<object>(PyIter_Next(m_ptr));
874  if (PyErr_Occurred()) { throw error_already_set(); }
875  }
876 
877 private:
878  object value = {};
879 };
880 
881 class iterable : public object {
882 public:
884 };
885 
886 class bytes;
887 
888 class str : public object {
889 public:
891 
892  str(const char *c, size_t n)
893  : object(PyUnicode_FromStringAndSize(c, (ssize_t) n), stolen_t{}) {
894  if (!m_ptr) pybind11_fail("Could not allocate string object!");
895  }
896 
897  // 'explicit' is explicitly omitted from the following constructors to allow implicit conversion to py::str from C++ string-like objects
898  str(const char *c = "")
899  : object(PyUnicode_FromString(c), stolen_t{}) {
900  if (!m_ptr) pybind11_fail("Could not allocate string object!");
901  }
902 
903  str(const std::string &s) : str(s.data(), s.size()) { }
904 
905  explicit str(const bytes &b);
906 
911  explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { }
912 
913  operator std::string() const {
914  object temp = *this;
915  if (PyUnicode_Check(m_ptr)) {
916  temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
917  if (!temp)
918  pybind11_fail("Unable to extract string contents! (encoding issue)");
919  }
920  char *buffer;
921  ssize_t length;
922  if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length))
923  pybind11_fail("Unable to extract string contents! (invalid type)");
924  return std::string(buffer, (size_t) length);
925  }
926 
927  template <typename... Args>
928  str format(Args &&...args) const {
929  return attr("format")(std::forward<Args>(args)...);
930  }
931 
932 private:
934  static PyObject *raw_str(PyObject *op) {
935  PyObject *str_value = PyObject_Str(op);
936 #if PY_MAJOR_VERSION < 3
937  if (!str_value) throw error_already_set();
938  PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
939  Py_XDECREF(str_value); str_value = unicode;
940 #endif
941  return str_value;
942  }
943 };
945 
946 inline namespace literals {
950 inline str operator"" _s(const char *s, size_t size) { return {s, size}; }
951 }
952 
955 class bytes : public object {
956 public:
958 
959  // Allow implicit conversion:
960  bytes(const char *c = "")
962  if (!m_ptr) pybind11_fail("Could not allocate bytes object!");
963  }
964 
965  bytes(const char *c, size_t n)
967  if (!m_ptr) pybind11_fail("Could not allocate bytes object!");
968  }
969 
970  // Allow implicit conversion:
971  bytes(const std::string &s) : bytes(s.data(), s.size()) { }
972 
973  explicit bytes(const pybind11::str &s);
974 
975  operator std::string() const {
976  char *buffer;
977  ssize_t length;
978  if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length))
979  pybind11_fail("Unable to extract bytes contents!");
980  return std::string(buffer, (size_t) length);
981  }
982 };
983 
984 inline bytes::bytes(const pybind11::str &s) {
985  object temp = s;
986  if (PyUnicode_Check(s.ptr())) {
987  temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));
988  if (!temp)
989  pybind11_fail("Unable to extract string contents! (encoding issue)");
990  }
991  char *buffer;
992  ssize_t length;
993  if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length))
994  pybind11_fail("Unable to extract string contents! (invalid type)");
995  auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));
996  if (!obj)
997  pybind11_fail("Could not allocate bytes object!");
998  m_ptr = obj.release().ptr();
999 }
1000 
1001 inline str::str(const bytes& b) {
1002  char *buffer;
1003  ssize_t length;
1004  if (PYBIND11_BYTES_AS_STRING_AND_SIZE(b.ptr(), &buffer, &length))
1005  pybind11_fail("Unable to extract bytes contents!");
1006  auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, (ssize_t) length));
1007  if (!obj)
1008  pybind11_fail("Could not allocate string object!");
1009  m_ptr = obj.release().ptr();
1010 }
1011 
1012 class none : public object {
1013 public:
1015  none() : object(Py_None, borrowed_t{}) { }
1016 };
1017 
1018 #if PY_MAJOR_VERSION >= 3
1019 class ellipsis : public object {
1020 public:
1021  PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check)
1022  ellipsis() : object(Py_Ellipsis, borrowed_t{}) { }
1023 };
1024 #endif
1025 
1026 class bool_ : public object {
1027 public:
1028  PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool)
1029  bool_() : object(Py_False, borrowed_t{}) { }
1030  // Allow implicit conversion from and to `bool`:
1031  bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) { }
1032  operator bool() const { return m_ptr && PyLong_AsLong(m_ptr) != 0; }
1033 
1034 private:
1036  static PyObject *raw_bool(PyObject *op) {
1037  const auto value = PyObject_IsTrue(op);
1038  if (value == -1) return nullptr;
1039  return handle(value ? Py_True : Py_False).inc_ref().ptr();
1040  }
1041 };
1042 
1043 NAMESPACE_BEGIN(detail)
1044 // Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1;
1045 // otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned).
1046 // (The distinction is critically important when casting a returned -1 error value to some other
1047 // unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes).
1048 template <typename Unsigned>
1049 Unsigned as_unsigned(PyObject *o) {
1050  if (sizeof(Unsigned) <= sizeof(unsigned long)
1051 #if PY_VERSION_HEX < 0x03000000
1052  || PyInt_Check(o)
1053 #endif
1054  ) {
1055  unsigned long v = PyLong_AsUnsignedLong(o);
1056  return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1057  }
1058  else {
1059  unsigned long long v = PyLong_AsUnsignedLongLong(o);
1060  return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1061  }
1062 }
1063 NAMESPACE_END(detail)
1064 
1065 class int_ : public object {
1066 public:
1068  int_() : object(PyLong_FromLong(0), stolen_t{}) { }
1069  // Allow implicit conversion from C++ integral types:
1070  template <typename T,
1072  int_(T value) {
1073  if (sizeof(T) <= sizeof(long)) {
1075  m_ptr = PyLong_FromLong((long) value);
1076  else
1077  m_ptr = PyLong_FromUnsignedLong((unsigned long) value);
1078  } else {
1080  m_ptr = PyLong_FromLongLong((long long) value);
1081  else
1082  m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value);
1083  }
1084  if (!m_ptr) pybind11_fail("Could not allocate int object!");
1085  }
1086 
1087  template <typename T,
1088  detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1089  operator T() const {
1091  ? detail::as_unsigned<T>(m_ptr)
1092  : sizeof(T) <= sizeof(long)
1093  ? (T) PyLong_AsLong(m_ptr)
1094  : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
1095  }
1096 };
1098 class float_ : public object {
1099 public:
1100  PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)
1101  // Allow implicit conversion from float/double:
1102  float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1103  if (!m_ptr) pybind11_fail("Could not allocate float object!");
1104  }
1105  float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1106  if (!m_ptr) pybind11_fail("Could not allocate float object!");
1107  }
1108  operator float() const { return (float) PyFloat_AsDouble(m_ptr); }
1109  operator double() const { return (double) PyFloat_AsDouble(m_ptr); }
1110 };
1112 class weakref : public object {
1113 public:
1114  PYBIND11_OBJECT_DEFAULT(weakref, object, PyWeakref_Check)
1115  explicit weakref(handle obj, handle callback = {})
1116  : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) {
1117  if (!m_ptr) pybind11_fail("Could not allocate weak reference!");
1118  }
1119 };
1121 class slice : public object {
1122 public:
1123  PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check)
1124  slice(ssize_t start_, ssize_t stop_, ssize_t step_) {
1125  int_ start(start_), stop(stop_), step(step_);
1126  m_ptr = PySlice_New(start.ptr(), stop.ptr(), step.ptr());
1127  if (!m_ptr) pybind11_fail("Could not allocate slice object!");
1128  }
1129  bool compute(size_t length, size_t *start, size_t *stop, size_t *step,
1130  size_t *slicelength) const {
1131  return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1132  (ssize_t) length, (ssize_t *) start,
1133  (ssize_t *) stop, (ssize_t *) step,
1134  (ssize_t *) slicelength) == 0;
1135  }
1136  bool compute(ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step,
1137  ssize_t *slicelength) const {
1138  return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1139  length, start,
1140  stop, step,
1141  slicelength) == 0;
1142  }
1143 };
1145 class capsule : public object {
1146 public:
1147  PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact)
1148  PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()")
1149  capsule(PyObject *ptr, bool is_borrowed) : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) { }
1150 
1151  explicit capsule(const void *value, const char *name = nullptr, void (*destructor)(PyObject *) = nullptr)
1152  : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) {
1153  if (!m_ptr)
1154  pybind11_fail("Could not allocate capsule object!");
1155  }
1156 
1157  PYBIND11_DEPRECATED("Please pass a destructor that takes a void pointer as input")
1158  capsule(const void *value, void (*destruct)(PyObject *))
1159  : object(PyCapsule_New(const_cast<void*>(value), nullptr, destruct), stolen_t{}) {
1160  if (!m_ptr)
1161  pybind11_fail("Could not allocate capsule object!");
1162  }
1163 
1164  capsule(const void *value, void (*destructor)(void *)) {
1165  m_ptr = PyCapsule_New(const_cast<void *>(value), nullptr, [](PyObject *o) {
1166  auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o));
1167  void *ptr = PyCapsule_GetPointer(o, nullptr);
1168  destructor(ptr);
1169  });
1170 
1171  if (!m_ptr)
1172  pybind11_fail("Could not allocate capsule object!");
1173 
1174  if (PyCapsule_SetContext(m_ptr, (void *) destructor) != 0)
1175  pybind11_fail("Could not set capsule context!");
1176  }
1177 
1178  capsule(void (*destructor)()) {
1179  m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) {
1180  auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, nullptr));
1181  destructor();
1182  });
1183 
1184  if (!m_ptr)
1185  pybind11_fail("Could not allocate capsule object!");
1186  }
1187 
1188  template <typename T> operator T *() const {
1189  auto name = this->name();
1190  T * result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));
1191  if (!result) pybind11_fail("Unable to extract capsule contents!");
1192  return result;
1193  }
1194 
1195  const char *name() const { return PyCapsule_GetName(m_ptr); }
1196 };
1198 class tuple : public object {
1199 public:
1200  PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple)
1201  explicit tuple(size_t size = 0) : object(PyTuple_New((ssize_t) size), stolen_t{}) {
1202  if (!m_ptr) pybind11_fail("Could not allocate tuple object!");
1203  }
1204  size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
1205  bool empty() const { return size() == 0; }
1206  detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }
1207  detail::item_accessor operator[](handle h) const { return object::operator[](h); }
1208  detail::tuple_iterator begin() const { return {*this, 0}; }
1209  detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }
1210 };
1212 class dict : public object {
1213 public:
1214  PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)
1215  dict() : object(PyDict_New(), stolen_t{}) {
1216  if (!m_ptr) pybind11_fail("Could not allocate dict object!");
1217  }
1218  template <typename... Args,
1220  // MSVC workaround: it can't compile an out-of-line definition, so defer the collector
1222  explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) { }
1224  size_t size() const { return (size_t) PyDict_Size(m_ptr); }
1225  bool empty() const { return size() == 0; }
1226  detail::dict_iterator begin() const { return {*this, 0}; }
1227  detail::dict_iterator end() const { return {}; }
1228  void clear() const { PyDict_Clear(ptr()); }
1229  template <typename T> bool contains(T &&key) const {
1230  return PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr()) == 1;
1231  }
1232 
1233 private:
1235  static PyObject *raw_dict(PyObject *op) {
1236  if (PyDict_Check(op))
1237  return handle(op).inc_ref().ptr();
1238  return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
1239  }
1240 };
1242 class sequence : public object {
1243 public:
1244  PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)
1245  size_t size() const { return (size_t) PySequence_Size(m_ptr); }
1246  bool empty() const { return size() == 0; }
1247  detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
1248  detail::item_accessor operator[](handle h) const { return object::operator[](h); }
1249  detail::sequence_iterator begin() const { return {*this, 0}; }
1250  detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; }
1251 };
1253 class list : public object {
1254 public:
1255  PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
1256  explicit list(size_t size = 0) : object(PyList_New((ssize_t) size), stolen_t{}) {
1257  if (!m_ptr) pybind11_fail("Could not allocate list object!");
1258  }
1259  size_t size() const { return (size_t) PyList_Size(m_ptr); }
1260  bool empty() const { return size() == 0; }
1261  detail::list_accessor operator[](size_t index) const { return {*this, index}; }
1262  detail::item_accessor operator[](handle h) const { return object::operator[](h); }
1263  detail::list_iterator begin() const { return {*this, 0}; }
1264  detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
1265  template <typename T> void append(T &&val) const {
1266  PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
1267  }
1268  template <typename T> void insert(size_t index, T &&val) const {
1269  PyList_Insert(m_ptr, static_cast<ssize_t>(index),
1270  detail::object_or_cast(std::forward<T>(val)).ptr());
1271  }
1272 };
1274 class args : public tuple { PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) };
1275 class kwargs : public dict { PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check) };
1277 class set : public object {
1278 public:
1279  PYBIND11_OBJECT_CVT(set, object, PySet_Check, PySet_New)
1280  set() : object(PySet_New(nullptr), stolen_t{}) {
1281  if (!m_ptr) pybind11_fail("Could not allocate set object!");
1282  }
1283  size_t size() const { return (size_t) PySet_Size(m_ptr); }
1284  bool empty() const { return size() == 0; }
1285  template <typename T> bool add(T &&val) const {
1286  return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
1287  }
1288  void clear() const { PySet_Clear(m_ptr); }
1289  template <typename T> bool contains(T &&val) const {
1290  return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1;
1291  }
1292 };
1294 class function : public object {
1295 public:
1296  PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)
1297  handle cpp_function() const {
1298  handle fun = detail::get_function(m_ptr);
1299  if (fun && PyCFunction_Check(fun.ptr()))
1300  return fun;
1301  return handle();
1302  }
1303  bool is_cpp_function() const { return (bool) cpp_function(); }
1304 };
1306 class staticmethod : public object {
1307 public:
1308  PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)
1309 };
1311 class buffer : public object {
1312 public:
1313  PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)
1314 
1315  buffer_info request(bool writable = false) const {
1316  int flags = PyBUF_STRIDES | PyBUF_FORMAT;
1317  if (writable) flags |= PyBUF_WRITABLE;
1318  Py_buffer *view = new Py_buffer();
1319  if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
1320  delete view;
1321  throw error_already_set();
1322  }
1323  return buffer_info(view);
1324  }
1325 };
1327 class memoryview : public object {
1328 public:
1329  explicit memoryview(const buffer_info& info) {
1330  static Py_buffer buf { };
1331  // Py_buffer uses signed sizes, strides and shape!..
1332  static std::vector<Py_ssize_t> py_strides { };
1333  static std::vector<Py_ssize_t> py_shape { };
1334  buf.buf = info.ptr;
1335  buf.itemsize = info.itemsize;
1336  buf.format = const_cast<char *>(info.format.c_str());
1337  buf.ndim = (int) info.ndim;
1338  buf.len = info.size;
1339  py_strides.clear();
1340  py_shape.clear();
1341  for (size_t i = 0; i < (size_t) info.ndim; ++i) {
1342  py_strides.push_back(info.strides[i]);
1343  py_shape.push_back(info.shape[i]);
1344  }
1345  buf.strides = py_strides.data();
1346  buf.shape = py_shape.data();
1347  buf.suboffsets = nullptr;
1348  buf.readonly = false;
1349  buf.internal = nullptr;
1350 
1351  m_ptr = PyMemoryView_FromBuffer(&buf);
1352  if (!m_ptr)
1353  pybind11_fail("Unable to create memoryview from buffer descriptor");
1354  }
1356  PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
1357 };
1359 
1362 inline size_t len(handle h) {
1363  ssize_t result = PyObject_Length(h.ptr());
1364  if (result < 0)
1365  pybind11_fail("Unable to compute length of object");
1366  return (size_t) result;
1367 }
1369 inline size_t len_hint(handle h) {
1370 #if PY_VERSION_HEX >= 0x03040000
1371  ssize_t result = PyObject_LengthHint(h.ptr(), 0);
1372 #else
1373  ssize_t result = PyObject_Length(h.ptr());
1374 #endif
1375  if (result < 0) {
1376  // Sometimes a length can't be determined at all (eg generators)
1377  // In which case simply return 0
1378  PyErr_Clear();
1379  return 0;
1380  }
1381  return (size_t) result;
1382 }
1384 inline str repr(handle h) {
1385  PyObject *str_value = PyObject_Repr(h.ptr());
1386  if (!str_value) throw error_already_set();
1387 #if PY_MAJOR_VERSION < 3
1388  PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
1389  Py_XDECREF(str_value); str_value = unicode;
1390  if (!str_value) throw error_already_set();
1391 #endif
1392  return reinterpret_steal<str>(str_value);
1393 }
1395 inline iterator iter(handle obj) {
1396  PyObject *result = PyObject_GetIter(obj.ptr());
1397  if (!result) { throw error_already_set(); }
1398  return reinterpret_steal<iterator>(result);
1399 }
1401 
1403 template <typename D> iterator object_api<D>::begin() const { return iter(derived()); }
1404 template <typename D> iterator object_api<D>::end() const { return iterator::sentinel(); }
1405 template <typename D> item_accessor object_api<D>::operator[](handle key) const {
1406  return {derived(), reinterpret_borrow<object>(key)};
1408 template <typename D> item_accessor object_api<D>::operator[](const char *key) const {
1409  return {derived(), pybind11::str(key)};
1411 template <typename D> obj_attr_accessor object_api<D>::attr(handle key) const {
1412  return {derived(), reinterpret_borrow<object>(key)};
1414 template <typename D> str_attr_accessor object_api<D>::attr(const char *key) const {
1415  return {derived(), key};
1417 template <typename D> args_proxy object_api<D>::operator*() const {
1418  return args_proxy(derived().ptr());
1420 template <typename D> template <typename T> bool object_api<D>::contains(T &&item) const {
1421  return attr("__contains__")(std::forward<T>(item)).template cast<bool>();
1422 }
1423 
1424 template <typename D>
1425 pybind11::str object_api<D>::str() const { return pybind11::str(derived()); }
1426 
1427 template <typename D>
1428 str_attr_accessor object_api<D>::doc() const { return attr("__doc__"); }
1429 
1430 template <typename D>
1431 handle object_api<D>::get_type() const { return (PyObject *) Py_TYPE(derived().ptr()); }
1432 
1433 template <typename D>
1434 bool object_api<D>::rich_compare(object_api const &other, int value) const {
1435  int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
1436  if (rv == -1)
1437  throw error_already_set();
1438  return rv == 1;
1439 }
1441 #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
1442  template <typename D> object object_api<D>::op() const { \
1443  object result = reinterpret_steal<object>(fn(derived().ptr())); \
1444  if (!result.ptr()) \
1445  throw error_already_set(); \
1446  return result; \
1447  }
1449 #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
1450  template <typename D> \
1451  object object_api<D>::op(object_api const &other) const { \
1452  object result = reinterpret_steal<object>( \
1453  fn(derived().ptr(), other.derived().ptr())); \
1454  if (!result.ptr()) \
1455  throw error_already_set(); \
1456  return result; \
1457  }
1459 PYBIND11_MATH_OPERATOR_UNARY (operator~, PyNumber_Invert)
1460 PYBIND11_MATH_OPERATOR_UNARY (operator-, PyNumber_Negative)
1461 PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)
1462 PYBIND11_MATH_OPERATOR_BINARY(operator+=, PyNumber_InPlaceAdd)
1463 PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)
1464 PYBIND11_MATH_OPERATOR_BINARY(operator-=, PyNumber_InPlaceSubtract)
1465 PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)
1466 PYBIND11_MATH_OPERATOR_BINARY(operator*=, PyNumber_InPlaceMultiply)
1467 PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)
1468 PYBIND11_MATH_OPERATOR_BINARY(operator/=, PyNumber_InPlaceTrueDivide)
1469 PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)
1470 PYBIND11_MATH_OPERATOR_BINARY(operator|=, PyNumber_InPlaceOr)
1471 PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)
1472 PYBIND11_MATH_OPERATOR_BINARY(operator&=, PyNumber_InPlaceAnd)
1473 PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)
1474 PYBIND11_MATH_OPERATOR_BINARY(operator^=, PyNumber_InPlaceXor)
1475 PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)
1476 PYBIND11_MATH_OPERATOR_BINARY(operator<<=, PyNumber_InPlaceLshift)
1477 PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)
1478 PYBIND11_MATH_OPERATOR_BINARY(operator>>=, PyNumber_InPlaceRshift)
1479 
1480 #undef PYBIND11_MATH_OPERATOR_UNARY
1481 #undef PYBIND11_MATH_OPERATOR_BINARY
1482 
1483 NAMESPACE_END(detail)
bool isinstance< handle >(handle obj)=delete
op_< op_invert, op_u, self_t, undefined_t > operator~(const self_t &)
Definition: operators.h:152
friend It operator-(const It &a, difference_type n)
Definition: pytypes.h:630
kwargs_proxy operator*() const
Definition: pytypes.h:755
bool is(object_api const &other) const
Equivalent to obj is other in Python.
Definition: pytypes.h:114
op_< op_float, op_u, self_t, undefined_t > float_(const self_t &)
Definition: operators.h:155
friend bool operator<=(const It &a, const It &b)
Definition: pytypes.h:638
op_< op_ixor, op_l, self_t, T > operator^=(const self_t &, const T &)
Definition: operators.h:146
op_< op_xor, op_l, self_t, self_t > operator^(const self_t &, const self_t &)
Definition: operators.h:129
T reinterpret_steal(handle h)
Definition: pytypes.h:312
object getattr(handle obj, const char *name, handle default_)
Definition: pytypes.h:424
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
Definition: pybind11.h:56
constexpr bool operator!=(const day &x, const day &y) noexcept
Definition: date.h:1282
#define PYBIND11_SLICE_OBJECT
object(handle h, stolen_t)
Definition: pytypes.h:286
#define PYBIND11_NAMESPACE
Definition: detail/common.h:26
bool contains(T &&item) const
Check if the given item is contained within this object, i.e. item in obj.
Definition: pytypes.h:1419
op_< op_or, op_l, self_t, self_t > operator|(const self_t &, const self_t &)
Definition: operators.h:132
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:182
bool isinstance< object >(handle obj)
Definition: pytypes.h:374
std::size_t size_t
constexpr day operator-(const day &x, const days &y) noexcept
Definition: date.h:1347
ssize_t hash(handle obj)
Definition: pytypes.h:441
typename Policy::reference reference
Definition: pytypes.h:611
Quick proxy class needed to implement operator-> for iterators which can&#39;t return pointers...
Definition: pytypes.h:644
Helper class which collects positional, keyword, * and ** arguments for a Python function call...
Definition: cast.h:1967
const object & value() const
Definition: pytypes.h:350
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
Definition: pytypes.h:47
std::string error_string()
op_< op_irshift, op_l, self_t, T > operator>>=(const self_t &, const T &)
Definition: operators.h:144
typename Policy::iterator_category iterator_category
Definition: pytypes.h:609
bool operator>(object_api const &other) const
Definition: pytypes.h:122
~object()
Destructor; automatically calls handle::dec_ref()
Definition: pytypes.h:240
STL namespace.
int ref_count() const
Return the object&#39;s current reference count.
Definition: pytypes.h:153
bool hasattr(handle obj, const char *name)
Definition: pytypes.h:391
reference operator*() const
Definition: pytypes.h:617
bool equal(object_api const &other) const
Equivalent to obj == other in Python.
Definition: pytypes.h:118
Tag and check to identify a class which implements the Python object API.
Definition: pytypes.h:46
ssize_t distance_to(const sequence_slow_readwrite &b) const
Definition: pytypes.h:687
op_< op_mul, op_l, self_t, self_t > operator*(const self_t &, const self_t &)
Definition: operators.h:123
size_t len(handle h)
Definition: pytypes.h:1361
typename Policy::value_type value_type
Definition: pytypes.h:610
PyObject *& ptr()
Definition: pytypes.h:183
std::vector< ssize_t > strides
Definition: buffer_info.h:24
op_< op_ilshift, op_l, self_t, T > operator<<=(const self_t &, const T &)
Definition: operators.h:143
accessor< accessor_policies::sequence_item > sequence_accessor
Definition: pytypes.h:41
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)
Definition: pytypes.h:789
std::pair< handle, handle > value_type
Definition: pytypes.h:698
Information record describing a Python buffer object.
Definition: buffer_info.h:17
std::vector< ssize_t > shape
Definition: buffer_info.h:23
const handle & dec_ref() const &
Definition: pytypes.h:197
It & operator-=(difference_type n)
Definition: pytypes.h:626
constexpr bool operator>(const day &x, const day &y) noexcept
Definition: date.h:1298
object(handle h, borrowed_t)
Definition: pytypes.h:285
object & operator=(const object &other)
Definition: pytypes.h:253
bool PyUnicode_Check_Permissive(PyObject *o)
Definition: pytypes.h:743
op_< op_isub, op_l, self_t, T > operator-=(const self_t &, const T &)
Definition: operators.h:139
bool is_none() const
Equivalent to obj is None in Python.
Definition: pytypes.h:116
typename deferred_type< T, Us... >::type deferred_t
bool isinstance_generic(handle obj, const std::type_info &tp)
op_< op_int, op_u, self_t, undefined_t > int_(const self_t &)
Definition: operators.h:154
op_< op_iadd, op_l, self_t, T > operator+=(const self_t &, const T &)
Definition: operators.h:138
friend bool operator>=(const It &a, const It &b)
Definition: pytypes.h:637
std::is_same< args_proxy, T > is_s_unpacking
Definition: pytypes.h:760
bool isinstance(handle obj, handle type)
Definition: pytypes.h:378
#define NAMESPACE_END(name)
Definition: detail/common.h:16
const Derived & derived() const
Definition: pytypes.h:55
__attribute__((deprecated("Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)"))) explicit operator enable_if_t< std key_type key
Definition: pytypes.h:496
op_< op_ior, op_l, self_t, T > operator|=(const self_t &, const T &)
Definition: operators.h:147
static PyObject * raw_str(PyObject *op)
Return string representation – always returns a new reference, even if already a str...
Definition: pytypes.h:934
handle(PyObject *ptr)
Creates a handle from the given raw Python object pointer.
Definition: pytypes.h:179
void operator=(const accessor &a) &&
Definition: pytypes.h:485
bool operator<=(object_api const &other) const
Definition: pytypes.h:121
void delattr(handle obj, const char *name)
Definition: pytypes.h:399
#define PYBIND11_LONG_CHECK(o)
accessor(handle obj, key_type key)
Definition: pytypes.h:479
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
void setattr(handle obj, const char *name, handle value)
Definition: pytypes.h:437
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
Definition: pytypes.h:807
bool PyIterable_Check(PyObject *obj)
Definition: pytypes.h:727
typename Policy::pointer pointer
Definition: pytypes.h:612
op_< op_itruediv, op_l, self_t, T > operator/=(const self_t &, const T &)
Definition: operators.h:141
size_t function_call & call
Definition: pybind11.h:1610
object & operator=(object &&other) noexcept
Definition: pytypes.h:260
std::forward_iterator_tag iterator_category
Definition: pytypes.h:697
bool PyNone_Check(PyObject *o)
Definition: pytypes.h:738
#define PYBIND11_BYTES_FROM_STRING
generic_iterator(handle seq, ssize_t index)
Definition: pytypes.h:615
std::istream & operator>>(std::istream &in, T &item)
input streaming for enumerations
Definition: CLI11.hpp:234
typename Policy::key_type key_type
Definition: pytypes.h:476
constexpr year_month operator/(const year &y, const month &m) noexcept
Definition: date.h:3221
bool equal(const sequence_slow_readwrite &b) const
Definition: pytypes.h:686
size_t len_hint(handle h)
Definition: pytypes.h:1368
std::ostream & operator<<(std::ostream &in, const T &item)
output streaming for enumerations
Definition: CLI11.hpp:227
str repr(handle h)
Definition: pytypes.h:1383
#define PYBIND11_BYTES_AS_STRING_AND_SIZE
str format(Args &&...args) const
Definition: pytypes.h:928
Python&#39;s dictionary protocol permits this to be a forward iterator.
Definition: pytypes.h:695
const std::type_info & tp
Definition: cast.h:399
#define PYBIND11_BYTES_CHECK
handle object_or_cast(PyObject *ptr)
Definition: pytypes.h:472
bool equal(const dict_readonly &b) const
Definition: pytypes.h:707
ssize_t distance_to(const sequence_fast_readonly &b) const
Definition: pytypes.h:666
str(handle h)
Definition: pytypes.h:911
def doc()
Definition: conftest.py:152
Full read and write access using the sequence protocol: see detail::sequence_accessor ...
Definition: pytypes.h:673
reference operator[](difference_type n) const
Definition: pytypes.h:618
op_< op_and, op_l, self_t, self_t > operator &(const self_t &, const self_t &)
Definition: operators.h:128
std::is_same< kwargs_proxy, T > is_ds_unpacking
Definition: pytypes.h:761
bool PyStaticMethod_Check(PyObject *o)
Definition: pytypes.h:745
bool operator==(const NonZeroIterator< std::pair< A, B >> &it, const NonZeroSentinel &)
const detail::type_info * type
Definition: cast.h:453
Annotation for function names.
Definition: attr.h:33
bool operator>=(object_api const &other) const
Definition: pytypes.h:123
constexpr day operator+(const day &x, const days &y) noexcept
Definition: date.h:1331
detail::enable_if_t<!detail::move_never< T >::value, T > move(object &&obj)
Definition: cast.h:1685
op_< op_imul, op_l, self_t, T > operator*=(const self_t &, const T &)
Definition: operators.h:140
handle release()
Definition: pytypes.h:247
std::is_base_of< arg, T > is_keyword
Python argument categories (using PEP 448 terms)
Definition: pytypes.h:759
handle get_function(handle value)
Definition: pytypes.h:450
bool matches(handle exc) const
Definition: pytypes.h:347
friend bool operator==(const It &a, const It &b)
Definition: pytypes.h:633
return os str()
void operator=(T &&value) &&
Definition: pytypes.h:488
#define PYBIND11_MATH_OPERATOR_BINARY(op, fn)
Definition: pytypes.h:1448
const object & trace() const
Definition: pytypes.h:351
#define PYBIND11_MATH_OPERATOR_UNARY(op, fn)
Definition: pytypes.h:1440
#define PYBIND11_DEPRECATED(reason)
Definition: detail/common.h:92
T reinterpret_borrow(handle h)
Definition: pytypes.h:302
It & operator+=(difference_type n)
Definition: pytypes.h:625
object(const object &o)
Copy constructor; always increases the reference count.
Definition: pytypes.h:236
Lightweight iterator policy using just a simple pointer: see PySequence_Fast_ITEMS ...
Definition: pytypes.h:652
ssize_t difference_type
Definition: pytypes.h:825
op_< op_iand, op_l, self_t, T > operator &=(const self_t &, const T &)
Definition: operators.h:145
std::random_access_iterator_tag iterator_category
Definition: pytypes.h:654
#define NAMESPACE_BEGIN(name)
Definition: detail/common.h:13
friend It operator+(difference_type n, const It &b)
Definition: pytypes.h:629
iterator iter(handle obj)
Definition: pytypes.h:1394
void operator=(const accessor &a) &
Definition: pytypes.h:486
friend It operator+(const It &a, difference_type n)
Definition: pytypes.h:628
STL iterator template used for tuple, list, sequence and dict.
Definition: pytypes.h:604
constexpr bool operator<(const day &x, const day &y) noexcept
Definition: date.h:1290
T cast(const handle &handle)
Definition: cast.h:1659
friend difference_type operator-(const It &a, const It &b)
Definition: pytypes.h:631
bool equal(const sequence_fast_readonly &b) const
Definition: pytypes.h:665
const object & type() const
Definition: pytypes.h:349
object(object &&other) noexcept
Move constructor; steals the object from other and preserves its reference count. ...
Definition: pytypes.h:238
Unsigned as_unsigned(PyObject *o)
Definition: pytypes.h:1049
bool not_equal(object_api const &other) const
Definition: pytypes.h:119
std::input_iterator_tag iterator_category
Definition: pytypes.h:824
bool operator<(object_api const &other) const
Definition: pytypes.h:120
#define PYBIND11_BYTES_FROM_STRING_AND_SIZE
std::string format
Definition: buffer_info.h:21
void operator=(T &&value) &
Definition: pytypes.h:491
#define PYBIND11_OBJECT(Name, Parent, CheckFun)
Definition: pytypes.h:801
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
const handle & inc_ref() const &
Definition: pytypes.h:190
Py_ssize_t ssize_t
friend bool operator!=(const It &a, const It &b)
Definition: pytypes.h:634
#define PYBIND11_LONG_AS_LONGLONG(o)