pytypes.h revision 12037:d28054ac6ec9
1/* 2 pybind11/typeid.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 "common.h" 13#include <utility> 14#include <type_traits> 15 16NAMESPACE_BEGIN(pybind11) 17 18/* A few forward declarations */ 19class handle; class object; 20class str; class iterator; 21struct arg; struct arg_v; 22 23NAMESPACE_BEGIN(detail) 24class args_proxy; 25inline bool isinstance_generic(handle obj, const std::type_info &tp); 26 27// Accessor forward declarations 28template <typename Policy> class accessor; 29namespace accessor_policies { 30 struct obj_attr; 31 struct str_attr; 32 struct generic_item; 33 struct sequence_item; 34 struct list_item; 35 struct tuple_item; 36} 37using obj_attr_accessor = accessor<accessor_policies::obj_attr>; 38using str_attr_accessor = accessor<accessor_policies::str_attr>; 39using item_accessor = accessor<accessor_policies::generic_item>; 40using sequence_accessor = accessor<accessor_policies::sequence_item>; 41using list_accessor = accessor<accessor_policies::list_item>; 42using tuple_accessor = accessor<accessor_policies::tuple_item>; 43 44/// Tag and check to identify a class which implements the Python object API 45class pyobject_tag { }; 46template <typename T> using is_pyobject = std::is_base_of<pyobject_tag, typename std::remove_reference<T>::type>; 47 48/** \rst 49 A mixin class which adds common functions to `handle`, `object` and various accessors. 50 The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``. 51\endrst */ 52template <typename Derived> 53class object_api : public pyobject_tag { 54 const Derived &derived() const { return static_cast<const Derived &>(*this); } 55 56public: 57 /** \rst 58 Return an iterator equivalent to calling ``iter()`` in Python. The object 59 must be a collection which supports the iteration protocol. 60 \endrst */ 61 iterator begin() const; 62 /// Return a sentinel which ends iteration. 63 iterator end() const; 64 65 /** \rst 66 Return an internal functor to invoke the object's sequence protocol. Casting 67 the returned ``detail::item_accessor`` instance to a `handle` or `object` 68 subclass causes a corresponding call to ``__getitem__``. Assigning a `handle` 69 or `object` subclass causes a call to ``__setitem__``. 70 \endrst */ 71 item_accessor operator[](handle key) const; 72 /// See above (the only difference is that they key is provided as a string literal) 73 item_accessor operator[](const char *key) const; 74 75 /** \rst 76 Return an internal functor to access the object's attributes. Casting the 77 returned ``detail::obj_attr_accessor`` instance to a `handle` or `object` 78 subclass causes a corresponding call to ``getattr``. Assigning a `handle` 79 or `object` subclass causes a call to ``setattr``. 80 \endrst */ 81 obj_attr_accessor attr(handle key) const; 82 /// See above (the only difference is that they key is provided as a string literal) 83 str_attr_accessor attr(const char *key) const; 84 85 /** \rst 86 Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple`` 87 or ``list`` for a function call. Applying another * to the result yields 88 ** unpacking, e.g. to unpack a dict as function keyword arguments. 89 See :ref:`calling_python_functions`. 90 \endrst */ 91 args_proxy operator*() const; 92 93 /// Check if the given item is contained within this object, i.e. ``item in obj``. 94 template <typename T> bool contains(T &&item) const; 95 96 /** \rst 97 Assuming the Python object is a function or implements the ``__call__`` 98 protocol, ``operator()`` invokes the underlying function, passing an 99 arbitrary set of parameters. The result is returned as a `object` and 100 may need to be converted back into a Python object using `handle::cast()`. 101 102 When some of the arguments cannot be converted to Python objects, the 103 function will throw a `cast_error` exception. When the Python function 104 call fails, a `error_already_set` exception is thrown. 105 \endrst */ 106 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> 107 object operator()(Args &&...args) const; 108 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> 109 PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)") 110 object call(Args&&... args) const; 111 112 /// Equivalent to ``obj is None`` in Python. 113 bool is_none() const { return derived().ptr() == Py_None; } 114 PYBIND11_DEPRECATED("Use py::str(obj) instead") 115 pybind11::str str() const; 116 117 /// Return the object's current reference count 118 int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); } 119 /// Return a handle to the Python type object underlying the instance 120 handle get_type() const; 121}; 122 123NAMESPACE_END(detail) 124 125/** \rst 126 Holds a reference to a Python object (no reference counting) 127 128 The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a 129 ``PyObject *`` in Python's C API). It does not perform any automatic reference 130 counting and merely provides a basic C++ interface to various Python API functions. 131 132 .. seealso:: 133 The `object` class inherits from `handle` and adds automatic reference 134 counting features. 135\endrst */ 136class handle : public detail::object_api<handle> { 137public: 138 /// The default constructor creates a handle with a ``nullptr``-valued pointer 139 handle() = default; 140 /// Creates a ``handle`` from the given raw Python object pointer 141 handle(PyObject *ptr) : m_ptr(ptr) { } // Allow implicit conversion from PyObject* 142 143 /// Return the underlying ``PyObject *`` pointer 144 PyObject *ptr() const { return m_ptr; } 145 PyObject *&ptr() { return m_ptr; } 146 147 /** \rst 148 Manually increase the reference count of the Python object. Usually, it is 149 preferable to use the `object` class which derives from `handle` and calls 150 this function automatically. Returns a reference to itself. 151 \endrst */ 152 const handle& inc_ref() const & { Py_XINCREF(m_ptr); return *this; } 153 154 /** \rst 155 Manually decrease the reference count of the Python object. Usually, it is 156 preferable to use the `object` class which derives from `handle` and calls 157 this function automatically. Returns a reference to itself. 158 \endrst */ 159 const handle& dec_ref() const & { Py_XDECREF(m_ptr); return *this; } 160 161 /** \rst 162 Attempt to cast the Python object into the given C++ type. A `cast_error` 163 will be throw upon failure. 164 \endrst */ 165 template <typename T> T cast() const; 166 /// Return ``true`` when the `handle` wraps a valid Python object 167 explicit operator bool() const { return m_ptr != nullptr; } 168 /** \rst 169 Check that the underlying pointers are the same. 170 Equivalent to ``obj1 is obj2`` in Python. 171 \endrst */ 172 bool operator==(const handle &h) const { return m_ptr == h.m_ptr; } 173 bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; } 174 PYBIND11_DEPRECATED("Use handle::operator bool() instead") 175 bool check() const { return m_ptr != nullptr; } 176protected: 177 PyObject *m_ptr = nullptr; 178}; 179 180/** \rst 181 Holds a reference to a Python object (with reference counting) 182 183 Like `handle`, the `object` class is a thin wrapper around an arbitrary Python 184 object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it 185 optionally increases the object's reference count upon construction, and it 186 *always* decreases the reference count when the `object` instance goes out of 187 scope and is destructed. When using `object` instances consistently, it is much 188 easier to get reference counting right at the first attempt. 189\endrst */ 190class object : public handle { 191public: 192 object() = default; 193 PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()") 194 object(handle h, bool is_borrowed) : handle(h) { if (is_borrowed) inc_ref(); } 195 /// Copy constructor; always increases the reference count 196 object(const object &o) : handle(o) { inc_ref(); } 197 /// Move constructor; steals the object from ``other`` and preserves its reference count 198 object(object &&other) noexcept { m_ptr = other.m_ptr; other.m_ptr = nullptr; } 199 /// Destructor; automatically calls `handle::dec_ref()` 200 ~object() { dec_ref(); } 201 202 /** \rst 203 Resets the internal pointer to ``nullptr`` without without decreasing the 204 object's reference count. The function returns a raw handle to the original 205 Python object. 206 \endrst */ 207 handle release() { 208 PyObject *tmp = m_ptr; 209 m_ptr = nullptr; 210 return handle(tmp); 211 } 212 213 object& operator=(const object &other) { 214 other.inc_ref(); 215 dec_ref(); 216 m_ptr = other.m_ptr; 217 return *this; 218 } 219 220 object& operator=(object &&other) noexcept { 221 if (this != &other) { 222 handle temp(m_ptr); 223 m_ptr = other.m_ptr; 224 other.m_ptr = nullptr; 225 temp.dec_ref(); 226 } 227 return *this; 228 } 229 230 // Calling cast() on an object lvalue just copies (via handle::cast) 231 template <typename T> T cast() const &; 232 // Calling on an object rvalue does a move, if needed and/or possible 233 template <typename T> T cast() &&; 234 235protected: 236 // Tags for choosing constructors from raw PyObject * 237 struct borrowed_t { }; static constexpr borrowed_t borrowed{}; 238 struct stolen_t { }; static constexpr stolen_t stolen{}; 239 240 template <typename T> friend T reinterpret_borrow(handle); 241 template <typename T> friend T reinterpret_steal(handle); 242 243public: 244 // Only accessible from derived classes and the reinterpret_* functions 245 object(handle h, borrowed_t) : handle(h) { inc_ref(); } 246 object(handle h, stolen_t) : handle(h) { } 247}; 248 249/** \rst 250 Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference. 251 The target type ``T`` must be `object` or one of its derived classes. The function 252 doesn't do any conversions or checks. It's up to the user to make sure that the 253 target type is correct. 254 255 .. code-block:: cpp 256 257 PyObject *p = PyList_GetItem(obj, index); 258 py::object o = reinterpret_borrow<py::object>(p); 259 // or 260 py::tuple t = reinterpret_borrow<py::tuple>(p); // <-- `p` must be already be a `tuple` 261\endrst */ 262template <typename T> T reinterpret_borrow(handle h) { return {h, object::borrowed}; } 263 264/** \rst 265 Like `reinterpret_borrow`, but steals the reference. 266 267 .. code-block:: cpp 268 269 PyObject *p = PyObject_Str(obj); 270 py::str s = reinterpret_steal<py::str>(p); // <-- `p` must be already be a `str` 271\endrst */ 272template <typename T> T reinterpret_steal(handle h) { return {h, object::stolen}; } 273 274/** \defgroup python_builtins _ 275 Unless stated otherwise, the following C++ functions behave the same 276 as their Python counterparts. 277 */ 278 279/** \ingroup python_builtins 280 \rst 281 Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of 282 `object` or a class which was exposed to Python as ``py::class_<T>``. 283\endrst */ 284template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0> 285bool isinstance(handle obj) { return T::check_(obj); } 286 287template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0> 288bool isinstance(handle obj) { return detail::isinstance_generic(obj, typeid(T)); } 289 290template <> inline bool isinstance<handle>(handle obj) = delete; 291template <> inline bool isinstance<object>(handle obj) { return obj.ptr() != nullptr; } 292 293/// \ingroup python_builtins 294/// Return true if ``obj`` is an instance of the ``type``. 295inline bool isinstance(handle obj, handle type) { 296 const auto result = PyObject_IsInstance(obj.ptr(), type.ptr()); 297 if (result == -1) 298 throw error_already_set(); 299 return result != 0; 300} 301 302/// \addtogroup python_builtins 303/// @{ 304inline bool hasattr(handle obj, handle name) { 305 return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1; 306} 307 308inline bool hasattr(handle obj, const char *name) { 309 return PyObject_HasAttrString(obj.ptr(), name) == 1; 310} 311 312inline object getattr(handle obj, handle name) { 313 PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr()); 314 if (!result) { throw error_already_set(); } 315 return reinterpret_steal<object>(result); 316} 317 318inline object getattr(handle obj, const char *name) { 319 PyObject *result = PyObject_GetAttrString(obj.ptr(), name); 320 if (!result) { throw error_already_set(); } 321 return reinterpret_steal<object>(result); 322} 323 324inline object getattr(handle obj, handle name, handle default_) { 325 if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) { 326 return reinterpret_steal<object>(result); 327 } else { 328 PyErr_Clear(); 329 return reinterpret_borrow<object>(default_); 330 } 331} 332 333inline object getattr(handle obj, const char *name, handle default_) { 334 if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) { 335 return reinterpret_steal<object>(result); 336 } else { 337 PyErr_Clear(); 338 return reinterpret_borrow<object>(default_); 339 } 340} 341 342inline void setattr(handle obj, handle name, handle value) { 343 if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) { throw error_already_set(); } 344} 345 346inline void setattr(handle obj, const char *name, handle value) { 347 if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { throw error_already_set(); } 348} 349/// @} python_builtins 350 351NAMESPACE_BEGIN(detail) 352inline handle get_function(handle value) { 353 if (value) { 354#if PY_MAJOR_VERSION >= 3 355 if (PyInstanceMethod_Check(value.ptr())) 356 value = PyInstanceMethod_GET_FUNCTION(value.ptr()); 357#endif 358 if (PyMethod_Check(value.ptr())) 359 value = PyMethod_GET_FUNCTION(value.ptr()); 360 } 361 return value; 362} 363 364// Helper aliases/functions to support implicit casting of values given to python accessors/methods. 365// When given a pyobject, this simply returns the pyobject as-is; for other C++ type, the value goes 366// through pybind11::cast(obj) to convert it to an `object`. 367template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0> 368auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) { return std::forward<T>(o); } 369// The following casting version is implemented in cast.h: 370template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0> 371object object_or_cast(T &&o); 372// Match a PyObject*, which we want to convert directly to handle via its converting constructor 373inline handle object_or_cast(PyObject *ptr) { return ptr; } 374 375 376template <typename Policy> 377class accessor : public object_api<accessor<Policy>> { 378 using key_type = typename Policy::key_type; 379 380public: 381 accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) { } 382 383 // accessor overload required to override default assignment operator (templates are not allowed 384 // to replace default compiler-generated assignments). 385 void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); } 386 void operator=(const accessor &a) & { operator=(handle(a)); } 387 388 template <typename T> void operator=(T &&value) && { 389 Policy::set(obj, key, object_or_cast(std::forward<T>(value))); 390 } 391 template <typename T> void operator=(T &&value) & { 392 get_cache() = reinterpret_borrow<object>(object_or_cast(std::forward<T>(value))); 393 } 394 395 template <typename T = Policy> 396 PYBIND11_DEPRECATED("Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)") 397 explicit operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value || 398 std::is_same<T, accessor_policies::obj_attr>::value, bool>() const { 399 return hasattr(obj, key); 400 } 401 template <typename T = Policy> 402 PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)") 403 explicit operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const { 404 return obj.contains(key); 405 } 406 407 operator object() const { return get_cache(); } 408 PyObject *ptr() const { return get_cache().ptr(); } 409 template <typename T> T cast() const { return get_cache().template cast<T>(); } 410 411private: 412 object &get_cache() const { 413 if (!cache) { cache = Policy::get(obj, key); } 414 return cache; 415 } 416 417private: 418 handle obj; 419 key_type key; 420 mutable object cache; 421}; 422 423NAMESPACE_BEGIN(accessor_policies) 424struct obj_attr { 425 using key_type = object; 426 static object get(handle obj, handle key) { return getattr(obj, key); } 427 static void set(handle obj, handle key, handle val) { setattr(obj, key, val); } 428}; 429 430struct str_attr { 431 using key_type = const char *; 432 static object get(handle obj, const char *key) { return getattr(obj, key); } 433 static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); } 434}; 435 436struct generic_item { 437 using key_type = object; 438 439 static object get(handle obj, handle key) { 440 PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr()); 441 if (!result) { throw error_already_set(); } 442 return reinterpret_steal<object>(result); 443 } 444 445 static void set(handle obj, handle key, handle val) { 446 if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) { throw error_already_set(); } 447 } 448}; 449 450struct sequence_item { 451 using key_type = size_t; 452 453 static object get(handle obj, size_t index) { 454 PyObject *result = PySequence_GetItem(obj.ptr(), static_cast<ssize_t>(index)); 455 if (!result) { throw error_already_set(); } 456 return reinterpret_steal<object>(result); 457 } 458 459 static void set(handle obj, size_t index, handle val) { 460 // PySequence_SetItem does not steal a reference to 'val' 461 if (PySequence_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.ptr()) != 0) { 462 throw error_already_set(); 463 } 464 } 465}; 466 467struct list_item { 468 using key_type = size_t; 469 470 static object get(handle obj, size_t index) { 471 PyObject *result = PyList_GetItem(obj.ptr(), static_cast<ssize_t>(index)); 472 if (!result) { throw error_already_set(); } 473 return reinterpret_borrow<object>(result); 474 } 475 476 static void set(handle obj, size_t index, handle val) { 477 // PyList_SetItem steals a reference to 'val' 478 if (PyList_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.inc_ref().ptr()) != 0) { 479 throw error_already_set(); 480 } 481 } 482}; 483 484struct tuple_item { 485 using key_type = size_t; 486 487 static object get(handle obj, size_t index) { 488 PyObject *result = PyTuple_GetItem(obj.ptr(), static_cast<ssize_t>(index)); 489 if (!result) { throw error_already_set(); } 490 return reinterpret_borrow<object>(result); 491 } 492 493 static void set(handle obj, size_t index, handle val) { 494 // PyTuple_SetItem steals a reference to 'val' 495 if (PyTuple_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.inc_ref().ptr()) != 0) { 496 throw error_already_set(); 497 } 498 } 499}; 500NAMESPACE_END(accessor_policies) 501 502/// STL iterator template used for tuple, list, sequence and dict 503template <typename Policy> 504class generic_iterator : public Policy { 505 using It = generic_iterator; 506 507public: 508 using difference_type = ssize_t; 509 using iterator_category = typename Policy::iterator_category; 510 using value_type = typename Policy::value_type; 511 using reference = typename Policy::reference; 512 using pointer = typename Policy::pointer; 513 514 generic_iterator() = default; 515 generic_iterator(handle seq, ssize_t index) : Policy(seq, index) { } 516 517 reference operator*() const { return Policy::dereference(); } 518 reference operator[](difference_type n) const { return *(*this + n); } 519 pointer operator->() const { return **this; } 520 521 It &operator++() { Policy::increment(); return *this; } 522 It operator++(int) { auto copy = *this; Policy::increment(); return copy; } 523 It &operator--() { Policy::decrement(); return *this; } 524 It operator--(int) { auto copy = *this; Policy::decrement(); return copy; } 525 It &operator+=(difference_type n) { Policy::advance(n); return *this; } 526 It &operator-=(difference_type n) { Policy::advance(-n); return *this; } 527 528 friend It operator+(const It &a, difference_type n) { auto copy = a; return copy += n; } 529 friend It operator+(difference_type n, const It &b) { return b + n; } 530 friend It operator-(const It &a, difference_type n) { auto copy = a; return copy -= n; } 531 friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); } 532 533 friend bool operator==(const It &a, const It &b) { return a.equal(b); } 534 friend bool operator!=(const It &a, const It &b) { return !(a == b); } 535 friend bool operator< (const It &a, const It &b) { return b - a > 0; } 536 friend bool operator> (const It &a, const It &b) { return b < a; } 537 friend bool operator>=(const It &a, const It &b) { return !(a < b); } 538 friend bool operator<=(const It &a, const It &b) { return !(a > b); } 539}; 540 541NAMESPACE_BEGIN(iterator_policies) 542/// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers 543template <typename T> 544struct arrow_proxy { 545 T value; 546 547 arrow_proxy(T &&value) : value(std::move(value)) { } 548 T *operator->() const { return &value; } 549}; 550 551/// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS`` 552class sequence_fast_readonly { 553protected: 554 using iterator_category = std::random_access_iterator_tag; 555 using value_type = handle; 556 using reference = const handle; 557 using pointer = arrow_proxy<const handle>; 558 559 sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) { } 560 561 reference dereference() const { return *ptr; } 562 void increment() { ++ptr; } 563 void decrement() { --ptr; } 564 void advance(ssize_t n) { ptr += n; } 565 bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; } 566 ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; } 567 568private: 569 PyObject **ptr; 570}; 571 572/// Full read and write access using the sequence protocol: see ``detail::sequence_accessor`` 573class sequence_slow_readwrite { 574protected: 575 using iterator_category = std::random_access_iterator_tag; 576 using value_type = object; 577 using reference = sequence_accessor; 578 using pointer = arrow_proxy<const sequence_accessor>; 579 580 sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) { } 581 582 reference dereference() const { return {obj, static_cast<size_t>(index)}; } 583 void increment() { ++index; } 584 void decrement() { --index; } 585 void advance(ssize_t n) { index += n; } 586 bool equal(const sequence_slow_readwrite &b) const { return index == b.index; } 587 ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; } 588 589private: 590 handle obj; 591 ssize_t index; 592}; 593 594/// Python's dictionary protocol permits this to be a forward iterator 595class dict_readonly { 596protected: 597 using iterator_category = std::forward_iterator_tag; 598 using value_type = std::pair<handle, handle>; 599 using reference = const value_type; 600 using pointer = arrow_proxy<const value_type>; 601 602 dict_readonly() = default; 603 dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); } 604 605 reference dereference() const { return {key, value}; } 606 void increment() { if (!PyDict_Next(obj.ptr(), &pos, &key, &value)) { pos = -1; } } 607 bool equal(const dict_readonly &b) const { return pos == b.pos; } 608 609private: 610 handle obj; 611 PyObject *key, *value; 612 ssize_t pos = -1; 613}; 614NAMESPACE_END(iterator_policies) 615 616#if !defined(PYPY_VERSION) 617using tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>; 618using list_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>; 619#else 620using tuple_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>; 621using list_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>; 622#endif 623 624using sequence_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>; 625using dict_iterator = generic_iterator<iterator_policies::dict_readonly>; 626 627inline bool PyIterable_Check(PyObject *obj) { 628 PyObject *iter = PyObject_GetIter(obj); 629 if (iter) { 630 Py_DECREF(iter); 631 return true; 632 } else { 633 PyErr_Clear(); 634 return false; 635 } 636} 637 638inline bool PyNone_Check(PyObject *o) { return o == Py_None; } 639 640inline bool PyUnicode_Check_Permissive(PyObject *o) { return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); } 641 642class kwargs_proxy : public handle { 643public: 644 explicit kwargs_proxy(handle h) : handle(h) { } 645}; 646 647class args_proxy : public handle { 648public: 649 explicit args_proxy(handle h) : handle(h) { } 650 kwargs_proxy operator*() const { return kwargs_proxy(*this); } 651}; 652 653/// Python argument categories (using PEP 448 terms) 654template <typename T> using is_keyword = std::is_base_of<arg, T>; 655template <typename T> using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking 656template <typename T> using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking 657template <typename T> using is_positional = satisfies_none_of<T, 658 is_keyword, is_s_unpacking, is_ds_unpacking 659>; 660template <typename T> using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>; 661 662// Call argument collector forward declarations 663template <return_value_policy policy = return_value_policy::automatic_reference> 664class simple_collector; 665template <return_value_policy policy = return_value_policy::automatic_reference> 666class unpacking_collector; 667 668NAMESPACE_END(detail) 669 670// TODO: After the deprecated constructors are removed, this macro can be simplified by 671// inheriting ctors: `using Parent::Parent`. It's not an option right now because 672// the `using` statement triggers the parent deprecation warning even if the ctor 673// isn't even used. 674#define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ 675 public: \ 676 PYBIND11_DEPRECATED("Use reinterpret_borrow<"#Name">() or reinterpret_steal<"#Name">()") \ 677 Name(handle h, bool is_borrowed) : Parent(is_borrowed ? Parent(h, borrowed) : Parent(h, stolen)) { } \ 678 Name(handle h, borrowed_t) : Parent(h, borrowed) { } \ 679 Name(handle h, stolen_t) : Parent(h, stolen) { } \ 680 PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \ 681 bool check() const { return m_ptr != nullptr && (bool) CheckFun(m_ptr); } \ 682 static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } 683 684#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \ 685 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ 686 /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ 687 Name(const object &o) : Parent(ConvertFun(o.ptr()), stolen) { if (!m_ptr) throw error_already_set(); } 688 689#define PYBIND11_OBJECT(Name, Parent, CheckFun) \ 690 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ 691 /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ 692 Name(const object &o) : Parent(o) { } \ 693 Name(object &&o) : Parent(std::move(o)) { } 694 695#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \ 696 PYBIND11_OBJECT(Name, Parent, CheckFun) \ 697 Name() : Parent() { } 698 699/// \addtogroup pytypes 700/// @{ 701 702/** \rst 703 Wraps a Python iterator so that it can also be used as a C++ input iterator 704 705 Caveat: copying an iterator does not (and cannot) clone the internal 706 state of the Python iterable. This also applies to the post-increment 707 operator. This iterator should only be used to retrieve the current 708 value using ``operator*()``. 709\endrst */ 710class iterator : public object { 711public: 712 using iterator_category = std::input_iterator_tag; 713 using difference_type = ssize_t; 714 using value_type = handle; 715 using reference = const handle; 716 using pointer = const handle *; 717 718 PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check) 719 720 iterator& operator++() { 721 advance(); 722 return *this; 723 } 724 725 iterator operator++(int) { 726 auto rv = *this; 727 advance(); 728 return rv; 729 } 730 731 reference operator*() const { 732 if (m_ptr && !value.ptr()) { 733 auto& self = const_cast<iterator &>(*this); 734 self.advance(); 735 } 736 return value; 737 } 738 739 pointer operator->() const { operator*(); return &value; } 740 741 /** \rst 742 The value which marks the end of the iteration. ``it == iterator::sentinel()`` 743 is equivalent to catching ``StopIteration`` in Python. 744 745 .. code-block:: cpp 746 747 void foo(py::iterator it) { 748 while (it != py::iterator::sentinel()) { 749 // use `*it` 750 ++it; 751 } 752 } 753 \endrst */ 754 static iterator sentinel() { return {}; } 755 756 friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); } 757 friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); } 758 759private: 760 void advance() { 761 value = reinterpret_steal<object>(PyIter_Next(m_ptr)); 762 if (PyErr_Occurred()) { throw error_already_set(); } 763 } 764 765private: 766 object value = {}; 767}; 768 769class iterable : public object { 770public: 771 PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check) 772}; 773 774class bytes; 775 776class str : public object { 777public: 778 PYBIND11_OBJECT_CVT(str, object, detail::PyUnicode_Check_Permissive, raw_str) 779 780 str(const char *c, size_t n) 781 : object(PyUnicode_FromStringAndSize(c, (ssize_t) n), stolen) { 782 if (!m_ptr) pybind11_fail("Could not allocate string object!"); 783 } 784 785 // 'explicit' is explicitly omitted from the following constructors to allow implicit conversion to py::str from C++ string-like objects 786 str(const char *c = "") 787 : object(PyUnicode_FromString(c), stolen) { 788 if (!m_ptr) pybind11_fail("Could not allocate string object!"); 789 } 790 791 str(const std::string &s) : str(s.data(), s.size()) { } 792 793 explicit str(const bytes &b); 794 795 /** \rst 796 Return a string representation of the object. This is analogous to 797 the ``str()`` function in Python. 798 \endrst */ 799 explicit str(handle h) : object(raw_str(h.ptr()), stolen) { } 800 801 operator std::string() const { 802 object temp = *this; 803 if (PyUnicode_Check(m_ptr)) { 804 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr)); 805 if (!temp) 806 pybind11_fail("Unable to extract string contents! (encoding issue)"); 807 } 808 char *buffer; 809 ssize_t length; 810 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length)) 811 pybind11_fail("Unable to extract string contents! (invalid type)"); 812 return std::string(buffer, (size_t) length); 813 } 814 815 template <typename... Args> 816 str format(Args &&...args) const { 817 return attr("format")(std::forward<Args>(args)...); 818 } 819 820private: 821 /// Return string representation -- always returns a new reference, even if already a str 822 static PyObject *raw_str(PyObject *op) { 823 PyObject *str_value = PyObject_Str(op); 824#if PY_MAJOR_VERSION < 3 825 if (!str_value) throw error_already_set(); 826 PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr); 827 Py_XDECREF(str_value); str_value = unicode; 828#endif 829 return str_value; 830 } 831}; 832/// @} pytypes 833 834inline namespace literals { 835/** \rst 836 String literal version of `str` 837 \endrst */ 838inline str operator"" _s(const char *s, size_t size) { return {s, size}; } 839} 840 841/// \addtogroup pytypes 842/// @{ 843class bytes : public object { 844public: 845 PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK) 846 847 // Allow implicit conversion: 848 bytes(const char *c = "") 849 : object(PYBIND11_BYTES_FROM_STRING(c), stolen) { 850 if (!m_ptr) pybind11_fail("Could not allocate bytes object!"); 851 } 852 853 bytes(const char *c, size_t n) 854 : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, (ssize_t) n), stolen) { 855 if (!m_ptr) pybind11_fail("Could not allocate bytes object!"); 856 } 857 858 // Allow implicit conversion: 859 bytes(const std::string &s) : bytes(s.data(), s.size()) { } 860 861 explicit bytes(const pybind11::str &s); 862 863 operator std::string() const { 864 char *buffer; 865 ssize_t length; 866 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length)) 867 pybind11_fail("Unable to extract bytes contents!"); 868 return std::string(buffer, (size_t) length); 869 } 870}; 871 872inline bytes::bytes(const pybind11::str &s) { 873 object temp = s; 874 if (PyUnicode_Check(s.ptr())) { 875 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr())); 876 if (!temp) 877 pybind11_fail("Unable to extract string contents! (encoding issue)"); 878 } 879 char *buffer; 880 ssize_t length; 881 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length)) 882 pybind11_fail("Unable to extract string contents! (invalid type)"); 883 auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length)); 884 if (!obj) 885 pybind11_fail("Could not allocate bytes object!"); 886 m_ptr = obj.release().ptr(); 887} 888 889inline str::str(const bytes& b) { 890 char *buffer; 891 ssize_t length; 892 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(b.ptr(), &buffer, &length)) 893 pybind11_fail("Unable to extract bytes contents!"); 894 auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, (ssize_t) length)); 895 if (!obj) 896 pybind11_fail("Could not allocate string object!"); 897 m_ptr = obj.release().ptr(); 898} 899 900class none : public object { 901public: 902 PYBIND11_OBJECT(none, object, detail::PyNone_Check) 903 none() : object(Py_None, borrowed) { } 904}; 905 906class bool_ : public object { 907public: 908 PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool) 909 bool_() : object(Py_False, borrowed) { } 910 // Allow implicit conversion from and to `bool`: 911 bool_(bool value) : object(value ? Py_True : Py_False, borrowed) { } 912 operator bool() const { return m_ptr && PyLong_AsLong(m_ptr) != 0; } 913 914private: 915 /// Return the truth value of an object -- always returns a new reference 916 static PyObject *raw_bool(PyObject *op) { 917 const auto value = PyObject_IsTrue(op); 918 if (value == -1) return nullptr; 919 return handle(value ? Py_True : Py_False).inc_ref().ptr(); 920 } 921}; 922 923class int_ : public object { 924public: 925 PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long) 926 int_() : object(PyLong_FromLong(0), stolen) { } 927 // Allow implicit conversion from C++ integral types: 928 template <typename T, 929 detail::enable_if_t<std::is_integral<T>::value, int> = 0> 930 int_(T value) { 931 if (sizeof(T) <= sizeof(long)) { 932 if (std::is_signed<T>::value) 933 m_ptr = PyLong_FromLong((long) value); 934 else 935 m_ptr = PyLong_FromUnsignedLong((unsigned long) value); 936 } else { 937 if (std::is_signed<T>::value) 938 m_ptr = PyLong_FromLongLong((long long) value); 939 else 940 m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value); 941 } 942 if (!m_ptr) pybind11_fail("Could not allocate int object!"); 943 } 944 945 template <typename T, 946 detail::enable_if_t<std::is_integral<T>::value, int> = 0> 947 operator T() const { 948 if (sizeof(T) <= sizeof(long)) { 949 if (std::is_signed<T>::value) 950 return (T) PyLong_AsLong(m_ptr); 951 else 952 return (T) PyLong_AsUnsignedLong(m_ptr); 953 } else { 954 if (std::is_signed<T>::value) 955 return (T) PYBIND11_LONG_AS_LONGLONG(m_ptr); 956 else 957 return (T) PYBIND11_LONG_AS_UNSIGNED_LONGLONG(m_ptr); 958 } 959 } 960}; 961 962class float_ : public object { 963public: 964 PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float) 965 // Allow implicit conversion from float/double: 966 float_(float value) : object(PyFloat_FromDouble((double) value), stolen) { 967 if (!m_ptr) pybind11_fail("Could not allocate float object!"); 968 } 969 float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen) { 970 if (!m_ptr) pybind11_fail("Could not allocate float object!"); 971 } 972 operator float() const { return (float) PyFloat_AsDouble(m_ptr); } 973 operator double() const { return (double) PyFloat_AsDouble(m_ptr); } 974}; 975 976class weakref : public object { 977public: 978 PYBIND11_OBJECT_DEFAULT(weakref, object, PyWeakref_Check) 979 explicit weakref(handle obj, handle callback = {}) 980 : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen) { 981 if (!m_ptr) pybind11_fail("Could not allocate weak reference!"); 982 } 983}; 984 985class slice : public object { 986public: 987 PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check) 988 slice(ssize_t start_, ssize_t stop_, ssize_t step_) { 989 int_ start(start_), stop(stop_), step(step_); 990 m_ptr = PySlice_New(start.ptr(), stop.ptr(), step.ptr()); 991 if (!m_ptr) pybind11_fail("Could not allocate slice object!"); 992 } 993 bool compute(size_t length, size_t *start, size_t *stop, size_t *step, 994 size_t *slicelength) const { 995 return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr, 996 (ssize_t) length, (ssize_t *) start, 997 (ssize_t *) stop, (ssize_t *) step, 998 (ssize_t *) slicelength) == 0; 999 } 1000}; 1001 1002class capsule : public object { 1003public: 1004 PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact) 1005 PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()") 1006 capsule(PyObject *ptr, bool is_borrowed) : object(is_borrowed ? object(ptr, borrowed) : object(ptr, stolen)) { } 1007 1008 explicit capsule(const void *value) 1009 : object(PyCapsule_New(const_cast<void *>(value), nullptr, nullptr), stolen) { 1010 if (!m_ptr) 1011 pybind11_fail("Could not allocate capsule object!"); 1012 } 1013 1014 PYBIND11_DEPRECATED("Please pass a destructor that takes a void pointer as input") 1015 capsule(const void *value, void (*destruct)(PyObject *)) 1016 : object(PyCapsule_New(const_cast<void*>(value), nullptr, destruct), stolen) { 1017 if (!m_ptr) 1018 pybind11_fail("Could not allocate capsule object!"); 1019 } 1020 1021 capsule(const void *value, void (*destructor)(void *)) { 1022 m_ptr = PyCapsule_New(const_cast<void *>(value), nullptr, [](PyObject *o) { 1023 auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o)); 1024 void *ptr = PyCapsule_GetPointer(o, nullptr); 1025 destructor(ptr); 1026 }); 1027 1028 if (!m_ptr) 1029 pybind11_fail("Could not allocate capsule object!"); 1030 1031 if (PyCapsule_SetContext(m_ptr, (void *) destructor) != 0) 1032 pybind11_fail("Could not set capsule context!"); 1033 } 1034 1035 capsule(void (*destructor)()) { 1036 m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) { 1037 auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, nullptr)); 1038 destructor(); 1039 }); 1040 1041 if (!m_ptr) 1042 pybind11_fail("Could not allocate capsule object!"); 1043 } 1044 1045 template <typename T> operator T *() const { 1046 T * result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, nullptr)); 1047 if (!result) pybind11_fail("Unable to extract capsule contents!"); 1048 return result; 1049 } 1050}; 1051 1052class tuple : public object { 1053public: 1054 PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple) 1055 explicit tuple(size_t size = 0) : object(PyTuple_New((ssize_t) size), stolen) { 1056 if (!m_ptr) pybind11_fail("Could not allocate tuple object!"); 1057 } 1058 size_t size() const { return (size_t) PyTuple_Size(m_ptr); } 1059 detail::tuple_accessor operator[](size_t index) const { return {*this, index}; } 1060 detail::tuple_iterator begin() const { return {*this, 0}; } 1061 detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; } 1062}; 1063 1064class dict : public object { 1065public: 1066 PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict) 1067 dict() : object(PyDict_New(), stolen) { 1068 if (!m_ptr) pybind11_fail("Could not allocate dict object!"); 1069 } 1070 template <typename... Args, 1071 typename = detail::enable_if_t<detail::all_of<detail::is_keyword_or_ds<Args>...>::value>, 1072 // MSVC workaround: it can't compile an out-of-line definition, so defer the collector 1073 typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>> 1074 explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) { } 1075 1076 size_t size() const { return (size_t) PyDict_Size(m_ptr); } 1077 detail::dict_iterator begin() const { return {*this, 0}; } 1078 detail::dict_iterator end() const { return {}; } 1079 void clear() const { PyDict_Clear(ptr()); } 1080 bool contains(handle key) const { return PyDict_Contains(ptr(), key.ptr()) == 1; } 1081 bool contains(const char *key) const { return PyDict_Contains(ptr(), pybind11::str(key).ptr()) == 1; } 1082 1083private: 1084 /// Call the `dict` Python type -- always returns a new reference 1085 static PyObject *raw_dict(PyObject *op) { 1086 if (PyDict_Check(op)) 1087 return handle(op).inc_ref().ptr(); 1088 return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr); 1089 } 1090}; 1091 1092class sequence : public object { 1093public: 1094 PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check) 1095 size_t size() const { return (size_t) PySequence_Size(m_ptr); } 1096 detail::sequence_accessor operator[](size_t index) const { return {*this, index}; } 1097 detail::sequence_iterator begin() const { return {*this, 0}; } 1098 detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; } 1099}; 1100 1101class list : public object { 1102public: 1103 PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List) 1104 explicit list(size_t size = 0) : object(PyList_New((ssize_t) size), stolen) { 1105 if (!m_ptr) pybind11_fail("Could not allocate list object!"); 1106 } 1107 size_t size() const { return (size_t) PyList_Size(m_ptr); } 1108 detail::list_accessor operator[](size_t index) const { return {*this, index}; } 1109 detail::list_iterator begin() const { return {*this, 0}; } 1110 detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; } 1111 template <typename T> void append(T &&val) const { 1112 PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()); 1113 } 1114}; 1115 1116class args : public tuple { PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) }; 1117class kwargs : public dict { PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check) }; 1118 1119class set : public object { 1120public: 1121 PYBIND11_OBJECT_CVT(set, object, PySet_Check, PySet_New) 1122 set() : object(PySet_New(nullptr), stolen) { 1123 if (!m_ptr) pybind11_fail("Could not allocate set object!"); 1124 } 1125 size_t size() const { return (size_t) PySet_Size(m_ptr); } 1126 template <typename T> bool add(T &&val) const { 1127 return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0; 1128 } 1129 void clear() const { PySet_Clear(m_ptr); } 1130}; 1131 1132class function : public object { 1133public: 1134 PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check) 1135 bool is_cpp_function() const { 1136 handle fun = detail::get_function(m_ptr); 1137 return fun && PyCFunction_Check(fun.ptr()); 1138 } 1139}; 1140 1141class buffer : public object { 1142public: 1143 PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer) 1144 1145 buffer_info request(bool writable = false) { 1146 int flags = PyBUF_STRIDES | PyBUF_FORMAT; 1147 if (writable) flags |= PyBUF_WRITABLE; 1148 Py_buffer *view = new Py_buffer(); 1149 if (PyObject_GetBuffer(m_ptr, view, flags) != 0) 1150 throw error_already_set(); 1151 return buffer_info(view); 1152 } 1153}; 1154 1155class memoryview : public object { 1156public: 1157 explicit memoryview(const buffer_info& info) { 1158 static Py_buffer buf { }; 1159 // Py_buffer uses signed sizes, strides and shape!.. 1160 static std::vector<Py_ssize_t> py_strides { }; 1161 static std::vector<Py_ssize_t> py_shape { }; 1162 buf.buf = info.ptr; 1163 buf.itemsize = (Py_ssize_t) info.itemsize; 1164 buf.format = const_cast<char *>(info.format.c_str()); 1165 buf.ndim = (int) info.ndim; 1166 buf.len = (Py_ssize_t) info.size; 1167 py_strides.clear(); 1168 py_shape.clear(); 1169 for (size_t i = 0; i < info.ndim; ++i) { 1170 py_strides.push_back((Py_ssize_t) info.strides[i]); 1171 py_shape.push_back((Py_ssize_t) info.shape[i]); 1172 } 1173 buf.strides = py_strides.data(); 1174 buf.shape = py_shape.data(); 1175 buf.suboffsets = nullptr; 1176 buf.readonly = false; 1177 buf.internal = nullptr; 1178 1179 m_ptr = PyMemoryView_FromBuffer(&buf); 1180 if (!m_ptr) 1181 pybind11_fail("Unable to create memoryview from buffer descriptor"); 1182 } 1183 1184 PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject) 1185}; 1186/// @} pytypes 1187 1188/// \addtogroup python_builtins 1189/// @{ 1190inline size_t len(handle h) { 1191 ssize_t result = PyObject_Length(h.ptr()); 1192 if (result < 0) 1193 pybind11_fail("Unable to compute length of object"); 1194 return (size_t) result; 1195} 1196 1197inline str repr(handle h) { 1198 PyObject *str_value = PyObject_Repr(h.ptr()); 1199 if (!str_value) throw error_already_set(); 1200#if PY_MAJOR_VERSION < 3 1201 PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr); 1202 Py_XDECREF(str_value); str_value = unicode; 1203 if (!str_value) throw error_already_set(); 1204#endif 1205 return reinterpret_steal<str>(str_value); 1206} 1207 1208inline iterator iter(handle obj) { 1209 PyObject *result = PyObject_GetIter(obj.ptr()); 1210 if (!result) { throw error_already_set(); } 1211 return reinterpret_steal<iterator>(result); 1212} 1213/// @} python_builtins 1214 1215NAMESPACE_BEGIN(detail) 1216template <typename D> iterator object_api<D>::begin() const { return iter(derived()); } 1217template <typename D> iterator object_api<D>::end() const { return iterator::sentinel(); } 1218template <typename D> item_accessor object_api<D>::operator[](handle key) const { 1219 return {derived(), reinterpret_borrow<object>(key)}; 1220} 1221template <typename D> item_accessor object_api<D>::operator[](const char *key) const { 1222 return {derived(), pybind11::str(key)}; 1223} 1224template <typename D> obj_attr_accessor object_api<D>::attr(handle key) const { 1225 return {derived(), reinterpret_borrow<object>(key)}; 1226} 1227template <typename D> str_attr_accessor object_api<D>::attr(const char *key) const { 1228 return {derived(), key}; 1229} 1230template <typename D> args_proxy object_api<D>::operator*() const { 1231 return args_proxy(derived().ptr()); 1232} 1233template <typename D> template <typename T> bool object_api<D>::contains(T &&item) const { 1234 return attr("__contains__")(std::forward<T>(item)).template cast<bool>(); 1235} 1236 1237template <typename D> 1238pybind11::str object_api<D>::str() const { return pybind11::str(derived()); } 1239 1240template <typename D> 1241handle object_api<D>::get_type() const { return (PyObject *) Py_TYPE(derived().ptr()); } 1242 1243NAMESPACE_END(detail) 1244NAMESPACE_END(pybind11) 1245