HepMC3 event record library
pytypes.h
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 
17 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
18 
19 /* A few forward declarations */
20 class handle; class object;
21 class str; class iterator;
22 class type;
23 struct arg; struct arg_v;
24 
25 PYBIND11_NAMESPACE_BEGIN(detail)
26 class args_proxy;
27 inline bool isinstance_generic(handle obj, const std::type_info &tp);
28 
29 // Accessor forward declarations
30 template <typename Policy> class accessor;
31 namespace accessor_policies {
32  struct obj_attr;
33  struct str_attr;
34  struct generic_item;
35  struct sequence_item;
36  struct list_item;
37  struct tuple_item;
38 } // namespace accessor_policies
45 
46 /// Tag and check to identify a class which implements the Python object API
47 class pyobject_tag { };
48 template <typename T> using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
49 
50 /** \rst
51  A mixin class which adds common functions to `handle`, `object` and various accessors.
52  The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``.
53 \endrst */
54 template <typename Derived>
55 class object_api : public pyobject_tag {
56  const Derived &derived() const { return static_cast<const Derived &>(*this); }
57 
58 public:
59  /** \rst
60  Return an iterator equivalent to calling ``iter()`` in Python. The object
61  must be a collection which supports the iteration protocol.
62  \endrst */
63  iterator begin() const;
64  /// Return a sentinel which ends iteration.
65  iterator end() const;
66 
67  /** \rst
68  Return an internal functor to invoke the object's sequence protocol. Casting
69  the returned ``detail::item_accessor`` instance to a `handle` or `object`
70  subclass causes a corresponding call to ``__getitem__``. Assigning a `handle`
71  or `object` subclass causes a call to ``__setitem__``.
72  \endrst */
73  item_accessor operator[](handle key) const;
74  /// See above (the only difference is that they key is provided as a string literal)
75  item_accessor operator[](const char *key) const;
76 
77  /** \rst
78  Return an internal functor to access the object's attributes. Casting the
79  returned ``detail::obj_attr_accessor`` instance to a `handle` or `object`
80  subclass causes a corresponding call to ``getattr``. Assigning a `handle`
81  or `object` subclass causes a call to ``setattr``.
82  \endrst */
83  obj_attr_accessor attr(handle key) const;
84  /// See above (the only difference is that they key is provided as a string literal)
85  str_attr_accessor attr(const char *key) const;
86 
87  /** \rst
88  Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple``
89  or ``list`` for a function call. Applying another * to the result yields
90  ** unpacking, e.g. to unpack a dict as function keyword arguments.
91  See :ref:`calling_python_functions`.
92  \endrst */
93  args_proxy operator*() const;
94 
95  /// Check if the given item is contained within this object, i.e. ``item in obj``.
96  template <typename T> bool contains(T &&item) const;
97 
98  /** \rst
99  Assuming the Python object is a function or implements the ``__call__``
100  protocol, ``operator()`` invokes the underlying function, passing an
101  arbitrary set of parameters. The result is returned as a `object` and
102  may need to be converted back into a Python object using `handle::cast()`.
103 
104  When some of the arguments cannot be converted to Python objects, the
105  function will throw a `cast_error` exception. When the Python function
106  call fails, a `error_already_set` exception is thrown.
107  \endrst */
108  template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
109  object operator()(Args &&...args) const;
110  template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
111  PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)")
112  object call(Args&&... args) const;
113 
114  /// Equivalent to ``obj is other`` in Python.
115  bool is(object_api const& other) const { return derived().ptr() == other.derived().ptr(); }
116  /// Equivalent to ``obj is None`` in Python.
117  bool is_none() const { return derived().ptr() == Py_None; }
118  /// Equivalent to obj == other in Python
119  bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); }
120  bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); }
121  bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); }
122  bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); }
123  bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); }
124  bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); }
125 
126  object operator-() const;
127  object operator~() 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  object operator>>=(object_api const &other) const;
146 
147  PYBIND11_DEPRECATED("Use py::str(obj) instead")
148  pybind11::str str() const;
149 
150  /// Get or set the object's docstring, i.e. ``obj.__doc__``.
151  str_attr_accessor doc() const;
152 
153  /// Return the object's current reference count
154  int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); }
155 
156  // TODO PYBIND11_DEPRECATED("Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()")
157  handle get_type() const;
158 
159 private:
160  bool rich_compare(object_api const &other, int value) const;
161 };
162 
163 PYBIND11_NAMESPACE_END(detail)
164 
165 /** \rst
166  Holds a reference to a Python object (no reference counting)
167 
168  The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a
169  ``PyObject *`` in Python's C API). It does not perform any automatic reference
170  counting and merely provides a basic C++ interface to various Python API functions.
171 
172  .. seealso::
173  The `object` class inherits from `handle` and adds automatic reference
174  counting features.
175 \endrst */
176 class handle : public detail::object_api<handle> {
177 public:
178  /// The default constructor creates a handle with a ``nullptr``-valued pointer
179  handle() = default;
180  /// Creates a ``handle`` from the given raw Python object pointer
181  handle(PyObject *ptr) : m_ptr(ptr) { } // Allow implicit conversion from PyObject*
182 
183  /// Return the underlying ``PyObject *`` pointer
184  PyObject *ptr() const { return m_ptr; }
185  PyObject *&ptr() { return m_ptr; }
186 
187  /** \rst
188  Manually increase the reference count of the Python object. Usually, it is
189  preferable to use the `object` class which derives from `handle` and calls
190  this function automatically. Returns a reference to itself.
191  \endrst */
192  const handle& inc_ref() const & { Py_XINCREF(m_ptr); return *this; }
193 
194  /** \rst
195  Manually decrease the reference count of the Python object. Usually, it is
196  preferable to use the `object` class which derives from `handle` and calls
197  this function automatically. Returns a reference to itself.
198  \endrst */
199  const handle& dec_ref() const & { Py_XDECREF(m_ptr); return *this; }
200 
201  /** \rst
202  Attempt to cast the Python object into the given C++ type. A `cast_error`
203  will be throw upon failure.
204  \endrst */
205  template <typename T> T cast() const;
206  /// Return ``true`` when the `handle` wraps a valid Python object
207  explicit operator bool() const { return m_ptr != nullptr; }
208  /** \rst
209  Deprecated: Check that the underlying pointers are the same.
210  Equivalent to ``obj1 is obj2`` in Python.
211  \endrst */
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 !obj1.is(obj2) instead")
215  bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }
216  PYBIND11_DEPRECATED("Use handle::operator bool() instead")
217  bool check() const { return m_ptr != nullptr; }
218 protected:
219  PyObject *m_ptr = nullptr;
220 };
221 
222 /** \rst
223  Holds a reference to a Python object (with reference counting)
224 
225  Like `handle`, the `object` class is a thin wrapper around an arbitrary Python
226  object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it
227  optionally increases the object's reference count upon construction, and it
228  *always* decreases the reference count when the `object` instance goes out of
229  scope and is destructed. When using `object` instances consistently, it is much
230  easier to get reference counting right at the first attempt.
231 \endrst */
232 class object : public handle {
233 public:
234  object() = default;
235  PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()")
236  object(handle h, bool is_borrowed) : handle(h) { if (is_borrowed) inc_ref(); }
237  /// Copy constructor; always increases the reference count
238  object(const object &o) : handle(o) { inc_ref(); }
239  /// Move constructor; steals the object from ``other`` and preserves its reference count
240  object(object &&other) noexcept { m_ptr = other.m_ptr; other.m_ptr = nullptr; }
241  /// Destructor; automatically calls `handle::dec_ref()`
242  ~object() { dec_ref(); }
243 
244  /** \rst
245  Resets the internal pointer to ``nullptr`` without decreasing the
246  object's reference count. The function returns a raw handle to the original
247  Python object.
248  \endrst */
250  PyObject *tmp = m_ptr;
251  m_ptr = nullptr;
252  return handle(tmp);
253  }
254 
255  object& operator=(const object &other) {
256  other.inc_ref();
257  dec_ref();
258  m_ptr = other.m_ptr;
259  return *this;
260  }
261 
262  object& operator=(object &&other) noexcept {
263  if (this != &other) {
264  handle temp(m_ptr);
265  m_ptr = other.m_ptr;
266  other.m_ptr = nullptr;
267  temp.dec_ref();
268  }
269  return *this;
270  }
271 
272  // Calling cast() on an object lvalue just copies (via handle::cast)
273  template <typename T> T cast() const &;
274  // Calling on an object rvalue does a move, if needed and/or possible
275  template <typename T> T cast() &&;
276 
277 protected:
278  // Tags for choosing constructors from raw PyObject *
279  struct borrowed_t { };
280  struct stolen_t { };
281 
282  template <typename T> friend T reinterpret_borrow(handle);
283  template <typename T> friend T reinterpret_steal(handle);
284 
285 public:
286  // Only accessible from derived classes and the reinterpret_* functions
287  object(handle h, borrowed_t) : handle(h) { inc_ref(); }
288  object(handle h, stolen_t) : handle(h) { }
289 };
290 
291 /** \rst
292  Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference.
293  The target type ``T`` must be `object` or one of its derived classes. The function
294  doesn't do any conversions or checks. It's up to the user to make sure that the
295  target type is correct.
296 
297  .. code-block:: cpp
298 
299  PyObject *p = PyList_GetItem(obj, index);
300  py::object o = reinterpret_borrow<py::object>(p);
301  // or
302  py::tuple t = reinterpret_borrow<py::tuple>(p); // <-- `p` must be already be a `tuple`
303 \endrst */
304 template <typename T> T reinterpret_borrow(handle h) { return {h, object::borrowed_t{}}; }
305 
306 /** \rst
307  Like `reinterpret_borrow`, but steals the reference.
308 
309  .. code-block:: cpp
310 
311  PyObject *p = PyObject_Str(obj);
312  py::str s = reinterpret_steal<py::str>(p); // <-- `p` must be already be a `str`
313 \endrst */
314 template <typename T> T reinterpret_steal(handle h) { return {h, object::stolen_t{}}; }
315 
316 PYBIND11_NAMESPACE_BEGIN(detail)
317 inline std::string error_string();
318 PYBIND11_NAMESPACE_END(detail)
319 
320 /// Fetch and hold an error which was already set in Python. An instance of this is typically
321 /// thrown to propagate python-side errors back through C++ which can either be caught manually or
322 /// else falls back to the function dispatcher (which then raises the captured error back to
323 /// python).
324 class error_already_set : public std::runtime_error {
325 public:
326  /// Constructs a new exception from the current Python error indicator, if any. The current
327  /// Python error indicator will be cleared.
328  error_already_set() : std::runtime_error(detail::error_string()) {
329  PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
330  }
331 
332  error_already_set(const error_already_set &) = default;
333  error_already_set(error_already_set &&) = default;
334 
335  inline ~error_already_set() override;
336 
337  /// Give the currently-held error back to Python, if any. If there is currently a Python error
338  /// already set it is cleared first. After this call, the current object no longer stores the
339  /// error variables (but the `.what()` string is still available).
340  void restore() { PyErr_Restore(m_type.release().ptr(), m_value.release().ptr(), m_trace.release().ptr()); }
341 
342  /// If it is impossible to raise the currently-held error, such as in destructor, we can write
343  /// it out using Python's unraisable hook (sys.unraisablehook). The error context should be
344  /// some object whose repr() helps identify the location of the error. Python already knows the
345  /// type and value of the error, so there is no need to repeat that. For example, __func__ could
346  /// be helpful. After this call, the current object no longer stores the error variables,
347  /// and neither does Python.
348  void discard_as_unraisable(object err_context) {
349  restore();
350  PyErr_WriteUnraisable(err_context.ptr());
351  }
352  void discard_as_unraisable(const char *err_context) {
353  discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context)));
354  }
355 
356  // Does nothing; provided for backwards compatibility.
357  PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated")
358  void clear() {}
359 
360  /// Check if the currently trapped error type matches the given Python exception class (or a
361  /// subclass thereof). May also be passed a tuple to search for any exception class matches in
362  /// the given tuple.
363  bool matches(handle exc) const { return PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()); }
364 
365  const object& type() const { return m_type; }
366  const object& value() const { return m_value; }
367  const object& trace() const { return m_trace; }
368 
369 private:
370  object m_type, m_value, m_trace;
371 };
372 
373 /** \defgroup python_builtins _
374  Unless stated otherwise, the following C++ functions behave the same
375  as their Python counterparts.
376  */
377 
378 /** \ingroup python_builtins
379  \rst
380  Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of
381  `object` or a class which was exposed to Python as ``py::class_<T>``.
382 \endrst */
383 template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0>
384 bool isinstance(handle obj) { return T::check_(obj); }
385 
386 template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0>
387 bool isinstance(handle obj) { return detail::isinstance_generic(obj, typeid(T)); }
388 
389 template <> inline bool isinstance<handle>(handle) = delete;
390 template <> inline bool isinstance<object>(handle obj) { return obj.ptr() != nullptr; }
391 
392 /// \ingroup python_builtins
393 /// Return true if ``obj`` is an instance of the ``type``.
394 inline bool isinstance(handle obj, handle type) {
395  const auto result = PyObject_IsInstance(obj.ptr(), type.ptr());
396  if (result == -1)
397  throw error_already_set();
398  return result != 0;
399 }
400 
401 /// \addtogroup python_builtins
402 /// @{
403 inline bool hasattr(handle obj, handle name) {
404  return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1;
405 }
406 
407 inline bool hasattr(handle obj, const char *name) {
408  return PyObject_HasAttrString(obj.ptr(), name) == 1;
409 }
410 
411 inline void delattr(handle obj, handle name) {
412  if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) { throw error_already_set(); }
413 }
414 
415 inline void delattr(handle obj, const char *name) {
416  if (PyObject_DelAttrString(obj.ptr(), name) != 0) { throw error_already_set(); }
417 }
418 
419 inline object getattr(handle obj, handle name) {
420  PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr());
421  if (!result) { throw error_already_set(); }
422  return reinterpret_steal<object>(result);
423 }
424 
425 inline object getattr(handle obj, const char *name) {
426  PyObject *result = PyObject_GetAttrString(obj.ptr(), name);
427  if (!result) { throw error_already_set(); }
428  return reinterpret_steal<object>(result);
429 }
430 
431 inline object getattr(handle obj, handle name, handle default_) {
432  if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) {
433  return reinterpret_steal<object>(result);
434  } else {
435  PyErr_Clear();
436  return reinterpret_borrow<object>(default_);
437  }
438 }
439 
440 inline object getattr(handle obj, const char *name, handle default_) {
441  if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) {
442  return reinterpret_steal<object>(result);
443  } else {
444  PyErr_Clear();
445  return reinterpret_borrow<object>(default_);
446  }
447 }
448 
449 inline void setattr(handle obj, handle name, handle value) {
450  if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) { throw error_already_set(); }
451 }
452 
453 inline void setattr(handle obj, const char *name, handle value) {
454  if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { throw error_already_set(); }
455 }
456 
457 inline ssize_t hash(handle obj) {
458  auto h = PyObject_Hash(obj.ptr());
459  if (h == -1) { throw error_already_set(); }
460  return h;
461 }
462 
463 /// @} python_builtins
464 
465 PYBIND11_NAMESPACE_BEGIN(detail)
466 inline handle get_function(handle value) {
467  if (value) {
468 #if PY_MAJOR_VERSION >= 3
469  if (PyInstanceMethod_Check(value.ptr()))
470  value = PyInstanceMethod_GET_FUNCTION(value.ptr());
471  else
472 #endif
473  if (PyMethod_Check(value.ptr()))
474  value = PyMethod_GET_FUNCTION(value.ptr());
475  }
476  return value;
477 }
478 
479 // Helper aliases/functions to support implicit casting of values given to python accessors/methods.
480 // When given a pyobject, this simply returns the pyobject as-is; for other C++ type, the value goes
481 // through pybind11::cast(obj) to convert it to an `object`.
482 template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0>
483 auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) { return std::forward<T>(o); }
484 // The following casting version is implemented in cast.h:
485 template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0>
486 object object_or_cast(T &&o);
487 // Match a PyObject*, which we want to convert directly to handle via its converting constructor
488 inline handle object_or_cast(PyObject *ptr) { return ptr; }
489 
490 template <typename Policy>
491 class accessor : public object_api<accessor<Policy>> {
492  using key_type = typename Policy::key_type;
493 
494 public:
495  accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) { }
496  accessor(const accessor &) = default;
497  accessor(accessor &&) = default;
498 
499  // accessor overload required to override default assignment operator (templates are not allowed
500  // to replace default compiler-generated assignments).
501  void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); }
502  void operator=(const accessor &a) & { operator=(handle(a)); }
503 
504  template <typename T> void operator=(T &&value) && {
505  Policy::set(obj, key, object_or_cast(std::forward<T>(value)));
506  }
507  template <typename T> void operator=(T &&value) & {
508  get_cache() = reinterpret_borrow<object>(object_or_cast(std::forward<T>(value)));
509  }
510 
511  template <typename T = Policy>
512  PYBIND11_DEPRECATED("Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
513  explicit operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value ||
514  std::is_same<T, accessor_policies::obj_attr>::value, bool>() const {
515  return hasattr(obj, key);
516  }
517  template <typename T = Policy>
518  PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
519  explicit operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const {
520  return obj.contains(key);
521  }
522 
523  operator object() const { return get_cache(); }
524  PyObject *ptr() const { return get_cache().ptr(); }
525  template <typename T> T cast() const { return get_cache().template cast<T>(); }
526 
527 private:
528  object &get_cache() const {
529  if (!cache) { cache = Policy::get(obj, key); }
530  return cache;
531  }
532 
533 private:
534  handle obj;
535  key_type key;
536  mutable object cache;
537 };
538 
539 PYBIND11_NAMESPACE_BEGIN(accessor_policies)
540 struct obj_attr {
541  using key_type = object;
542  static object get(handle obj, handle key) { return getattr(obj, key); }
543  static void set(handle obj, handle key, handle val) { setattr(obj, key, val); }
544 };
545 
546 struct str_attr {
547  using key_type = const char *;
548  static object get(handle obj, const char *key) { return getattr(obj, key); }
549  static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); }
550 };
551 
552 struct generic_item {
553  using key_type = object;
554 
555  static object get(handle obj, handle key) {
556  PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr());
557  if (!result) { throw error_already_set(); }
558  return reinterpret_steal<object>(result);
559  }
560 
561  static void set(handle obj, handle key, handle val) {
562  if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) { throw error_already_set(); }
563  }
564 };
565 
567  using key_type = size_t;
568 
569  static object get(handle obj, size_t index) {
570  PyObject *result = PySequence_GetItem(obj.ptr(), static_cast<ssize_t>(index));
571  if (!result) { throw error_already_set(); }
572  return reinterpret_steal<object>(result);
573  }
574 
575  static void set(handle obj, size_t index, handle val) {
576  // PySequence_SetItem does not steal a reference to 'val'
577  if (PySequence_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.ptr()) != 0) {
578  throw error_already_set();
579  }
580  }
581 };
582 
583 struct list_item {
584  using key_type = size_t;
585 
586  static object get(handle obj, size_t index) {
587  PyObject *result = PyList_GetItem(obj.ptr(), static_cast<ssize_t>(index));
588  if (!result) { throw error_already_set(); }
589  return reinterpret_borrow<object>(result);
590  }
591 
592  static void set(handle obj, size_t index, handle val) {
593  // PyList_SetItem steals a reference to 'val'
594  if (PyList_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.inc_ref().ptr()) != 0) {
595  throw error_already_set();
596  }
597  }
598 };
599 
600 struct tuple_item {
601  using key_type = size_t;
602 
603  static object get(handle obj, size_t index) {
604  PyObject *result = PyTuple_GetItem(obj.ptr(), static_cast<ssize_t>(index));
605  if (!result) { throw error_already_set(); }
606  return reinterpret_borrow<object>(result);
607  }
608 
609  static void set(handle obj, size_t index, handle val) {
610  // PyTuple_SetItem steals a reference to 'val'
611  if (PyTuple_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.inc_ref().ptr()) != 0) {
612  throw error_already_set();
613  }
614  }
615 };
616 PYBIND11_NAMESPACE_END(accessor_policies)
617 
618 /// STL iterator template used for tuple, list, sequence and dict
619 template <typename Policy>
620 class generic_iterator : public Policy {
621  using It = generic_iterator;
622 
623 public:
624  using difference_type = ssize_t;
625  using iterator_category = typename Policy::iterator_category;
626  using value_type = typename Policy::value_type;
627  using reference = typename Policy::reference;
628  using pointer = typename Policy::pointer;
629 
630  generic_iterator() = default;
631  generic_iterator(handle seq, ssize_t index) : Policy(seq, index) { }
632 
633  reference operator*() const { return Policy::dereference(); }
634  reference operator[](difference_type n) const { return *(*this + n); }
635  pointer operator->() const { return **this; }
636 
637  It &operator++() { Policy::increment(); return *this; }
638  It operator++(int) { auto copy = *this; Policy::increment(); return copy; }
639  It &operator--() { Policy::decrement(); return *this; }
640  It operator--(int) { auto copy = *this; Policy::decrement(); return copy; }
641  It &operator+=(difference_type n) { Policy::advance(n); return *this; }
642  It &operator-=(difference_type n) { Policy::advance(-n); return *this; }
643 
644  friend It operator+(const It &a, difference_type n) { auto copy = a; return copy += n; }
645  friend It operator+(difference_type n, const It &b) { return b + n; }
646  friend It operator-(const It &a, difference_type n) { auto copy = a; return copy -= n; }
647  friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); }
648 
649  friend bool operator==(const It &a, const It &b) { return a.equal(b); }
650  friend bool operator!=(const It &a, const It &b) { return !(a == b); }
651  friend bool operator< (const It &a, const It &b) { return b - a > 0; }
652  friend bool operator> (const It &a, const It &b) { return b < a; }
653  friend bool operator>=(const It &a, const It &b) { return !(a < b); }
654  friend bool operator<=(const It &a, const It &b) { return !(a > b); }
655 };
656 
657 PYBIND11_NAMESPACE_BEGIN(iterator_policies)
658 /// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers
659 template <typename T>
660 struct arrow_proxy {
661  T value;
662 
663  arrow_proxy(T &&value) : value(std::move(value)) { }
664  T *operator->() const { return &value; }
665 };
666 
667 /// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS``
669 protected:
670  using iterator_category = std::random_access_iterator_tag;
671  using value_type = handle;
672  using reference = const handle;
674 
675  sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) { }
676 
677  reference dereference() const { return *ptr; }
678  void increment() { ++ptr; }
679  void decrement() { --ptr; }
680  void advance(ssize_t n) { ptr += n; }
681  bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; }
682  ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; }
683 
684 private:
685  PyObject **ptr;
686 };
687 
688 /// Full read and write access using the sequence protocol: see ``detail::sequence_accessor``
690 protected:
691  using iterator_category = std::random_access_iterator_tag;
692  using value_type = object;
695 
696  sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) { }
697 
698  reference dereference() const { return {obj, static_cast<size_t>(index)}; }
699  void increment() { ++index; }
700  void decrement() { --index; }
701  void advance(ssize_t n) { index += n; }
702  bool equal(const sequence_slow_readwrite &b) const { return index == b.index; }
703  ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; }
704 
705 private:
706  handle obj;
707  ssize_t index;
708 };
709 
710 /// Python's dictionary protocol permits this to be a forward iterator
712 protected:
713  using iterator_category = std::forward_iterator_tag;
714  using value_type = std::pair<handle, handle>;
715  using reference = const value_type;
717 
718  dict_readonly() = default;
719  dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }
720 
721  reference dereference() const { return {key, value}; }
722  void increment() { if (!PyDict_Next(obj.ptr(), &pos, &key, &value)) { pos = -1; } }
723  bool equal(const dict_readonly &b) const { return pos == b.pos; }
724 
725 private:
726  handle obj;
727  PyObject *key = nullptr, *value = nullptr;
728  ssize_t pos = -1;
729 };
730 PYBIND11_NAMESPACE_END(iterator_policies)
731 
732 #if !defined(PYPY_VERSION)
735 #else
738 #endif
739 
742 
743 inline bool PyIterable_Check(PyObject *obj) {
744  PyObject *iter = PyObject_GetIter(obj);
745  if (iter) {
746  Py_DECREF(iter);
747  return true;
748  } else {
749  PyErr_Clear();
750  return false;
751  }
752 }
753 
754 inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
755 inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }
756 
757 inline bool PyUnicode_Check_Permissive(PyObject *o) { return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); }
758 
759 inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; }
760 
761 class kwargs_proxy : public handle {
762 public:
763  explicit kwargs_proxy(handle h) : handle(h) { }
764 };
765 
766 class args_proxy : public handle {
767 public:
768  explicit args_proxy(handle h) : handle(h) { }
769  kwargs_proxy operator*() const { return kwargs_proxy(*this); }
770 };
771 
772 /// Python argument categories (using PEP 448 terms)
773 template <typename T> using is_keyword = std::is_base_of<arg, T>;
774 template <typename T> using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking
775 template <typename T> using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking
776 template <typename T> using is_positional = satisfies_none_of<T,
777  is_keyword, is_s_unpacking, is_ds_unpacking
778 >;
780 
781 // Call argument collector forward declarations
782 template <return_value_policy policy = return_value_policy::automatic_reference>
784 template <return_value_policy policy = return_value_policy::automatic_reference>
786 
787 PYBIND11_NAMESPACE_END(detail)
788 
789 // TODO: After the deprecated constructors are removed, this macro can be simplified by
790 // inheriting ctors: `using Parent::Parent`. It's not an option right now because
791 // the `using` statement triggers the parent deprecation warning even if the ctor
792 // isn't even used.
793 #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
794  public: \
795  PYBIND11_DEPRECATED("Use reinterpret_borrow<"#Name">() or reinterpret_steal<"#Name">()") \
796  Name(handle h, bool is_borrowed) : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) { } \
797  Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) { } \
798  Name(handle h, stolen_t) : Parent(h, stolen_t{}) { } \
799  PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
800  bool check() const { return m_ptr != nullptr && (bool) CheckFun(m_ptr); } \
801  static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \
802  template <typename Policy_> \
803  Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) { }
804 
805 #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
806  PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
807  /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
808  Name(const object &o) \
809  : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) \
810  { if (!m_ptr) throw error_already_set(); } \
811  Name(object &&o) \
812  : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) \
813  { if (!m_ptr) throw error_already_set(); }
814 
815 #define PYBIND11_OBJECT_CHECK_FAILED(Name, o) \
816  ::pybind11::type_error("Object of type '" + \
817  ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o.ptr())) + \
818  "' is not an instance of '" #Name "'")
819 
820 #define PYBIND11_OBJECT(Name, Parent, CheckFun) \
821  PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
822  /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
823  Name(const object &o) : Parent(o) \
824  { if (o && !check_(o)) throw PYBIND11_OBJECT_CHECK_FAILED(Name, o); } \
825  Name(object &&o) : Parent(std::move(o)) \
826  { if (o && !check_(o)) throw PYBIND11_OBJECT_CHECK_FAILED(Name, o); }
827 
828 #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
829  PYBIND11_OBJECT(Name, Parent, CheckFun) \
830  Name() : Parent() { }
831 
832 /// \addtogroup pytypes
833 /// @{
834 
835 /** \rst
836  Wraps a Python iterator so that it can also be used as a C++ input iterator
837 
838  Caveat: copying an iterator does not (and cannot) clone the internal
839  state of the Python iterable. This also applies to the post-increment
840  operator. This iterator should only be used to retrieve the current
841  value using ``operator*()``.
842 \endrst */
843 class iterator : public object {
844 public:
845  using iterator_category = std::input_iterator_tag;
846  using difference_type = ssize_t;
847  using value_type = handle;
848  using reference = const handle;
849  using pointer = const handle *;
850 
851  PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)
852 
853  iterator& operator++() {
854  advance();
855  return *this;
856  }
857 
858  iterator operator++(int) {
859  auto rv = *this;
860  advance();
861  return rv;
862  }
863 
864  reference operator*() const {
865  if (m_ptr && !value.ptr()) {
866  auto& self = const_cast<iterator &>(*this);
867  self.advance();
868  }
869  return value;
870  }
871 
872  pointer operator->() const { operator*(); return &value; }
873 
874  /** \rst
875  The value which marks the end of the iteration. ``it == iterator::sentinel()``
876  is equivalent to catching ``StopIteration`` in Python.
877 
878  .. code-block:: cpp
879 
880  void foo(py::iterator it) {
881  while (it != py::iterator::sentinel()) {
882  // use `*it`
883  ++it;
884  }
885  }
886  \endrst */
887  static iterator sentinel() { return {}; }
888 
889  friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); }
890  friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); }
891 
892 private:
893  void advance() {
894  value = reinterpret_steal<object>(PyIter_Next(m_ptr));
895  if (PyErr_Occurred()) { throw error_already_set(); }
896  }
897 
898 private:
899  object value = {};
900 };
901 
902 
903 
904 class type : public object {
905 public:
906  PYBIND11_OBJECT(type, object, PyType_Check)
907 
908  /// Return a type handle from a handle or an object
909  static handle handle_of(handle h) { return handle((PyObject*) Py_TYPE(h.ptr())); }
910 
911  /// Return a type object from a handle or an object
912  static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); }
913 
914  // Defined in pybind11/cast.h
915  /// Convert C++ type to handle if previously registered. Does not convert
916  /// standard types, like int, float. etc. yet.
917  /// See https://github.com/pybind/pybind11/issues/2486
918  template<typename T>
919  static handle handle_of();
920 
921  /// Convert C++ type to type if previously registered. Does not convert
922  /// standard types, like int, float. etc. yet.
923  /// See https://github.com/pybind/pybind11/issues/2486
924  template<typename T>
925  static type of() {return type(type::handle_of<T>(), borrowed_t{}); }
926 };
927 
928 class iterable : public object {
929 public:
930  PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check)
931 };
932 
933 class bytes;
934 
935 class str : public object {
936 public:
937  PYBIND11_OBJECT_CVT(str, object, detail::PyUnicode_Check_Permissive, raw_str)
938 
939  str(const char *c, size_t n)
940  : object(PyUnicode_FromStringAndSize(c, (ssize_t) n), stolen_t{}) {
941  if (!m_ptr) pybind11_fail("Could not allocate string object!");
942  }
943 
944  // 'explicit' is explicitly omitted from the following constructors to allow implicit conversion to py::str from C++ string-like objects
945  str(const char *c = "")
946  : object(PyUnicode_FromString(c), stolen_t{}) {
947  if (!m_ptr) pybind11_fail("Could not allocate string object!");
948  }
949 
950  str(const std::string &s) : str(s.data(), s.size()) { }
951 
952  explicit str(const bytes &b);
953 
954  /** \rst
955  Return a string representation of the object. This is analogous to
956  the ``str()`` function in Python.
957  \endrst */
958  explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { if (!m_ptr) throw error_already_set(); }
959 
960  operator std::string() const {
961  object temp = *this;
962  if (PyUnicode_Check(m_ptr)) {
963  temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
964  if (!temp)
965  pybind11_fail("Unable to extract string contents! (encoding issue)");
966  }
967  char *buffer;
968  ssize_t length;
969  if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length))
970  pybind11_fail("Unable to extract string contents! (invalid type)");
971  return std::string(buffer, (size_t) length);
972  }
973 
974  template <typename... Args>
975  str format(Args &&...args) const {
976  return attr("format")(std::forward<Args>(args)...);
977  }
978 
979 private:
980  /// Return string representation -- always returns a new reference, even if already a str
981  static PyObject *raw_str(PyObject *op) {
982  PyObject *str_value = PyObject_Str(op);
983 #if PY_MAJOR_VERSION < 3
984  if (!str_value) throw error_already_set();
985  PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
986  Py_XDECREF(str_value); str_value = unicode;
987 #endif
988  return str_value;
989  }
990 };
991 /// @} pytypes
992 
993 inline namespace literals {
994 /** \rst
995  String literal version of `str`
996  \endrst */
997 inline str operator"" _s(const char *s, size_t size) { return {s, size}; }
998 } // namespace literals
999 
1000 /// \addtogroup pytypes
1001 /// @{
1002 class bytes : public object {
1003 public:
1004  PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK)
1005 
1006  // Allow implicit conversion:
1007  bytes(const char *c = "")
1008  : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) {
1009  if (!m_ptr) pybind11_fail("Could not allocate bytes object!");
1010  }
1011 
1012  bytes(const char *c, size_t n)
1013  : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, (ssize_t) n), stolen_t{}) {
1014  if (!m_ptr) pybind11_fail("Could not allocate bytes object!");
1015  }
1016 
1017  // Allow implicit conversion:
1018  bytes(const std::string &s) : bytes(s.data(), s.size()) { }
1019 
1020  explicit bytes(const pybind11::str &s);
1021 
1022  operator std::string() const {
1023  char *buffer;
1024  ssize_t length;
1025  if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length))
1026  pybind11_fail("Unable to extract bytes contents!");
1027  return std::string(buffer, (size_t) length);
1028  }
1029 };
1030 // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1031 // are included in the doxygen group; close here and reopen after as a workaround
1032 /// @} pytypes
1033 
1034 inline bytes::bytes(const pybind11::str &s) {
1035  object temp = s;
1036  if (PyUnicode_Check(s.ptr())) {
1037  temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));
1038  if (!temp)
1039  pybind11_fail("Unable to extract string contents! (encoding issue)");
1040  }
1041  char *buffer;
1042  ssize_t length;
1043  if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length))
1044  pybind11_fail("Unable to extract string contents! (invalid type)");
1045  auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));
1046  if (!obj)
1047  pybind11_fail("Could not allocate bytes object!");
1048  m_ptr = obj.release().ptr();
1049 }
1050 
1051 inline str::str(const bytes& b) {
1052  char *buffer;
1053  ssize_t length;
1054  if (PYBIND11_BYTES_AS_STRING_AND_SIZE(b.ptr(), &buffer, &length))
1055  pybind11_fail("Unable to extract bytes contents!");
1056  auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, (ssize_t) length));
1057  if (!obj)
1058  pybind11_fail("Could not allocate string object!");
1059  m_ptr = obj.release().ptr();
1060 }
1061 
1062 /// \addtogroup pytypes
1063 /// @{
1064 class none : public object {
1065 public:
1066  PYBIND11_OBJECT(none, object, detail::PyNone_Check)
1067  none() : object(Py_None, borrowed_t{}) { }
1068 };
1069 
1070 class ellipsis : public object {
1071 public:
1072  PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check)
1073  ellipsis() : object(Py_Ellipsis, borrowed_t{}) { }
1074 };
1075 
1076 class bool_ : public object {
1077 public:
1078  PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool)
1079  bool_() : object(Py_False, borrowed_t{}) { }
1080  // Allow implicit conversion from and to `bool`:
1081  bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) { }
1082  operator bool() const { return m_ptr && PyLong_AsLong(m_ptr) != 0; }
1083 
1084 private:
1085  /// Return the truth value of an object -- always returns a new reference
1086  static PyObject *raw_bool(PyObject *op) {
1087  const auto value = PyObject_IsTrue(op);
1088  if (value == -1) return nullptr;
1089  return handle(value ? Py_True : Py_False).inc_ref().ptr();
1090  }
1091 };
1092 
1093 PYBIND11_NAMESPACE_BEGIN(detail)
1094 // Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1;
1095 // otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned).
1096 // (The distinction is critically important when casting a returned -1 error value to some other
1097 // unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes).
1098 template <typename Unsigned>
1099 Unsigned as_unsigned(PyObject *o) {
1100  if (sizeof(Unsigned) <= sizeof(unsigned long)
1101 #if PY_VERSION_HEX < 0x03000000
1102  || PyInt_Check(o)
1103 #endif
1104  ) {
1105  unsigned long v = PyLong_AsUnsignedLong(o);
1106  return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1107  }
1108  else {
1109  unsigned long long v = PyLong_AsUnsignedLongLong(o);
1110  return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1111  }
1112 }
1113 PYBIND11_NAMESPACE_END(detail)
1114 
1115 class int_ : public object {
1116 public:
1117  PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long)
1118  int_() : object(PyLong_FromLong(0), stolen_t{}) { }
1119  // Allow implicit conversion from C++ integral types:
1120  template <typename T,
1121  detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1122  int_(T value) {
1123  if (sizeof(T) <= sizeof(long)) {
1124  if (std::is_signed<T>::value)
1125  m_ptr = PyLong_FromLong((long) value);
1126  else
1127  m_ptr = PyLong_FromUnsignedLong((unsigned long) value);
1128  } else {
1129  if (std::is_signed<T>::value)
1130  m_ptr = PyLong_FromLongLong((long long) value);
1131  else
1132  m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value);
1133  }
1134  if (!m_ptr) pybind11_fail("Could not allocate int object!");
1135  }
1136 
1137  template <typename T,
1138  detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1139  operator T() const {
1140  return std::is_unsigned<T>::value
1141  ? detail::as_unsigned<T>(m_ptr)
1142  : sizeof(T) <= sizeof(long)
1143  ? (T) PyLong_AsLong(m_ptr)
1144  : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
1145  }
1146 };
1147 
1148 class float_ : public object {
1149 public:
1150  PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)
1151  // Allow implicit conversion from float/double:
1152  float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1153  if (!m_ptr) pybind11_fail("Could not allocate float object!");
1154  }
1155  float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1156  if (!m_ptr) pybind11_fail("Could not allocate float object!");
1157  }
1158  operator float() const { return (float) PyFloat_AsDouble(m_ptr); }
1159  operator double() const { return (double) PyFloat_AsDouble(m_ptr); }
1160 };
1161 
1162 class weakref : public object {
1163 public:
1164  PYBIND11_OBJECT_DEFAULT(weakref, object, PyWeakref_Check)
1165  explicit weakref(handle obj, handle callback = {})
1166  : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) {
1167  if (!m_ptr) pybind11_fail("Could not allocate weak reference!");
1168  }
1169 };
1170 
1171 class slice : public object {
1172 public:
1173  PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check)
1174  slice(ssize_t start_, ssize_t stop_, ssize_t step_) {
1175  int_ start(start_), stop(stop_), step(step_);
1176  m_ptr = PySlice_New(start.ptr(), stop.ptr(), step.ptr());
1177  if (!m_ptr) pybind11_fail("Could not allocate slice object!");
1178  }
1179  bool compute(size_t length, size_t *start, size_t *stop, size_t *step,
1180  size_t *slicelength) const {
1181  return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1182  (ssize_t) length, (ssize_t *) start,
1183  (ssize_t *) stop, (ssize_t *) step,
1184  (ssize_t *) slicelength) == 0;
1185  }
1186  bool compute(ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step,
1187  ssize_t *slicelength) const {
1188  return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1189  length, start,
1190  stop, step,
1191  slicelength) == 0;
1192  }
1193 };
1194 
1195 class capsule : public object {
1196 public:
1197  PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact)
1198  PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()")
1199  capsule(PyObject *ptr, bool is_borrowed) : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) { }
1200 
1201  explicit capsule(const void *value, const char *name = nullptr, void (*destructor)(PyObject *) = nullptr)
1202  : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) {
1203  if (!m_ptr)
1204  pybind11_fail("Could not allocate capsule object!");
1205  }
1206 
1207  PYBIND11_DEPRECATED("Please pass a destructor that takes a void pointer as input")
1208  capsule(const void *value, void (*destruct)(PyObject *))
1209  : object(PyCapsule_New(const_cast<void*>(value), nullptr, destruct), stolen_t{}) {
1210  if (!m_ptr)
1211  pybind11_fail("Could not allocate capsule object!");
1212  }
1213 
1214  capsule(const void *value, void (*destructor)(void *)) {
1215  m_ptr = PyCapsule_New(const_cast<void *>(value), nullptr, [](PyObject *o) {
1216  auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o));
1217  void *ptr = PyCapsule_GetPointer(o, nullptr);
1218  destructor(ptr);
1219  });
1220 
1221  if (!m_ptr)
1222  pybind11_fail("Could not allocate capsule object!");
1223 
1224  if (PyCapsule_SetContext(m_ptr, (void *) destructor) != 0)
1225  pybind11_fail("Could not set capsule context!");
1226  }
1227 
1228  capsule(void (*destructor)()) {
1229  m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) {
1230  auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, nullptr));
1231  destructor();
1232  });
1233 
1234  if (!m_ptr)
1235  pybind11_fail("Could not allocate capsule object!");
1236  }
1237 
1238  template <typename T> operator T *() const {
1239  return get_pointer<T>();
1240  }
1241 
1242  /// Get the pointer the capsule holds.
1243  template<typename T = void>
1244  T* get_pointer() const {
1245  auto name = this->name();
1246  T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));
1247  if (!result) pybind11_fail("Unable to extract capsule contents!");
1248  return result;
1249  }
1250 
1251  /// Replaces a capsule's pointer *without* calling the destructor on the existing one.
1252  void set_pointer(const void *value) {
1253  if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0)
1254  pybind11_fail("Could not set capsule pointer");
1255  }
1256 
1257  const char *name() const { return PyCapsule_GetName(m_ptr); }
1258 };
1259 
1260 class tuple : public object {
1261 public:
1262  PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple)
1263  explicit tuple(size_t size = 0) : object(PyTuple_New((ssize_t) size), stolen_t{}) {
1264  if (!m_ptr) pybind11_fail("Could not allocate tuple object!");
1265  }
1266  size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
1267  bool empty() const { return size() == 0; }
1268  detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }
1269  detail::item_accessor operator[](handle h) const { return object::operator[](h); }
1270  detail::tuple_iterator begin() const { return {*this, 0}; }
1271  detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }
1272 };
1273 
1274 class dict : public object {
1275 public:
1276  PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)
1277  dict() : object(PyDict_New(), stolen_t{}) {
1278  if (!m_ptr) pybind11_fail("Could not allocate dict object!");
1279  }
1280  template <typename... Args,
1281  typename = detail::enable_if_t<detail::all_of<detail::is_keyword_or_ds<Args>...>::value>,
1282  // MSVC workaround: it can't compile an out-of-line definition, so defer the collector
1283  typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
1284  explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) { }
1285 
1286  size_t size() const { return (size_t) PyDict_Size(m_ptr); }
1287  bool empty() const { return size() == 0; }
1288  detail::dict_iterator begin() const { return {*this, 0}; }
1289  detail::dict_iterator end() const { return {}; }
1290  void clear() const { PyDict_Clear(ptr()); }
1291  template <typename T> bool contains(T &&key) const {
1292  return PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr()) == 1;
1293  }
1294 
1295 private:
1296  /// Call the `dict` Python type -- always returns a new reference
1297  static PyObject *raw_dict(PyObject *op) {
1298  if (PyDict_Check(op))
1299  return handle(op).inc_ref().ptr();
1300  return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
1301  }
1302 };
1303 
1304 class sequence : public object {
1305 public:
1306  PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)
1307  size_t size() const {
1308  ssize_t result = PySequence_Size(m_ptr);
1309  if (result == -1)
1310  throw error_already_set();
1311  return (size_t) result;
1312  }
1313  bool empty() const { return size() == 0; }
1314  detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
1315  detail::item_accessor operator[](handle h) const { return object::operator[](h); }
1316  detail::sequence_iterator begin() const { return {*this, 0}; }
1317  detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; }
1318 };
1319 
1320 class list : public object {
1321 public:
1322  PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
1323  explicit list(size_t size = 0) : object(PyList_New((ssize_t) size), stolen_t{}) {
1324  if (!m_ptr) pybind11_fail("Could not allocate list object!");
1325  }
1326  size_t size() const { return (size_t) PyList_Size(m_ptr); }
1327  bool empty() const { return size() == 0; }
1328  detail::list_accessor operator[](size_t index) const { return {*this, index}; }
1329  detail::item_accessor operator[](handle h) const { return object::operator[](h); }
1330  detail::list_iterator begin() const { return {*this, 0}; }
1331  detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
1332  template <typename T> void append(T &&val) const {
1333  PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
1334  }
1335  template <typename T> void insert(size_t index, T &&val) const {
1336  PyList_Insert(m_ptr, static_cast<ssize_t>(index),
1337  detail::object_or_cast(std::forward<T>(val)).ptr());
1338  }
1339 };
1340 
1341 class args : public tuple { PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) };
1342 class kwargs : public dict { PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check) };
1343 
1344 class set : public object {
1345 public:
1346  PYBIND11_OBJECT_CVT(set, object, PySet_Check, PySet_New)
1347  set() : object(PySet_New(nullptr), stolen_t{}) {
1348  if (!m_ptr) pybind11_fail("Could not allocate set object!");
1349  }
1350  size_t size() const { return (size_t) PySet_Size(m_ptr); }
1351  bool empty() const { return size() == 0; }
1352  template <typename T> bool add(T &&val) const {
1353  return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
1354  }
1355  void clear() const { PySet_Clear(m_ptr); }
1356  template <typename T> bool contains(T &&val) const {
1357  return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1;
1358  }
1359 };
1360 
1361 class function : public object {
1362 public:
1363  PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)
1364  handle cpp_function() const {
1365  handle fun = detail::get_function(m_ptr);
1366  if (fun && PyCFunction_Check(fun.ptr()))
1367  return fun;
1368  return handle();
1369  }
1370  bool is_cpp_function() const { return (bool) cpp_function(); }
1371 };
1372 
1373 class staticmethod : public object {
1374 public:
1375  PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)
1376 };
1377 
1378 class buffer : public object {
1379 public:
1380  PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)
1381 
1382  buffer_info request(bool writable = false) const {
1383  int flags = PyBUF_STRIDES | PyBUF_FORMAT;
1384  if (writable) flags |= PyBUF_WRITABLE;
1385  auto *view = new Py_buffer();
1386  if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
1387  delete view;
1388  throw error_already_set();
1389  }
1390  return buffer_info(view);
1391  }
1392 };
1393 
1394 class memoryview : public object {
1395 public:
1396  PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
1397 
1398  /** \rst
1399  Creates ``memoryview`` from ``buffer_info``.
1400 
1401  ``buffer_info`` must be created from ``buffer::request()``. Otherwise
1402  throws an exception.
1403 
1404  For creating a ``memoryview`` from objects that support buffer protocol,
1405  use ``memoryview(const object& obj)`` instead of this constructor.
1406  \endrst */
1407  explicit memoryview(const buffer_info& info) {
1408  if (!info.view())
1409  pybind11_fail("Prohibited to create memoryview without Py_buffer");
1410  // Note: PyMemoryView_FromBuffer never increments obj reference.
1411  m_ptr = (info.view()->obj) ?
1412  PyMemoryView_FromObject(info.view()->obj) :
1413  PyMemoryView_FromBuffer(info.view());
1414  if (!m_ptr)
1415  pybind11_fail("Unable to create memoryview from buffer descriptor");
1416  }
1417 
1418  /** \rst
1419  Creates ``memoryview`` from static buffer.
1420 
1421  This method is meant for providing a ``memoryview`` for C/C++ buffer not
1422  managed by Python. The caller is responsible for managing the lifetime
1423  of ``ptr`` and ``format``, which MUST outlive the memoryview constructed
1424  here.
1425 
1426  See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
1427 
1428  .. _PyMemoryView_FromBuffer: https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer
1429 
1430  :param ptr: Pointer to the buffer.
1431  :param itemsize: Byte size of an element.
1432  :param format: Pointer to the null-terminated format string. For
1433  homogeneous Buffers, this should be set to
1434  ``format_descriptor<T>::value``.
1435  :param shape: Shape of the tensor (1 entry per dimension).
1436  :param strides: Number of bytes between adjacent entries (for each
1437  per dimension).
1438  :param readonly: Flag to indicate if the underlying storage may be
1439  written to.
1440  \endrst */
1441  static memoryview from_buffer(
1442  void *ptr, ssize_t itemsize, const char *format,
1443  detail::any_container<ssize_t> shape,
1444  detail::any_container<ssize_t> strides, bool readonly = false);
1445 
1446  static memoryview from_buffer(
1447  const void *ptr, ssize_t itemsize, const char *format,
1448  detail::any_container<ssize_t> shape,
1449  detail::any_container<ssize_t> strides) {
1450  return memoryview::from_buffer(
1451  const_cast<void*>(ptr), itemsize, format, shape, strides, true);
1452  }
1453 
1454  template<typename T>
1455  static memoryview from_buffer(
1456  T *ptr, detail::any_container<ssize_t> shape,
1457  detail::any_container<ssize_t> strides, bool readonly = false) {
1458  return memoryview::from_buffer(
1459  reinterpret_cast<void*>(ptr), sizeof(T),
1460  format_descriptor<T>::value, shape, strides, readonly);
1461  }
1462 
1463  template<typename T>
1464  static memoryview from_buffer(
1465  const T *ptr, detail::any_container<ssize_t> shape,
1466  detail::any_container<ssize_t> strides) {
1467  return memoryview::from_buffer(
1468  const_cast<T*>(ptr), shape, strides, true);
1469  }
1470 
1471 #if PY_MAJOR_VERSION >= 3
1472  /** \rst
1473  Creates ``memoryview`` from static memory.
1474 
1475  This method is meant for providing a ``memoryview`` for C/C++ buffer not
1476  managed by Python. The caller is responsible for managing the lifetime
1477  of ``mem``, which MUST outlive the memoryview constructed here.
1478 
1479  This method is not available in Python 2.
1480 
1481  See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
1482 
1483  .. _PyMemoryView_FromMemory: https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory
1484  \endrst */
1485  static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) {
1486  PyObject* ptr = PyMemoryView_FromMemory(
1487  reinterpret_cast<char*>(mem), size,
1488  (readonly) ? PyBUF_READ : PyBUF_WRITE);
1489  if (!ptr)
1490  pybind11_fail("Could not allocate memoryview object!");
1491  return memoryview(object(ptr, stolen_t{}));
1492  }
1493 
1494  static memoryview from_memory(const void *mem, ssize_t size) {
1495  return memoryview::from_memory(const_cast<void*>(mem), size, true);
1496  }
1497 #endif
1498 };
1499 
1500 #ifndef DOXYGEN_SHOULD_SKIP_THIS
1502  void *ptr, ssize_t itemsize, const char* format,
1503  detail::any_container<ssize_t> shape,
1504  detail::any_container<ssize_t> strides, bool readonly) {
1505  size_t ndim = shape->size();
1506  if (ndim != strides->size())
1507  pybind11_fail("memoryview: shape length doesn't match strides length");
1508  ssize_t size = ndim ? 1 : 0;
1509  for (size_t i = 0; i < ndim; ++i)
1510  size *= (*shape)[i];
1511  Py_buffer view;
1512  view.buf = ptr;
1513  view.obj = nullptr;
1514  view.len = size * itemsize;
1515  view.readonly = static_cast<int>(readonly);
1516  view.itemsize = itemsize;
1517  view.format = const_cast<char*>(format);
1518  view.ndim = static_cast<int>(ndim);
1519  view.shape = shape->data();
1520  view.strides = strides->data();
1521  view.suboffsets = nullptr;
1522  view.internal = nullptr;
1523  PyObject* obj = PyMemoryView_FromBuffer(&view);
1524  if (!obj)
1525  throw error_already_set();
1526  return memoryview(object(obj, stolen_t{}));
1527 }
1528 #endif // DOXYGEN_SHOULD_SKIP_THIS
1529 /// @} pytypes
1530 
1531 /// \addtogroup python_builtins
1532 /// @{
1533 
1534 /// Get the length of a Python object.
1535 inline size_t len(handle h) {
1536  ssize_t result = PyObject_Length(h.ptr());
1537  if (result < 0)
1538  throw error_already_set();
1539  return (size_t) result;
1540 }
1541 
1542 /// Get the length hint of a Python object.
1543 /// Returns 0 when this cannot be determined.
1544 inline size_t len_hint(handle h) {
1545 #if PY_VERSION_HEX >= 0x03040000
1546  ssize_t result = PyObject_LengthHint(h.ptr(), 0);
1547 #else
1548  ssize_t result = PyObject_Length(h.ptr());
1549 #endif
1550  if (result < 0) {
1551  // Sometimes a length can't be determined at all (eg generators)
1552  // In which case simply return 0
1553  PyErr_Clear();
1554  return 0;
1555  }
1556  return (size_t) result;
1557 }
1558 
1559 inline str repr(handle h) {
1560  PyObject *str_value = PyObject_Repr(h.ptr());
1561  if (!str_value) throw error_already_set();
1562 #if PY_MAJOR_VERSION < 3
1563  PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
1564  Py_XDECREF(str_value); str_value = unicode;
1565  if (!str_value) throw error_already_set();
1566 #endif
1567  return reinterpret_steal<str>(str_value);
1568 }
1569 
1570 inline iterator iter(handle obj) {
1571  PyObject *result = PyObject_GetIter(obj.ptr());
1572  if (!result) { throw error_already_set(); }
1573  return reinterpret_steal<iterator>(result);
1574 }
1575 /// @} python_builtins
1576 
1577 PYBIND11_NAMESPACE_BEGIN(detail)
1578 template <typename D> iterator object_api<D>::begin() const { return iter(derived()); }
1579 template <typename D> iterator object_api<D>::end() const { return iterator::sentinel(); }
1580 template <typename D> item_accessor object_api<D>::operator[](handle key) const {
1581  return {derived(), reinterpret_borrow<object>(key)};
1582 }
1583 template <typename D> item_accessor object_api<D>::operator[](const char *key) const {
1584  return {derived(), pybind11::str(key)};
1585 }
1586 template <typename D> obj_attr_accessor object_api<D>::attr(handle key) const {
1587  return {derived(), reinterpret_borrow<object>(key)};
1588 }
1589 template <typename D> str_attr_accessor object_api<D>::attr(const char *key) const {
1590  return {derived(), key};
1591 }
1592 template <typename D> args_proxy object_api<D>::operator*() const {
1593  return args_proxy(derived().ptr());
1594 }
1595 template <typename D> template <typename T> bool object_api<D>::contains(T &&item) const {
1596  return attr("__contains__")(std::forward<T>(item)).template cast<bool>();
1597 }
1598 
1599 template <typename D>
1600 pybind11::str object_api<D>::str() const { return pybind11::str(derived()); }
1601 
1602 template <typename D>
1603 str_attr_accessor object_api<D>::doc() const { return attr("__doc__"); }
1604 
1605 template <typename D>
1606 handle object_api<D>::get_type() const { return type::handle_of(derived()); }
1607 
1608 template <typename D>
1609 bool object_api<D>::rich_compare(object_api const &other, int value) const {
1610  int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
1611  if (rv == -1)
1612  throw error_already_set();
1613  return rv == 1;
1614 }
1615 
1616 #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
1617  template <typename D> object object_api<D>::op() const { \
1618  object result = reinterpret_steal<object>(fn(derived().ptr())); \
1619  if (!result.ptr()) \
1620  throw error_already_set(); \
1621  return result; \
1622  }
1623 
1624 #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
1625  template <typename D> \
1626  object object_api<D>::op(object_api const &other) const { \
1627  object result = reinterpret_steal<object>( \
1628  fn(derived().ptr(), other.derived().ptr())); \
1629  if (!result.ptr()) \
1630  throw error_already_set(); \
1631  return result; \
1632  }
1633 
1634 PYBIND11_MATH_OPERATOR_UNARY (operator~, PyNumber_Invert)
1635 PYBIND11_MATH_OPERATOR_UNARY (operator-, PyNumber_Negative)
1636 PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)
1637 PYBIND11_MATH_OPERATOR_BINARY(operator+=, PyNumber_InPlaceAdd)
1638 PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)
1639 PYBIND11_MATH_OPERATOR_BINARY(operator-=, PyNumber_InPlaceSubtract)
1640 PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)
1641 PYBIND11_MATH_OPERATOR_BINARY(operator*=, PyNumber_InPlaceMultiply)
1642 PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)
1643 PYBIND11_MATH_OPERATOR_BINARY(operator/=, PyNumber_InPlaceTrueDivide)
1644 PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)
1645 PYBIND11_MATH_OPERATOR_BINARY(operator|=, PyNumber_InPlaceOr)
1646 PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)
1647 PYBIND11_MATH_OPERATOR_BINARY(operator&=, PyNumber_InPlaceAnd)
1648 PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)
1649 PYBIND11_MATH_OPERATOR_BINARY(operator^=, PyNumber_InPlaceXor)
1650 PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)
1651 PYBIND11_MATH_OPERATOR_BINARY(operator<<=, PyNumber_InPlaceLshift)
1652 PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)
1653 PYBIND11_MATH_OPERATOR_BINARY(operator>>=, PyNumber_InPlaceRshift)
1654 
1655 #undef PYBIND11_MATH_OPERATOR_UNARY
1656 #undef PYBIND11_MATH_OPERATOR_BINARY
1657 
1658 PYBIND11_NAMESPACE_END(detail)
1659 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
Quick proxy class needed to implement operator-&gt; for iterators which can&#39;t return pointers.
Definition: pytypes.h:660
iterator end() const
Return a sentinel which ends iteration.
Definition: pytypes.h:1579
object(object &&other) noexcept
Move constructor; steals the object from other and preserves its reference count. ...
Definition: pytypes.h:240
bool contains(T &&item) const
Check if the given item is contained within this object, i.e. item in obj.
Definition: pytypes.h:1595
friend T reinterpret_borrow(handle)
Definition: pytypes.h:304
static PyObject * raw_str(PyObject *op)
Return string representation – always returns a new reference, even if already a str...
Definition: pytypes.h:981
Definition: pytypes.h:1341
Annotation for documentation.
Definition: attr.h:33
const handle & dec_ref() const &
Definition: pytypes.h:199
static PyObject * raw_bool(PyObject *op)
Return the truth value of an object – always returns a new reference.
Definition: pytypes.h:1086
handle(PyObject *ptr)
Creates a handle from the given raw Python object pointer.
Definition: pytypes.h:181
friend T reinterpret_steal(handle)
Definition: pytypes.h:314
static type of(handle h)
Return a type object from a handle or an object.
Definition: pytypes.h:912
handle release()
Definition: pytypes.h:249
STL iterator template used for tuple, list, sequence and dict.
Definition: pytypes.h:620
bool isinstance(handle obj)
Definition: pytypes.h:384
object operator()(Args &&...args) const
~object()
Destructor; automatically calls handle::dec_ref()
Definition: pytypes.h:242
Definition: pytypes.h:1064
object(const object &o)
Copy constructor; always increases the reference count.
Definition: pytypes.h:238
str_attr_accessor doc() const
Get or set the object&#39;s docstring, i.e. obj.__doc__.
Definition: pytypes.h:1603
bool equal(object_api const &other) const
Equivalent to obj == other in Python.
Definition: pytypes.h:119
void restore()
Definition: pytypes.h:340
Definition: pytypes.h:935
static type of()
Definition: pytypes.h:925
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:184
const handle & inc_ref() const &
Definition: pytypes.h:192
args_proxy operator*() const
Definition: pytypes.h:1592
Python&#39;s dictionary protocol permits this to be a forward iterator.
Definition: pytypes.h:711
Full read and write access using the sequence protocol: see detail::sequence_accessor ...
Definition: pytypes.h:689
Definition: pytypes.h:1320
Tag and check to identify a class which implements the Python object API.
Definition: pytypes.h:47
Definition: pytypes.h:1115
bool is(object_api const &other) const
Equivalent to obj is other in Python.
Definition: pytypes.h:115
int ref_count() const
Return the object&#39;s current reference count.
Definition: pytypes.h:154
obj_attr_accessor attr(handle key) const
Definition: pytypes.h:1586
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
Definition: pybind11.h:62
size_t len_hint(handle h)
Definition: pytypes.h:1544
bool is_none() const
Equivalent to obj is None in Python.
Definition: pytypes.h:117
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)
str(handle h)
Definition: pytypes.h:958
Definition: pytypes.h:1274
void discard_as_unraisable(object err_context)
Definition: pytypes.h:348
static iterator sentinel()
Definition: pytypes.h:887
Annotation for function names.
Definition: attr.h:36
item_accessor operator[](handle key) const
Definition: pytypes.h:1580
Information record describing a Python buffer object.
Definition: buffer_info.h:40
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:1535
static PyObject * raw_dict(PyObject *op)
Call the dict Python type – always returns a new reference.
Definition: pytypes.h:1297
static handle handle_of()
bool matches(handle exc) const
Definition: pytypes.h:363
iterator begin() const
Definition: pytypes.h:1578
Definition: pytypes.h:1344
handle()=default
The default constructor creates a handle with a nullptr-valued pointer.
Definition: pytypes.h:904
Lightweight iterator policy using just a simple pointer: see PySequence_Fast_ITEMS ...
Definition: pytypes.h:668