• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
39 using obj_attr_accessor = accessor<accessor_policies::obj_attr>;
40 using str_attr_accessor = accessor<accessor_policies::str_attr>;
41 using item_accessor = accessor<accessor_policies::generic_item>;
42 using sequence_accessor = accessor<accessor_policies::sequence_item>;
43 using list_accessor = accessor<accessor_policies::list_item>;
44 using tuple_accessor = accessor<accessor_policies::tuple_item>;
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 {
derived()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.
is(object_api const & other)115     bool is(object_api const& other) const { return derived().ptr() == other.derived().ptr(); }
116     /// Equivalent to ``obj is None`` in Python.
is_none()117     bool is_none() const { return derived().ptr() == Py_None; }
118     /// Equivalent to obj == other in Python
equal(object_api const & other)119     bool equal(object_api const &other) const      { return rich_compare(other, Py_EQ); }
not_equal(object_api const & other)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
ref_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 
PYBIND11_NAMESPACE_END(detail)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>()")
object(handle h,bool is_borrowed)236     object(handle h, bool is_borrowed) : handle(h) { if (is_borrowed) inc_ref(); }
237     /// Copy constructor; always increases the reference count
object(const object & o)238     object(const object &o) : handle(o) { inc_ref(); }
239     /// Move constructor; steals the object from ``other`` and preserves its reference count
object(object && other)240     object(object &&other) noexcept { m_ptr = other.m_ptr; other.m_ptr = nullptr; }
241     /// Destructor; automatically calls `handle::dec_ref()`
~object()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 */
release()249     handle release() {
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
object(handle h,borrowed_t)287     object(handle h, borrowed_t) : handle(h) { inc_ref(); }
object(handle h,stolen_t)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 */
reinterpret_borrow(handle h)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 */
reinterpret_steal(handle h)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();
PYBIND11_NAMESPACE_END(detail)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>
isinstance(handle obj)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>
isinstance(handle obj)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``.
isinstance(handle obj,handle 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 /// @{
hasattr(handle obj,handle name)403 inline bool hasattr(handle obj, handle name) {
404     return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1;
405 }
406 
hasattr(handle obj,const char * name)407 inline bool hasattr(handle obj, const char *name) {
408     return PyObject_HasAttrString(obj.ptr(), name) == 1;
409 }
410 
delattr(handle obj,handle name)411 inline void delattr(handle obj, handle name) {
412     if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) { throw error_already_set(); }
413 }
414 
delattr(handle obj,const char * name)415 inline void delattr(handle obj, const char *name) {
416     if (PyObject_DelAttrString(obj.ptr(), name) != 0) { throw error_already_set(); }
417 }
418 
getattr(handle obj,handle name)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 
getattr(handle obj,const char * name)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 
getattr(handle obj,handle name,handle default_)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 
getattr(handle obj,const char * name,handle default_)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 
setattr(handle obj,handle name,handle value)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 
setattr(handle obj,const char * name,handle value)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 
hash(handle obj)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 
PYBIND11_NAMESPACE_BEGIN(detail)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
object_or_cast(PyObject * ptr)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:
accessor(handle obj,key_type key)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 
object()523     operator object() const { return get_cache(); }
ptr()524     PyObject *ptr() const { return get_cache().ptr(); }
cast()525     template <typename T> T cast() const { return get_cache().template cast<T>(); }
526 
527 private:
get_cache()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;
getobj_attr542     static object get(handle obj, handle key) { return getattr(obj, key); }
setobj_attr543     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 *;
getstr_attr548     static object get(handle obj, const char *key) { return getattr(obj, key); }
setstr_attr549     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 
getgeneric_item555     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 
setgeneric_item561     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 
566 struct sequence_item {
567     using key_type = size_t;
568 
getsequence_item569     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 
setsequence_item575     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 
getlist_item586     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 
setlist_item592     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 
gettuple_item603     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 
settuple_item609     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 };
PYBIND11_NAMESPACE_END(accessor_policies)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 
arrow_proxyarrow_proxy663     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``
668 class sequence_fast_readonly {
669 protected:
670     using iterator_category = std::random_access_iterator_tag;
671     using value_type = handle;
672     using reference = const handle;
673     using pointer = arrow_proxy<const handle>;
674 
sequence_fast_readonly(handle obj,ssize_t n)675     sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) { }
676 
dereference()677     reference dereference() const { return *ptr; }
increment()678     void increment() { ++ptr; }
decrement()679     void decrement() { --ptr; }
advance(ssize_t n)680     void advance(ssize_t n) { ptr += n; }
equal(const sequence_fast_readonly & b)681     bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; }
distance_to(const sequence_fast_readonly & b)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``
689 class sequence_slow_readwrite {
690 protected:
691     using iterator_category = std::random_access_iterator_tag;
692     using value_type = object;
693     using reference = sequence_accessor;
694     using pointer = arrow_proxy<const sequence_accessor>;
695 
sequence_slow_readwrite(handle obj,ssize_t index)696     sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) { }
697 
dereference()698     reference dereference() const { return {obj, static_cast<size_t>(index)}; }
increment()699     void increment() { ++index; }
decrement()700     void decrement() { --index; }
advance(ssize_t n)701     void advance(ssize_t n) { index += n; }
equal(const sequence_slow_readwrite & b)702     bool equal(const sequence_slow_readwrite &b) const { return index == b.index; }
distance_to(const sequence_slow_readwrite & b)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
711 class dict_readonly {
712 protected:
713     using iterator_category = std::forward_iterator_tag;
714     using value_type = std::pair<handle, handle>;
715     using reference = const value_type;
716     using pointer = arrow_proxy<const value_type>;
717 
718     dict_readonly() = default;
dict_readonly(handle obj,ssize_t pos)719     dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }
720 
dereference()721     reference dereference() const { return {key, value}; }
increment()722     void increment() { if (!PyDict_Next(obj.ptr(), &pos, &key, &value)) { pos = -1; } }
equal(const dict_readonly & b)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)
733 using tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
734 using list_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
735 #else
736 using tuple_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
737 using list_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
738 #endif
739 
740 using sequence_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
741 using dict_iterator = generic_iterator<iterator_policies::dict_readonly>;
742 
PyIterable_Check(PyObject * obj)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 
PyNone_Check(PyObject * o)754 inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
PyEllipsis_Check(PyObject * o)755 inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }
756 
PyUnicode_Check_Permissive(PyObject * o)757 inline bool PyUnicode_Check_Permissive(PyObject *o) { return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); }
758 
PyStaticMethod_Check(PyObject * o)759 inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; }
760 
761 class kwargs_proxy : public handle {
762 public:
kwargs_proxy(handle h)763     explicit kwargs_proxy(handle h) : handle(h) { }
764 };
765 
766 class args_proxy : public handle {
767 public:
args_proxy(handle h)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 >;
779 template <typename T> using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>;
780 
781 // Call argument collector forward declarations
782 template <return_value_policy policy = return_value_policy::automatic_reference>
783 class simple_collector;
784 template <return_value_policy policy = return_value_policy::automatic_reference>
785 class unpacking_collector;
786 
PYBIND11_NAMESPACE_END(detail)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_ptr) \
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 (m_ptr && !check_(m_ptr)) throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); } \
825     Name(object &&o) : Parent(std::move(o)) \
826     { if (m_ptr && !check_(m_ptr)) throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); }
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:
PYBIND11_OBJECT(type,object,PyType_Check)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
of(handle h)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>
of()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:
PYBIND11_OBJECT_CVT(str,object,detail::PyUnicode_Check_Permissive,raw_str)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 = "")
object(PyUnicode_FromString (c),stolen_t{})946         : object(PyUnicode_FromString(c), stolen_t{}) {
947         if (!m_ptr) pybind11_fail("Could not allocate string object!");
948     }
949 
str(const std::string & s)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 */
str(handle h)958     explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { if (!m_ptr) throw error_already_set(); }
959 
string()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>
format(Args &&...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
raw_str(PyObject * op)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:
PYBIND11_OBJECT(bytes,object,PYBIND11_BYTES_CHECK)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 
bytes(const char * c,size_t n)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:
bytes(const std::string & s)1018     bytes(const std::string &s) : bytes(s.data(), s.size()) { }
1019 
1020     explicit bytes(const pybind11::str &s);
1021 
string()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 
bytes(const pybind11::str & s)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 
str(const bytes & b)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:
PYBIND11_OBJECT(none,object,detail::PyNone_Check)1066     PYBIND11_OBJECT(none, object, detail::PyNone_Check)
1067     none() : object(Py_None, borrowed_t{}) { }
1068 };
1069 
1070 class ellipsis : public object {
1071 public:
PYBIND11_OBJECT(ellipsis,object,detail::PyEllipsis_Check)1072     PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check)
1073     ellipsis() : object(Py_Ellipsis, borrowed_t{}) { }
1074 };
1075 
1076 class bool_ : public object {
1077 public:
PYBIND11_OBJECT_CVT(bool_,object,PyBool_Check,raw_bool)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`:
bool_(bool value)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
raw_bool(PyObject * op)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 
PYBIND11_NAMESPACE_BEGIN(detail)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 }
PYBIND11_NAMESPACE_END(detail)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:
PYBIND11_OBJECT_CVT(float_,object,PyFloat_Check,PyNumber_Float)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:
PYBIND11_OBJECT_DEFAULT(weakref,object,PyWeakref_Check)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:
PYBIND11_OBJECT_DEFAULT(slice,object,PySlice_Check)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     }
compute(size_t length,size_t * start,size_t * stop,size_t * step,size_t * slicelength)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     }
compute(ssize_t length,ssize_t * start,ssize_t * stop,ssize_t * step,ssize_t * slicelength)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:
PYBIND11_OBJECT_DEFAULT(capsule,object,PyCapsule_CheckExact)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)
object(PyCapsule_New (const_cast<void * > (value),name,destructor),stolen_t{})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")
capsule(const void * value,void (* destruct)(PyObject *))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 
capsule(const void * value,void (* destructor)(void *))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 
capsule(void (* destructor)())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>
get_pointer()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.
set_pointer(const void * value)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 
name()1257     const char *name() const { return PyCapsule_GetName(m_ptr); }
1258 };
1259 
1260 class tuple : public object {
1261 public:
PYBIND11_OBJECT_CVT(tuple,object,PyTuple_Check,PySequence_Tuple)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     }
size()1266     size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
empty()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); }
begin()1270     detail::tuple_iterator begin() const { return {*this, 0}; }
end()1271     detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }
1272 };
1273 
1274 // We need to put this into a separate function because the Intel compiler
1275 // fails to compile enable_if_t<all_of<is_keyword_or_ds<Args>...>::value> part below
1276 // (tested with ICC 2021.1 Beta 20200827).
1277 template <typename... Args>
args_are_all_keyword_or_ds()1278 constexpr bool args_are_all_keyword_or_ds()
1279 {
1280   return detail::all_of<detail::is_keyword_or_ds<Args>...>::value;
1281 }
1282 
1283 class dict : public object {
1284 public:
PYBIND11_OBJECT_CVT(dict,object,PyDict_Check,raw_dict)1285     PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)
1286     dict() : object(PyDict_New(), stolen_t{}) {
1287         if (!m_ptr) pybind11_fail("Could not allocate dict object!");
1288     }
1289     template <typename... Args,
1290               typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>,
1291               // MSVC workaround: it can't compile an out-of-line definition, so defer the collector
1292               typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
dict(Args &&...args)1293     explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) { }
1294 
size()1295     size_t size() const { return (size_t) PyDict_Size(m_ptr); }
empty()1296     bool empty() const { return size() == 0; }
begin()1297     detail::dict_iterator begin() const { return {*this, 0}; }
end()1298     detail::dict_iterator end() const { return {}; }
clear()1299     void clear() const { PyDict_Clear(ptr()); }
contains(T && key)1300     template <typename T> bool contains(T &&key) const {
1301         return PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr()) == 1;
1302     }
1303 
1304 private:
1305     /// Call the `dict` Python type -- always returns a new reference
raw_dict(PyObject * op)1306     static PyObject *raw_dict(PyObject *op) {
1307         if (PyDict_Check(op))
1308             return handle(op).inc_ref().ptr();
1309         return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
1310     }
1311 };
1312 
1313 class sequence : public object {
1314 public:
PYBIND11_OBJECT_DEFAULT(sequence,object,PySequence_Check)1315     PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)
1316     size_t size() const {
1317         ssize_t result = PySequence_Size(m_ptr);
1318         if (result == -1)
1319             throw error_already_set();
1320         return (size_t) result;
1321     }
empty()1322     bool empty() const { return size() == 0; }
1323     detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
1324     detail::item_accessor operator[](handle h) const { return object::operator[](h); }
begin()1325     detail::sequence_iterator begin() const { return {*this, 0}; }
end()1326     detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; }
1327 };
1328 
1329 class list : public object {
1330 public:
PYBIND11_OBJECT_CVT(list,object,PyList_Check,PySequence_List)1331     PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
1332     explicit list(size_t size = 0) : object(PyList_New((ssize_t) size), stolen_t{}) {
1333         if (!m_ptr) pybind11_fail("Could not allocate list object!");
1334     }
size()1335     size_t size() const { return (size_t) PyList_Size(m_ptr); }
empty()1336     bool empty() const { return size() == 0; }
1337     detail::list_accessor operator[](size_t index) const { return {*this, index}; }
1338     detail::item_accessor operator[](handle h) const { return object::operator[](h); }
begin()1339     detail::list_iterator begin() const { return {*this, 0}; }
end()1340     detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
append(T && val)1341     template <typename T> void append(T &&val) const {
1342         PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
1343     }
insert(size_t index,T && val)1344     template <typename T> void insert(size_t index, T &&val) const {
1345         PyList_Insert(m_ptr, static_cast<ssize_t>(index),
1346             detail::object_or_cast(std::forward<T>(val)).ptr());
1347     }
1348 };
1349 
1350 class args : public tuple { PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) };
1351 class kwargs : public dict { PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check)  };
1352 
1353 class set : public object {
1354 public:
PYBIND11_OBJECT_CVT(set,object,PySet_Check,PySet_New)1355     PYBIND11_OBJECT_CVT(set, object, PySet_Check, PySet_New)
1356     set() : object(PySet_New(nullptr), stolen_t{}) {
1357         if (!m_ptr) pybind11_fail("Could not allocate set object!");
1358     }
size()1359     size_t size() const { return (size_t) PySet_Size(m_ptr); }
empty()1360     bool empty() const { return size() == 0; }
add(T && val)1361     template <typename T> bool add(T &&val) const {
1362         return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
1363     }
clear()1364     void clear() const { PySet_Clear(m_ptr); }
contains(T && val)1365     template <typename T> bool contains(T &&val) const {
1366         return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1;
1367     }
1368 };
1369 
1370 class function : public object {
1371 public:
PYBIND11_OBJECT_DEFAULT(function,object,PyCallable_Check)1372     PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)
1373     handle cpp_function() const {
1374         handle fun = detail::get_function(m_ptr);
1375         if (fun && PyCFunction_Check(fun.ptr()))
1376             return fun;
1377         return handle();
1378     }
is_cpp_function()1379     bool is_cpp_function() const { return (bool) cpp_function(); }
1380 };
1381 
1382 class staticmethod : public object {
1383 public:
1384     PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)
1385 };
1386 
1387 class buffer : public object {
1388 public:
PYBIND11_OBJECT_DEFAULT(buffer,object,PyObject_CheckBuffer)1389     PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)
1390 
1391     buffer_info request(bool writable = false) const {
1392         int flags = PyBUF_STRIDES | PyBUF_FORMAT;
1393         if (writable) flags |= PyBUF_WRITABLE;
1394         auto *view = new Py_buffer();
1395         if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
1396             delete view;
1397             throw error_already_set();
1398         }
1399         return buffer_info(view);
1400     }
1401 };
1402 
1403 class memoryview : public object {
1404 public:
PYBIND11_OBJECT_CVT(memoryview,object,PyMemoryView_Check,PyMemoryView_FromObject)1405     PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
1406 
1407     /** \rst
1408         Creates ``memoryview`` from ``buffer_info``.
1409 
1410         ``buffer_info`` must be created from ``buffer::request()``. Otherwise
1411         throws an exception.
1412 
1413         For creating a ``memoryview`` from objects that support buffer protocol,
1414         use ``memoryview(const object& obj)`` instead of this constructor.
1415      \endrst */
1416     explicit memoryview(const buffer_info& info) {
1417         if (!info.view())
1418             pybind11_fail("Prohibited to create memoryview without Py_buffer");
1419         // Note: PyMemoryView_FromBuffer never increments obj reference.
1420         m_ptr = (info.view()->obj) ?
1421             PyMemoryView_FromObject(info.view()->obj) :
1422             PyMemoryView_FromBuffer(info.view());
1423         if (!m_ptr)
1424             pybind11_fail("Unable to create memoryview from buffer descriptor");
1425     }
1426 
1427     /** \rst
1428         Creates ``memoryview`` from static buffer.
1429 
1430         This method is meant for providing a ``memoryview`` for C/C++ buffer not
1431         managed by Python. The caller is responsible for managing the lifetime
1432         of ``ptr`` and ``format``, which MUST outlive the memoryview constructed
1433         here.
1434 
1435         See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
1436 
1437         .. _PyMemoryView_FromBuffer: https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer
1438 
1439         :param ptr: Pointer to the buffer.
1440         :param itemsize: Byte size of an element.
1441         :param format: Pointer to the null-terminated format string. For
1442             homogeneous Buffers, this should be set to
1443             ``format_descriptor<T>::value``.
1444         :param shape: Shape of the tensor (1 entry per dimension).
1445         :param strides: Number of bytes between adjacent entries (for each
1446             per dimension).
1447         :param readonly: Flag to indicate if the underlying storage may be
1448             written to.
1449      \endrst */
1450     static memoryview from_buffer(
1451         void *ptr, ssize_t itemsize, const char *format,
1452         detail::any_container<ssize_t> shape,
1453         detail::any_container<ssize_t> strides, bool readonly = false);
1454 
from_buffer(const void * ptr,ssize_t itemsize,const char * format,detail::any_container<ssize_t> shape,detail::any_container<ssize_t> strides)1455     static memoryview from_buffer(
1456         const void *ptr, ssize_t itemsize, const char *format,
1457         detail::any_container<ssize_t> shape,
1458         detail::any_container<ssize_t> strides) {
1459         return memoryview::from_buffer(
1460             const_cast<void*>(ptr), itemsize, format, shape, strides, true);
1461     }
1462 
1463     template<typename T>
1464     static memoryview from_buffer(
1465         T *ptr, detail::any_container<ssize_t> shape,
1466         detail::any_container<ssize_t> strides, bool readonly = false) {
1467         return memoryview::from_buffer(
1468             reinterpret_cast<void*>(ptr), sizeof(T),
1469             format_descriptor<T>::value, shape, strides, readonly);
1470     }
1471 
1472     template<typename T>
from_buffer(const T * ptr,detail::any_container<ssize_t> shape,detail::any_container<ssize_t> strides)1473     static memoryview from_buffer(
1474         const T *ptr, detail::any_container<ssize_t> shape,
1475         detail::any_container<ssize_t> strides) {
1476         return memoryview::from_buffer(
1477             const_cast<T*>(ptr), shape, strides, true);
1478     }
1479 
1480 #if PY_MAJOR_VERSION >= 3
1481     /** \rst
1482         Creates ``memoryview`` from static memory.
1483 
1484         This method is meant for providing a ``memoryview`` for C/C++ buffer not
1485         managed by Python. The caller is responsible for managing the lifetime
1486         of ``mem``, which MUST outlive the memoryview constructed here.
1487 
1488         This method is not available in Python 2.
1489 
1490         See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
1491 
1492         .. _PyMemoryView_FromMemory: https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory
1493      \endrst */
1494     static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) {
1495         PyObject* ptr = PyMemoryView_FromMemory(
1496             reinterpret_cast<char*>(mem), size,
1497             (readonly) ? PyBUF_READ : PyBUF_WRITE);
1498         if (!ptr)
1499             pybind11_fail("Could not allocate memoryview object!");
1500         return memoryview(object(ptr, stolen_t{}));
1501     }
1502 
from_memory(const void * mem,ssize_t size)1503     static memoryview from_memory(const void *mem, ssize_t size) {
1504         return memoryview::from_memory(const_cast<void*>(mem), size, true);
1505     }
1506 #endif
1507 };
1508 
1509 #ifndef DOXYGEN_SHOULD_SKIP_THIS
from_buffer(void * ptr,ssize_t itemsize,const char * format,detail::any_container<ssize_t> shape,detail::any_container<ssize_t> strides,bool readonly)1510 inline memoryview memoryview::from_buffer(
1511     void *ptr, ssize_t itemsize, const char* format,
1512     detail::any_container<ssize_t> shape,
1513     detail::any_container<ssize_t> strides, bool readonly) {
1514     size_t ndim = shape->size();
1515     if (ndim != strides->size())
1516         pybind11_fail("memoryview: shape length doesn't match strides length");
1517     ssize_t size = ndim ? 1 : 0;
1518     for (size_t i = 0; i < ndim; ++i)
1519         size *= (*shape)[i];
1520     Py_buffer view;
1521     view.buf = ptr;
1522     view.obj = nullptr;
1523     view.len = size * itemsize;
1524     view.readonly = static_cast<int>(readonly);
1525     view.itemsize = itemsize;
1526     view.format = const_cast<char*>(format);
1527     view.ndim = static_cast<int>(ndim);
1528     view.shape = shape->data();
1529     view.strides = strides->data();
1530     view.suboffsets = nullptr;
1531     view.internal = nullptr;
1532     PyObject* obj = PyMemoryView_FromBuffer(&view);
1533     if (!obj)
1534         throw error_already_set();
1535     return memoryview(object(obj, stolen_t{}));
1536 }
1537 #endif  // DOXYGEN_SHOULD_SKIP_THIS
1538 /// @} pytypes
1539 
1540 /// \addtogroup python_builtins
1541 /// @{
1542 
1543 /// Get the length of a Python object.
len(handle h)1544 inline size_t len(handle h) {
1545     ssize_t result = PyObject_Length(h.ptr());
1546     if (result < 0)
1547         throw error_already_set();
1548     return (size_t) result;
1549 }
1550 
1551 /// Get the length hint of a Python object.
1552 /// Returns 0 when this cannot be determined.
len_hint(handle h)1553 inline size_t len_hint(handle h) {
1554 #if PY_VERSION_HEX >= 0x03040000
1555     ssize_t result = PyObject_LengthHint(h.ptr(), 0);
1556 #else
1557     ssize_t result = PyObject_Length(h.ptr());
1558 #endif
1559     if (result < 0) {
1560         // Sometimes a length can't be determined at all (eg generators)
1561         // In which case simply return 0
1562         PyErr_Clear();
1563         return 0;
1564     }
1565     return (size_t) result;
1566 }
1567 
repr(handle h)1568 inline str repr(handle h) {
1569     PyObject *str_value = PyObject_Repr(h.ptr());
1570     if (!str_value) throw error_already_set();
1571 #if PY_MAJOR_VERSION < 3
1572     PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
1573     Py_XDECREF(str_value); str_value = unicode;
1574     if (!str_value) throw error_already_set();
1575 #endif
1576     return reinterpret_steal<str>(str_value);
1577 }
1578 
iter(handle obj)1579 inline iterator iter(handle obj) {
1580     PyObject *result = PyObject_GetIter(obj.ptr());
1581     if (!result) { throw error_already_set(); }
1582     return reinterpret_steal<iterator>(result);
1583 }
1584 /// @} python_builtins
1585 
PYBIND11_NAMESPACE_BEGIN(detail)1586 PYBIND11_NAMESPACE_BEGIN(detail)
1587 template <typename D> iterator object_api<D>::begin() const { return iter(derived()); }
end()1588 template <typename D> iterator object_api<D>::end() const { return iterator::sentinel(); }
1589 template <typename D> item_accessor object_api<D>::operator[](handle key) const {
1590     return {derived(), reinterpret_borrow<object>(key)};
1591 }
1592 template <typename D> item_accessor object_api<D>::operator[](const char *key) const {
1593     return {derived(), pybind11::str(key)};
1594 }
attr(handle key)1595 template <typename D> obj_attr_accessor object_api<D>::attr(handle key) const {
1596     return {derived(), reinterpret_borrow<object>(key)};
1597 }
attr(const char * key)1598 template <typename D> str_attr_accessor object_api<D>::attr(const char *key) const {
1599     return {derived(), key};
1600 }
1601 template <typename D> args_proxy object_api<D>::operator*() const {
1602     return args_proxy(derived().ptr());
1603 }
contains(T && item)1604 template <typename D> template <typename T> bool object_api<D>::contains(T &&item) const {
1605     return attr("__contains__")(std::forward<T>(item)).template cast<bool>();
1606 }
1607 
1608 template <typename D>
str()1609 pybind11::str object_api<D>::str() const { return pybind11::str(derived()); }
1610 
1611 template <typename D>
doc()1612 str_attr_accessor object_api<D>::doc() const { return attr("__doc__"); }
1613 
1614 template <typename D>
get_type()1615 handle object_api<D>::get_type() const { return type::handle_of(derived()); }
1616 
1617 template <typename D>
rich_compare(object_api const & other,int value)1618 bool object_api<D>::rich_compare(object_api const &other, int value) const {
1619     int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
1620     if (rv == -1)
1621         throw error_already_set();
1622     return rv == 1;
1623 }
1624 
1625 #define PYBIND11_MATH_OPERATOR_UNARY(op, fn)                                   \
1626     template <typename D> object object_api<D>::op() const {                   \
1627         object result = reinterpret_steal<object>(fn(derived().ptr()));        \
1628         if (!result.ptr())                                                     \
1629             throw error_already_set();                                         \
1630         return result;                                                         \
1631     }
1632 
1633 #define PYBIND11_MATH_OPERATOR_BINARY(op, fn)                                  \
1634     template <typename D>                                                      \
1635     object object_api<D>::op(object_api const &other) const {                  \
1636         object result = reinterpret_steal<object>(                             \
1637             fn(derived().ptr(), other.derived().ptr()));                       \
1638         if (!result.ptr())                                                     \
1639             throw error_already_set();                                         \
1640         return result;                                                         \
1641     }
1642 
1643 PYBIND11_MATH_OPERATOR_UNARY (operator~,   PyNumber_Invert)
1644 PYBIND11_MATH_OPERATOR_UNARY (operator-,   PyNumber_Negative)
1645 PYBIND11_MATH_OPERATOR_BINARY(operator+,   PyNumber_Add)
1646 PYBIND11_MATH_OPERATOR_BINARY(operator+=,  PyNumber_InPlaceAdd)
1647 PYBIND11_MATH_OPERATOR_BINARY(operator-,   PyNumber_Subtract)
1648 PYBIND11_MATH_OPERATOR_BINARY(operator-=,  PyNumber_InPlaceSubtract)
1649 PYBIND11_MATH_OPERATOR_BINARY(operator*,   PyNumber_Multiply)
1650 PYBIND11_MATH_OPERATOR_BINARY(operator*=,  PyNumber_InPlaceMultiply)
1651 PYBIND11_MATH_OPERATOR_BINARY(operator/,   PyNumber_TrueDivide)
1652 PYBIND11_MATH_OPERATOR_BINARY(operator/=,  PyNumber_InPlaceTrueDivide)
1653 PYBIND11_MATH_OPERATOR_BINARY(operator|,   PyNumber_Or)
1654 PYBIND11_MATH_OPERATOR_BINARY(operator|=,  PyNumber_InPlaceOr)
1655 PYBIND11_MATH_OPERATOR_BINARY(operator&,   PyNumber_And)
1656 PYBIND11_MATH_OPERATOR_BINARY(operator&=,  PyNumber_InPlaceAnd)
1657 PYBIND11_MATH_OPERATOR_BINARY(operator^,   PyNumber_Xor)
1658 PYBIND11_MATH_OPERATOR_BINARY(operator^=,  PyNumber_InPlaceXor)
1659 PYBIND11_MATH_OPERATOR_BINARY(operator<<,  PyNumber_Lshift)
1660 PYBIND11_MATH_OPERATOR_BINARY(operator<<=, PyNumber_InPlaceLshift)
1661 PYBIND11_MATH_OPERATOR_BINARY(operator>>,  PyNumber_Rshift)
1662 PYBIND11_MATH_OPERATOR_BINARY(operator>>=, PyNumber_InPlaceRshift)
1663 
1664 #undef PYBIND11_MATH_OPERATOR_UNARY
1665 #undef PYBIND11_MATH_OPERATOR_BINARY
1666 
1667 PYBIND11_NAMESPACE_END(detail)
1668 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
1669