pytypes.h revision 11986:c12e4625ab56
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/// Mixin which adds common functions to handle, object and various accessors. 49/// The only requirement for `Derived` is to implement `PyObject *Derived::ptr() const`. 50template <typename Derived> 51class object_api : public pyobject_tag { 52 const Derived &derived() const { return static_cast<const Derived &>(*this); } 53 54public: 55 iterator begin() const; 56 iterator end() const; 57 item_accessor operator[](handle key) const; 58 item_accessor operator[](const char *key) const; 59 obj_attr_accessor attr(handle key) const; 60 str_attr_accessor attr(const char *key) const; 61 args_proxy operator*() const; 62 template <typename T> bool contains(T &&key) const; 63 64 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> 65 object operator()(Args &&...args) const; 66 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> 67 PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)") 68 object call(Args&&... args) const; 69 70 bool is_none() const { return derived().ptr() == Py_None; } 71 PYBIND11_DEPRECATED("Instead of obj.str(), use py::str(obj)") 72 pybind11::str str() const; 73 74 int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); } 75 handle get_type() const; 76}; 77 78NAMESPACE_END(detail) 79 80/// Holds a reference to a Python object (no reference counting) 81class handle : public detail::object_api<handle> { 82public: 83 handle() = default; 84 handle(PyObject *ptr) : m_ptr(ptr) { } // Allow implicit conversion from PyObject* 85 86 PyObject *ptr() const { return m_ptr; } 87 PyObject *&ptr() { return m_ptr; } 88 const handle& inc_ref() const { Py_XINCREF(m_ptr); return *this; } 89 const handle& dec_ref() const { Py_XDECREF(m_ptr); return *this; } 90 91 template <typename T> T cast() const; 92 explicit operator bool() const { return m_ptr != nullptr; } 93 bool operator==(const handle &h) const { return m_ptr == h.m_ptr; } 94 bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; } 95 PYBIND11_DEPRECATED("Use handle::operator bool() instead") 96 bool check() const { return m_ptr != nullptr; } 97protected: 98 PyObject *m_ptr = nullptr; 99}; 100 101/// Holds a reference to a Python object (with reference counting) 102class object : public handle { 103public: 104 object() = default; 105 PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()") 106 object(handle h, bool is_borrowed) : handle(h) { if (is_borrowed) inc_ref(); } 107 object(const object &o) : handle(o) { inc_ref(); } 108 object(object &&other) noexcept { m_ptr = other.m_ptr; other.m_ptr = nullptr; } 109 ~object() { dec_ref(); } 110 111 handle release() { 112 PyObject *tmp = m_ptr; 113 m_ptr = nullptr; 114 return handle(tmp); 115 } 116 117 object& operator=(const object &other) { 118 other.inc_ref(); 119 dec_ref(); 120 m_ptr = other.m_ptr; 121 return *this; 122 } 123 124 object& operator=(object &&other) noexcept { 125 if (this != &other) { 126 handle temp(m_ptr); 127 m_ptr = other.m_ptr; 128 other.m_ptr = nullptr; 129 temp.dec_ref(); 130 } 131 return *this; 132 } 133 134 // Calling cast() on an object lvalue just copies (via handle::cast) 135 template <typename T> T cast() const &; 136 // Calling on an object rvalue does a move, if needed and/or possible 137 template <typename T> T cast() &&; 138 139protected: 140 // Tags for choosing constructors from raw PyObject * 141 struct borrowed_t { }; static constexpr borrowed_t borrowed{}; 142 struct stolen_t { }; static constexpr stolen_t stolen{}; 143 144 template <typename T> friend T reinterpret_borrow(handle); 145 template <typename T> friend T reinterpret_steal(handle); 146 147public: 148 // Only accessible from derived classes and the reinterpret_* functions 149 object(handle h, borrowed_t) : handle(h) { inc_ref(); } 150 object(handle h, stolen_t) : handle(h) { } 151}; 152 153/** The following functions don't do any kind of conversion, they simply declare 154 that a PyObject is a certain type and borrow or steal the reference. */ 155template <typename T> T reinterpret_borrow(handle h) { return {h, object::borrowed}; } 156template <typename T> T reinterpret_steal(handle h) { return {h, object::stolen}; } 157 158/// Check if `obj` is an instance of type `T` 159template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0> 160bool isinstance(handle obj) { return T::_check(obj); } 161 162template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0> 163bool isinstance(handle obj) { return detail::isinstance_generic(obj, typeid(T)); } 164 165template <> inline bool isinstance<handle>(handle obj) = delete; 166template <> inline bool isinstance<object>(handle obj) { return obj.ptr() != nullptr; } 167 168inline bool hasattr(handle obj, handle name) { 169 return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1; 170} 171 172inline bool hasattr(handle obj, const char *name) { 173 return PyObject_HasAttrString(obj.ptr(), name) == 1; 174} 175 176inline object getattr(handle obj, handle name) { 177 PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr()); 178 if (!result) { throw error_already_set(); } 179 return reinterpret_steal<object>(result); 180} 181 182inline object getattr(handle obj, const char *name) { 183 PyObject *result = PyObject_GetAttrString(obj.ptr(), name); 184 if (!result) { throw error_already_set(); } 185 return reinterpret_steal<object>(result); 186} 187 188inline object getattr(handle obj, handle name, handle default_) { 189 if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) { 190 return reinterpret_steal<object>(result); 191 } else { 192 PyErr_Clear(); 193 return reinterpret_borrow<object>(default_); 194 } 195} 196 197inline object getattr(handle obj, const char *name, handle default_) { 198 if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) { 199 return reinterpret_steal<object>(result); 200 } else { 201 PyErr_Clear(); 202 return reinterpret_borrow<object>(default_); 203 } 204} 205 206inline void setattr(handle obj, handle name, handle value) { 207 if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) { throw error_already_set(); } 208} 209 210inline void setattr(handle obj, const char *name, handle value) { 211 if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { throw error_already_set(); } 212} 213 214NAMESPACE_BEGIN(detail) 215inline handle get_function(handle value) { 216 if (value) { 217#if PY_MAJOR_VERSION >= 3 218 if (PyInstanceMethod_Check(value.ptr())) 219 value = PyInstanceMethod_GET_FUNCTION(value.ptr()); 220#endif 221 if (PyMethod_Check(value.ptr())) 222 value = PyMethod_GET_FUNCTION(value.ptr()); 223 } 224 return value; 225} 226 227// Helper aliases/functions to support implicit casting of values given to python accessors/methods. 228// When given a pyobject, this simply returns the pyobject as-is; for other C++ type, the value goes 229// through pybind11::cast(obj) to convert it to an `object`. 230template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0> 231auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) { return std::forward<T>(o); } 232// The following casting version is implemented in cast.h: 233template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0> 234object object_or_cast(T &&o); 235// Match a PyObject*, which we want to convert directly to handle via its converting constructor 236inline handle object_or_cast(PyObject *ptr) { return ptr; } 237 238 239template <typename Policy> 240class accessor : public object_api<accessor<Policy>> { 241 using key_type = typename Policy::key_type; 242 243public: 244 accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) { } 245 246 // accessor overload required to override default assignment operator (templates are not allowed 247 // to replace default compiler-generated assignments). 248 void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); } 249 void operator=(const accessor &a) & { operator=(handle(a)); } 250 251 template <typename T> void operator=(T &&value) && { 252 Policy::set(obj, key, object_or_cast(std::forward<T>(value))); 253 } 254 template <typename T> void operator=(T &&value) & { 255 get_cache() = reinterpret_borrow<object>(object_or_cast(std::forward<T>(value))); 256 } 257 258 template <typename T = Policy> 259 PYBIND11_DEPRECATED("Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)") 260 explicit operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value || 261 std::is_same<T, accessor_policies::obj_attr>::value, bool>() const { 262 return hasattr(obj, key); 263 } 264 template <typename T = Policy> 265 PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)") 266 explicit operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const { 267 return obj.contains(key); 268 } 269 270 operator object() const { return get_cache(); } 271 PyObject *ptr() const { return get_cache().ptr(); } 272 template <typename T> T cast() const { return get_cache().template cast<T>(); } 273 274private: 275 object &get_cache() const { 276 if (!cache) { cache = Policy::get(obj, key); } 277 return cache; 278 } 279 280private: 281 handle obj; 282 key_type key; 283 mutable object cache; 284}; 285 286NAMESPACE_BEGIN(accessor_policies) 287struct obj_attr { 288 using key_type = object; 289 static object get(handle obj, handle key) { return getattr(obj, key); } 290 static void set(handle obj, handle key, handle val) { setattr(obj, key, val); } 291}; 292 293struct str_attr { 294 using key_type = const char *; 295 static object get(handle obj, const char *key) { return getattr(obj, key); } 296 static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); } 297}; 298 299struct generic_item { 300 using key_type = object; 301 302 static object get(handle obj, handle key) { 303 PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr()); 304 if (!result) { throw error_already_set(); } 305 return reinterpret_steal<object>(result); 306 } 307 308 static void set(handle obj, handle key, handle val) { 309 if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) { throw error_already_set(); } 310 } 311}; 312 313struct sequence_item { 314 using key_type = size_t; 315 316 static object get(handle obj, size_t index) { 317 PyObject *result = PySequence_GetItem(obj.ptr(), static_cast<ssize_t>(index)); 318 if (!result) { throw error_already_set(); } 319 return reinterpret_borrow<object>(result); 320 } 321 322 static void set(handle obj, size_t index, handle val) { 323 // PySequence_SetItem does not steal a reference to 'val' 324 if (PySequence_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.ptr()) != 0) { 325 throw error_already_set(); 326 } 327 } 328}; 329 330struct list_item { 331 using key_type = size_t; 332 333 static object get(handle obj, size_t index) { 334 PyObject *result = PyList_GetItem(obj.ptr(), static_cast<ssize_t>(index)); 335 if (!result) { throw error_already_set(); } 336 return reinterpret_borrow<object>(result); 337 } 338 339 static void set(handle obj, size_t index, handle val) { 340 // PyList_SetItem steals a reference to 'val' 341 if (PyList_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.inc_ref().ptr()) != 0) { 342 throw error_already_set(); 343 } 344 } 345}; 346 347struct tuple_item { 348 using key_type = size_t; 349 350 static object get(handle obj, size_t index) { 351 PyObject *result = PyTuple_GetItem(obj.ptr(), static_cast<ssize_t>(index)); 352 if (!result) { throw error_already_set(); } 353 return reinterpret_borrow<object>(result); 354 } 355 356 static void set(handle obj, size_t index, handle val) { 357 // PyTuple_SetItem steals a reference to 'val' 358 if (PyTuple_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.inc_ref().ptr()) != 0) { 359 throw error_already_set(); 360 } 361 } 362}; 363NAMESPACE_END(accessor_policies) 364 365struct dict_iterator { 366public: 367 explicit dict_iterator(handle dict = handle(), ssize_t pos = -1) : dict(dict), pos(pos) { } 368 dict_iterator& operator++() { 369 if (!PyDict_Next(dict.ptr(), &pos, &key.ptr(), &value.ptr())) 370 pos = -1; 371 return *this; 372 } 373 std::pair<handle, handle> operator*() const { 374 return std::make_pair(key, value); 375 } 376 bool operator==(const dict_iterator &it) const { return it.pos == pos; } 377 bool operator!=(const dict_iterator &it) const { return it.pos != pos; } 378private: 379 handle dict, key, value; 380 ssize_t pos = 0; 381}; 382 383inline bool PyIterable_Check(PyObject *obj) { 384 PyObject *iter = PyObject_GetIter(obj); 385 if (iter) { 386 Py_DECREF(iter); 387 return true; 388 } else { 389 PyErr_Clear(); 390 return false; 391 } 392} 393 394inline bool PyNone_Check(PyObject *o) { return o == Py_None; } 395 396inline bool PyUnicode_Check_Permissive(PyObject *o) { return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); } 397 398class kwargs_proxy : public handle { 399public: 400 explicit kwargs_proxy(handle h) : handle(h) { } 401}; 402 403class args_proxy : public handle { 404public: 405 explicit args_proxy(handle h) : handle(h) { } 406 kwargs_proxy operator*() const { return kwargs_proxy(*this); } 407}; 408 409/// Python argument categories (using PEP 448 terms) 410template <typename T> using is_keyword = std::is_base_of<arg, T>; 411template <typename T> using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking 412template <typename T> using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking 413template <typename T> using is_positional = bool_constant< 414 !is_keyword<T>::value && !is_s_unpacking<T>::value && !is_ds_unpacking<T>::value 415>; 416template <typename T> using is_keyword_or_ds = bool_constant< 417 is_keyword<T>::value || is_ds_unpacking<T>::value 418>; 419 420// Call argument collector forward declarations 421template <return_value_policy policy = return_value_policy::automatic_reference> 422class simple_collector; 423template <return_value_policy policy = return_value_policy::automatic_reference> 424class unpacking_collector; 425 426NAMESPACE_END(detail) 427 428// TODO: After the deprecated constructors are removed, this macro can be simplified by 429// inheriting ctors: `using Parent::Parent`. It's not an option right now because 430// the `using` statement triggers the parent deprecation warning even if the ctor 431// isn't even used. 432#define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ 433 public: \ 434 PYBIND11_DEPRECATED("Use reinterpret_borrow<"#Name">() or reinterpret_steal<"#Name">()") \ 435 Name(handle h, bool is_borrowed) : Parent(is_borrowed ? Parent(h, borrowed) : Parent(h, stolen)) { } \ 436 Name(handle h, borrowed_t) : Parent(h, borrowed) { } \ 437 Name(handle h, stolen_t) : Parent(h, stolen) { } \ 438 PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \ 439 bool check() const { return m_ptr != nullptr && (bool) CheckFun(m_ptr); } \ 440 static bool _check(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } 441 442#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \ 443 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ 444 /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ 445 Name(const object &o) : Parent(ConvertFun(o.ptr()), stolen) { if (!m_ptr) throw error_already_set(); } 446 447#define PYBIND11_OBJECT(Name, Parent, CheckFun) \ 448 PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ 449 /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ 450 Name(const object &o) : Parent(o) { } \ 451 Name(object &&o) : Parent(std::move(o)) { } 452 453#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \ 454 PYBIND11_OBJECT(Name, Parent, CheckFun) \ 455 Name() : Parent() { } 456 457class iterator : public object { 458public: 459 /** Caveat: copying an iterator does not (and cannot) clone the internal 460 state of the Python iterable */ 461 PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check) 462 463 iterator& operator++() { 464 if (m_ptr) 465 advance(); 466 return *this; 467 } 468 469 /** Caveat: this postincrement operator does not (and cannot) clone the 470 internal state of the Python iterable. It should only be used to 471 retrieve the current iterate using <tt>operator*()</tt> */ 472 iterator operator++(int) { 473 iterator rv(*this); 474 rv.value = value; 475 if (m_ptr) 476 advance(); 477 return rv; 478 } 479 480 bool operator==(const iterator &it) const { return *it == **this; } 481 bool operator!=(const iterator &it) const { return *it != **this; } 482 483 handle operator*() const { 484 if (!ready && m_ptr) { 485 auto& self = const_cast<iterator &>(*this); 486 self.advance(); 487 self.ready = true; 488 } 489 return value; 490 } 491 492private: 493 void advance() { value = reinterpret_steal<object>(PyIter_Next(m_ptr)); } 494 495private: 496 object value = {}; 497 bool ready = false; 498}; 499 500class iterable : public object { 501public: 502 PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check) 503}; 504 505class bytes; 506 507class str : public object { 508public: 509 PYBIND11_OBJECT_CVT(str, object, detail::PyUnicode_Check_Permissive, raw_str) 510 511 str(const char *c, size_t n) 512 : object(PyUnicode_FromStringAndSize(c, (ssize_t) n), stolen) { 513 if (!m_ptr) pybind11_fail("Could not allocate string object!"); 514 } 515 516 // 'explicit' is explicitly omitted from the following constructors to allow implicit conversion to py::str from C++ string-like objects 517 str(const char *c = "") 518 : object(PyUnicode_FromString(c), stolen) { 519 if (!m_ptr) pybind11_fail("Could not allocate string object!"); 520 } 521 522 str(const std::string &s) : str(s.data(), s.size()) { } 523 524 explicit str(const bytes &b); 525 526 explicit str(handle h) : object(raw_str(h.ptr()), stolen) { } 527 528 operator std::string() const { 529 object temp = *this; 530 if (PyUnicode_Check(m_ptr)) { 531 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr)); 532 if (!temp) 533 pybind11_fail("Unable to extract string contents! (encoding issue)"); 534 } 535 char *buffer; 536 ssize_t length; 537 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length)) 538 pybind11_fail("Unable to extract string contents! (invalid type)"); 539 return std::string(buffer, (size_t) length); 540 } 541 542 template <typename... Args> 543 str format(Args &&...args) const { 544 return attr("format")(std::forward<Args>(args)...); 545 } 546 547private: 548 /// Return string representation -- always returns a new reference, even if already a str 549 static PyObject *raw_str(PyObject *op) { 550 PyObject *str_value = PyObject_Str(op); 551#if PY_MAJOR_VERSION < 3 552 if (!str_value) throw error_already_set(); 553 PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr); 554 Py_XDECREF(str_value); str_value = unicode; 555#endif 556 return str_value; 557 } 558}; 559 560inline namespace literals { 561/// String literal version of str 562inline str operator"" _s(const char *s, size_t size) { return {s, size}; } 563} 564 565class bytes : public object { 566public: 567 PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK) 568 569 // Allow implicit conversion: 570 bytes(const char *c = "") 571 : object(PYBIND11_BYTES_FROM_STRING(c), stolen) { 572 if (!m_ptr) pybind11_fail("Could not allocate bytes object!"); 573 } 574 575 bytes(const char *c, size_t n) 576 : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, (ssize_t) n), stolen) { 577 if (!m_ptr) pybind11_fail("Could not allocate bytes object!"); 578 } 579 580 // Allow implicit conversion: 581 bytes(const std::string &s) : bytes(s.data(), s.size()) { } 582 583 explicit bytes(const pybind11::str &s); 584 585 operator std::string() const { 586 char *buffer; 587 ssize_t length; 588 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length)) 589 pybind11_fail("Unable to extract bytes contents!"); 590 return std::string(buffer, (size_t) length); 591 } 592}; 593 594inline bytes::bytes(const pybind11::str &s) { 595 object temp = s; 596 if (PyUnicode_Check(s.ptr())) { 597 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr())); 598 if (!temp) 599 pybind11_fail("Unable to extract string contents! (encoding issue)"); 600 } 601 char *buffer; 602 ssize_t length; 603 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length)) 604 pybind11_fail("Unable to extract string contents! (invalid type)"); 605 auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length)); 606 if (!obj) 607 pybind11_fail("Could not allocate bytes object!"); 608 m_ptr = obj.release().ptr(); 609} 610 611inline str::str(const bytes& b) { 612 char *buffer; 613 ssize_t length; 614 if (PYBIND11_BYTES_AS_STRING_AND_SIZE(b.ptr(), &buffer, &length)) 615 pybind11_fail("Unable to extract bytes contents!"); 616 auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, (ssize_t) length)); 617 if (!obj) 618 pybind11_fail("Could not allocate string object!"); 619 m_ptr = obj.release().ptr(); 620} 621 622class none : public object { 623public: 624 PYBIND11_OBJECT(none, object, detail::PyNone_Check) 625 none() : object(Py_None, borrowed) { } 626}; 627 628class bool_ : public object { 629public: 630 PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool) 631 bool_() : object(Py_False, borrowed) { } 632 // Allow implicit conversion from and to `bool`: 633 bool_(bool value) : object(value ? Py_True : Py_False, borrowed) { } 634 operator bool() const { return m_ptr && PyLong_AsLong(m_ptr) != 0; } 635 636private: 637 /// Return the truth value of an object -- always returns a new reference 638 static PyObject *raw_bool(PyObject *op) { 639 const auto value = PyObject_IsTrue(op); 640 if (value == -1) return nullptr; 641 return handle(value ? Py_True : Py_False).inc_ref().ptr(); 642 } 643}; 644 645class int_ : public object { 646public: 647 PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long) 648 int_() : object(PyLong_FromLong(0), stolen) { } 649 // Allow implicit conversion from C++ integral types: 650 template <typename T, 651 detail::enable_if_t<std::is_integral<T>::value, int> = 0> 652 int_(T value) { 653 if (sizeof(T) <= sizeof(long)) { 654 if (std::is_signed<T>::value) 655 m_ptr = PyLong_FromLong((long) value); 656 else 657 m_ptr = PyLong_FromUnsignedLong((unsigned long) value); 658 } else { 659 if (std::is_signed<T>::value) 660 m_ptr = PyLong_FromLongLong((long long) value); 661 else 662 m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value); 663 } 664 if (!m_ptr) pybind11_fail("Could not allocate int object!"); 665 } 666 667 template <typename T, 668 detail::enable_if_t<std::is_integral<T>::value, int> = 0> 669 operator T() const { 670 if (sizeof(T) <= sizeof(long)) { 671 if (std::is_signed<T>::value) 672 return (T) PyLong_AsLong(m_ptr); 673 else 674 return (T) PyLong_AsUnsignedLong(m_ptr); 675 } else { 676 if (std::is_signed<T>::value) 677 return (T) PYBIND11_LONG_AS_LONGLONG(m_ptr); 678 else 679 return (T) PYBIND11_LONG_AS_UNSIGNED_LONGLONG(m_ptr); 680 } 681 } 682}; 683 684class float_ : public object { 685public: 686 PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float) 687 // Allow implicit conversion from float/double: 688 float_(float value) : object(PyFloat_FromDouble((double) value), stolen) { 689 if (!m_ptr) pybind11_fail("Could not allocate float object!"); 690 } 691 float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen) { 692 if (!m_ptr) pybind11_fail("Could not allocate float object!"); 693 } 694 operator float() const { return (float) PyFloat_AsDouble(m_ptr); } 695 operator double() const { return (double) PyFloat_AsDouble(m_ptr); } 696}; 697 698class weakref : public object { 699public: 700 PYBIND11_OBJECT_DEFAULT(weakref, object, PyWeakref_Check) 701 explicit weakref(handle obj, handle callback = {}) 702 : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen) { 703 if (!m_ptr) pybind11_fail("Could not allocate weak reference!"); 704 } 705}; 706 707class slice : public object { 708public: 709 PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check) 710 slice(ssize_t start_, ssize_t stop_, ssize_t step_) { 711 int_ start(start_), stop(stop_), step(step_); 712 m_ptr = PySlice_New(start.ptr(), stop.ptr(), step.ptr()); 713 if (!m_ptr) pybind11_fail("Could not allocate slice object!"); 714 } 715 bool compute(size_t length, size_t *start, size_t *stop, size_t *step, 716 size_t *slicelength) const { 717 return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr, 718 (ssize_t) length, (ssize_t *) start, 719 (ssize_t *) stop, (ssize_t *) step, 720 (ssize_t *) slicelength) == 0; 721 } 722}; 723 724class capsule : public object { 725public: 726 PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact) 727 PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()") 728 capsule(PyObject *ptr, bool is_borrowed) : object(is_borrowed ? object(ptr, borrowed) : object(ptr, stolen)) { } 729 explicit capsule(const void *value, void (*destruct)(PyObject *) = nullptr) 730 : object(PyCapsule_New(const_cast<void*>(value), nullptr, destruct), stolen) { 731 if (!m_ptr) pybind11_fail("Could not allocate capsule object!"); 732 } 733 template <typename T> operator T *() const { 734 T * result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, nullptr)); 735 if (!result) pybind11_fail("Unable to extract capsule contents!"); 736 return result; 737 } 738}; 739 740class tuple : public object { 741public: 742 PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple) 743 explicit tuple(size_t size = 0) : object(PyTuple_New((ssize_t) size), stolen) { 744 if (!m_ptr) pybind11_fail("Could not allocate tuple object!"); 745 } 746 size_t size() const { return (size_t) PyTuple_Size(m_ptr); } 747 detail::tuple_accessor operator[](size_t index) const { return {*this, index}; } 748}; 749 750class dict : public object { 751public: 752 PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict) 753 dict() : object(PyDict_New(), stolen) { 754 if (!m_ptr) pybind11_fail("Could not allocate dict object!"); 755 } 756 template <typename... Args, 757 typename = detail::enable_if_t<detail::all_of_t<detail::is_keyword_or_ds, Args...>::value>, 758 // MSVC workaround: it can't compile an out-of-line definition, so defer the collector 759 typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>> 760 explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) { } 761 762 size_t size() const { return (size_t) PyDict_Size(m_ptr); } 763 detail::dict_iterator begin() const { return (++detail::dict_iterator(*this, 0)); } 764 detail::dict_iterator end() const { return detail::dict_iterator(); } 765 void clear() const { PyDict_Clear(ptr()); } 766 bool contains(handle key) const { return PyDict_Contains(ptr(), key.ptr()) == 1; } 767 bool contains(const char *key) const { return PyDict_Contains(ptr(), pybind11::str(key).ptr()) == 1; } 768 769private: 770 /// Call the `dict` Python type -- always returns a new reference 771 static PyObject *raw_dict(PyObject *op) { 772 if (PyDict_Check(op)) 773 return handle(op).inc_ref().ptr(); 774 return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr); 775 } 776}; 777 778class sequence : public object { 779public: 780 PYBIND11_OBJECT(sequence, object, PySequence_Check) 781 size_t size() const { return (size_t) PySequence_Size(m_ptr); } 782 detail::sequence_accessor operator[](size_t index) const { return {*this, index}; } 783}; 784 785class list : public object { 786public: 787 PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List) 788 explicit list(size_t size = 0) : object(PyList_New((ssize_t) size), stolen) { 789 if (!m_ptr) pybind11_fail("Could not allocate list object!"); 790 } 791 size_t size() const { return (size_t) PyList_Size(m_ptr); } 792 detail::list_accessor operator[](size_t index) const { return {*this, index}; } 793 template <typename T> void append(T &&val) const { 794 PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()); 795 } 796}; 797 798class args : public tuple { PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) }; 799class kwargs : public dict { PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check) }; 800 801class set : public object { 802public: 803 PYBIND11_OBJECT_CVT(set, object, PySet_Check, PySet_New) 804 set() : object(PySet_New(nullptr), stolen) { 805 if (!m_ptr) pybind11_fail("Could not allocate set object!"); 806 } 807 size_t size() const { return (size_t) PySet_Size(m_ptr); } 808 template <typename T> bool add(T &&val) const { 809 return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0; 810 } 811 void clear() const { PySet_Clear(m_ptr); } 812}; 813 814class function : public object { 815public: 816 PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check) 817 bool is_cpp_function() const { 818 handle fun = detail::get_function(m_ptr); 819 return fun && PyCFunction_Check(fun.ptr()); 820 } 821}; 822 823class buffer : public object { 824public: 825 PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer) 826 827 buffer_info request(bool writable = false) { 828 int flags = PyBUF_STRIDES | PyBUF_FORMAT; 829 if (writable) flags |= PyBUF_WRITABLE; 830 Py_buffer *view = new Py_buffer(); 831 if (PyObject_GetBuffer(m_ptr, view, flags) != 0) 832 throw error_already_set(); 833 return buffer_info(view); 834 } 835}; 836 837class memoryview : public object { 838public: 839 explicit memoryview(const buffer_info& info) { 840 static Py_buffer buf { }; 841 // Py_buffer uses signed sizes, strides and shape!.. 842 static std::vector<Py_ssize_t> py_strides { }; 843 static std::vector<Py_ssize_t> py_shape { }; 844 buf.buf = info.ptr; 845 buf.itemsize = (Py_ssize_t) info.itemsize; 846 buf.format = const_cast<char *>(info.format.c_str()); 847 buf.ndim = (int) info.ndim; 848 buf.len = (Py_ssize_t) info.size; 849 py_strides.clear(); 850 py_shape.clear(); 851 for (size_t i = 0; i < info.ndim; ++i) { 852 py_strides.push_back((Py_ssize_t) info.strides[i]); 853 py_shape.push_back((Py_ssize_t) info.shape[i]); 854 } 855 buf.strides = py_strides.data(); 856 buf.shape = py_shape.data(); 857 buf.suboffsets = nullptr; 858 buf.readonly = false; 859 buf.internal = nullptr; 860 861 m_ptr = PyMemoryView_FromBuffer(&buf); 862 if (!m_ptr) 863 pybind11_fail("Unable to create memoryview from buffer descriptor"); 864 } 865 866 PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject) 867}; 868 869inline size_t len(handle h) { 870 ssize_t result = PyObject_Length(h.ptr()); 871 if (result < 0) 872 pybind11_fail("Unable to compute length of object"); 873 return (size_t) result; 874} 875 876inline str repr(handle h) { 877 PyObject *str_value = PyObject_Repr(h.ptr()); 878 if (!str_value) throw error_already_set(); 879#if PY_MAJOR_VERSION < 3 880 PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr); 881 Py_XDECREF(str_value); str_value = unicode; 882 if (!str_value) throw error_already_set(); 883#endif 884 return reinterpret_steal<str>(str_value); 885} 886 887NAMESPACE_BEGIN(detail) 888template <typename D> iterator object_api<D>::begin() const { 889 return reinterpret_steal<iterator>(PyObject_GetIter(derived().ptr())); 890} 891template <typename D> iterator object_api<D>::end() const { 892 return {}; 893} 894template <typename D> item_accessor object_api<D>::operator[](handle key) const { 895 return {derived(), reinterpret_borrow<object>(key)}; 896} 897template <typename D> item_accessor object_api<D>::operator[](const char *key) const { 898 return {derived(), pybind11::str(key)}; 899} 900template <typename D> obj_attr_accessor object_api<D>::attr(handle key) const { 901 return {derived(), reinterpret_borrow<object>(key)}; 902} 903template <typename D> str_attr_accessor object_api<D>::attr(const char *key) const { 904 return {derived(), key}; 905} 906template <typename D> args_proxy object_api<D>::operator*() const { 907 return args_proxy(derived().ptr()); 908} 909template <typename D> template <typename T> bool object_api<D>::contains(T &&key) const { 910 return attr("__contains__")(std::forward<T>(key)).template cast<bool>(); 911} 912 913template <typename D> 914pybind11::str object_api<D>::str() const { return pybind11::str(derived()); } 915 916template <typename D> 917handle object_api<D>::get_type() const { return (PyObject *) Py_TYPE(derived().ptr()); } 918 919NAMESPACE_END(detail) 920NAMESPACE_END(pybind11) 921