μHAL (v2.8.17)
Part of the IPbus software repository
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
cast.h
Go to the documentation of this file.
1/*
2 pybind11/cast.h: Partial template specializations to cast between
3 C++ and Python types
4
5 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6
7 All rights reserved. Use of this source code is governed by a
8 BSD-style license that can be found in the LICENSE file.
9*/
10
11#pragma once
12
13#include "detail/common.h"
14#include "detail/descr.h"
15#include "detail/type_caster_base.h"
16#include "detail/typeid.h"
17#include "pytypes.h"
18
19#include <array>
20#include <cstring>
21#include <functional>
22#include <iosfwd>
23#include <iterator>
24#include <memory>
25#include <string>
26#include <tuple>
27#include <type_traits>
28#include <utility>
29#include <vector>
30
33
34template <typename type, typename SFINAE = void>
35class type_caster : public type_caster_base<type> {};
36template <typename type>
38
39// Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
40template <typename T>
42 return caster.operator typename make_caster<T>::template cast_op_type<T>();
43}
44template <typename T>
47 return std::move(caster).operator typename make_caster<T>::
49}
50
51template <typename type>
52class type_caster<std::reference_wrapper<type>> {
53private:
56 using reference_t = type &;
57 using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
58
59 static_assert(
60 std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
61 || std::is_same<reference_t, subcaster_cast_op_type>::value,
62 "std::reference_wrapper<T> caster requires T to have a caster with an "
63 "`operator T &()` or `operator const T &()`");
64
65public:
66 bool load(handle src, bool convert) { return subcaster.load(src, convert); }
67 static constexpr auto name = caster_t::name;
68 static handle
69 cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
70 // It is definitely wrong to take ownership of this pointer, so mask that rvp
71 if (policy == return_value_policy::take_ownership
72 || policy == return_value_policy::automatic) {
73 policy = return_value_policy::automatic_reference;
74 }
75 return caster_t::cast(&src.get(), policy, parent);
76 }
77 template <typename T>
78 using cast_op_type = std::reference_wrapper<type>;
79 explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
80};
81
82#define PYBIND11_TYPE_CASTER(type, py_name) \
83protected: \
84 type value; \
85 \
86public: \
87 static constexpr auto name = py_name; \
88 template <typename T_, \
89 ::pybind11::detail::enable_if_t< \
90 std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value, \
91 int> = 0> \
92 static ::pybind11::handle cast( \
93 T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) { \
94 if (!src) \
95 return ::pybind11::none().release(); \
96 if (policy == ::pybind11::return_value_policy::take_ownership) { \
97 auto h = cast(std::move(*src), policy, parent); \
98 delete src; \
99 return h; \
100 } \
101 return cast(*src, policy, parent); \
102 } \
103 operator type *() { return &value; } /* NOLINT(bugprone-macro-parentheses) */ \
104 operator type &() { return value; } /* NOLINT(bugprone-macro-parentheses) */ \
105 operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */ \
106 template <typename T_> \
107 using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
108
109template <typename CharT>
111#if defined(PYBIND11_HAS_U8STRING)
112 std::is_same<CharT, char8_t>, /* std::u8string */
113#endif
114 std::is_same<CharT, char16_t>, /* std::u16string */
115 std::is_same<CharT, char32_t>, /* std::u32string */
116 std::is_same<CharT, wchar_t> /* std::wstring */
117 >;
118
119template <typename T>
120struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
121 using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
124 typename std::make_unsigned<_py_type_0>::type>;
125 using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
126
127public:
128 bool load(handle src, bool convert) {
129 py_type py_value;
130
131 if (!src) {
132 return false;
133 }
134
135#if !defined(PYPY_VERSION)
136 auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
137#else
138 // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
139 // while CPython only considers the existence of `nb_index`/`__index__`.
140 auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
141#endif
142
143 if (std::is_floating_point<T>::value) {
144 if (convert || PyFloat_Check(src.ptr())) {
145 py_value = (py_type) PyFloat_AsDouble(src.ptr());
146 } else {
147 return false;
148 }
149 } else if (PyFloat_Check(src.ptr())
150 || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
151 return false;
152 } else {
153 handle src_or_index = src;
154 // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
155#if PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
156 object index;
157 if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
158 index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
159 if (!index) {
160 PyErr_Clear();
161 if (!convert)
162 return false;
163 } else {
164 src_or_index = index;
165 }
166 }
167#endif
168 if (std::is_unsigned<py_type>::value) {
169 py_value = as_unsigned<py_type>(src_or_index.ptr());
170 } else { // signed integer:
171 py_value = sizeof(T) <= sizeof(long)
172 ? (py_type) PyLong_AsLong(src_or_index.ptr())
173 : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
174 }
175 }
176
177 // Python API reported an error
178 bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
179
180 // Check to see if the conversion is valid (integers should match exactly)
181 // Signed/unsigned checks happen elsewhere
182 if (py_err
183 || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
184 && py_value != (py_type) (T) py_value)) {
185 PyErr_Clear();
186 if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
187 auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
188 ? PyNumber_Float(src.ptr())
189 : PyNumber_Long(src.ptr()));
190 PyErr_Clear();
191 return load(tmp, false);
192 }
193 return false;
194 }
195
196 value = (T) py_value;
197 return true;
198 }
199
200 template <typename U = T>
201 static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
202 cast(U src, return_value_policy /* policy */, handle /* parent */) {
203 return PyFloat_FromDouble((double) src);
204 }
205
206 template <typename U = T>
207 static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
208 && (sizeof(U) <= sizeof(long)),
210 cast(U src, return_value_policy /* policy */, handle /* parent */) {
211 return PYBIND11_LONG_FROM_SIGNED((long) src);
212 }
213
214 template <typename U = T>
215 static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
216 && (sizeof(U) <= sizeof(unsigned long)),
218 cast(U src, return_value_policy /* policy */, handle /* parent */) {
219 return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
220 }
221
222 template <typename U = T>
223 static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
224 && (sizeof(U) > sizeof(long)),
226 cast(U src, return_value_policy /* policy */, handle /* parent */) {
227 return PyLong_FromLongLong((long long) src);
228 }
229
230 template <typename U = T>
231 static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
232 && (sizeof(U) > sizeof(unsigned long)),
234 cast(U src, return_value_policy /* policy */, handle /* parent */) {
235 return PyLong_FromUnsignedLongLong((unsigned long long) src);
236 }
237
238 PYBIND11_TYPE_CASTER(T, const_name<std::is_integral<T>::value>("int", "float"));
239};
240
241template <typename T>
243public:
244 bool load(handle src, bool) {
245 if (src && src.is_none()) {
246 return true;
247 }
248 return false;
249 }
250 static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
251 return none().inc_ref();
252 }
254};
255
256template <>
257class type_caster<void_type> : public void_caster<void_type> {};
258
259template <>
260class type_caster<void> : public type_caster<void_type> {
261public:
263
264 bool load(handle h, bool) {
265 if (!h) {
266 return false;
267 }
268 if (h.is_none()) {
269 value = nullptr;
270 return true;
271 }
272
273 /* Check if this is a capsule */
274 if (isinstance<capsule>(h)) {
275 value = reinterpret_borrow<capsule>(h);
276 return true;
277 }
278
279 /* Check if this is a C++ type */
280 const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
281 if (bases.size() == 1) { // Only allowing loading from a single-value type
282 value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
283 return true;
284 }
285
286 /* Fail */
287 return false;
288 }
289
290 static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
291 if (ptr) {
292 return capsule(ptr).release();
293 }
294 return none().inc_ref();
295 }
296
297 template <typename T>
298 using cast_op_type = void *&;
299 explicit operator void *&() { return value; }
300 static constexpr auto name = const_name("capsule");
301
302private:
303 void *value = nullptr;
304};
305
306template <>
307class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
308
309template <>
310class type_caster<bool> {
311public:
312 bool load(handle src, bool convert) {
313 if (!src) {
314 return false;
315 }
316 if (src.ptr() == Py_True) {
317 value = true;
318 return true;
319 }
320 if (src.ptr() == Py_False) {
321 value = false;
322 return true;
323 }
324 if (convert || (std::strcmp("numpy.bool_", Py_TYPE(src.ptr())->tp_name) == 0)) {
325 // (allow non-implicit conversion for numpy booleans)
326
327 Py_ssize_t res = -1;
328 if (src.is_none()) {
329 res = 0; // None is implicitly converted to False
330 }
331#if defined(PYPY_VERSION)
332 // On PyPy, check that "__bool__" (or "__nonzero__" on Python 2.7) attr exists
333 else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
334 res = PyObject_IsTrue(src.ptr());
335 }
336#else
337 // Alternate approach for CPython: this does the same as the above, but optimized
338 // using the CPython API so as to avoid an unneeded attribute lookup.
339 else if (auto *tp_as_number = src.ptr()->ob_type->tp_as_number) {
340 if (PYBIND11_NB_BOOL(tp_as_number)) {
341 res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
342 }
343 }
344#endif
345 if (res == 0 || res == 1) {
346 value = (res != 0);
347 return true;
348 }
349 PyErr_Clear();
350 }
351 return false;
352 }
353 static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
354 return handle(src ? Py_True : Py_False).inc_ref();
355 }
357};
358
359// Helper class for UTF-{8,16,32} C++ stl strings:
360template <typename StringType, bool IsView = false>
362 using CharT = typename StringType::value_type;
363
364 // Simplify life by being able to assume standard char sizes (the standard only guarantees
365 // minimums, but Python requires exact sizes)
366 static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
367 "Unsupported char size != 1");
368#if defined(PYBIND11_HAS_U8STRING)
369 static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
370 "Unsupported char8_t size != 1");
371#endif
372 static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
373 "Unsupported char16_t size != 2");
374 static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
375 "Unsupported char32_t size != 4");
376 // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
377 static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
378 "Unsupported wchar_t size != 2/4");
379 static constexpr size_t UTF_N = 8 * sizeof(CharT);
380
381 bool load(handle src, bool) {
382#if PY_MAJOR_VERSION < 3
383 object temp;
384#endif
385 handle load_src = src;
386 if (!src) {
387 return false;
388 }
389 if (!PyUnicode_Check(load_src.ptr())) {
390#if PY_MAJOR_VERSION >= 3
391 return load_bytes(load_src);
392#else
393 if (std::is_same<CharT, char>::value) {
394 return load_bytes(load_src);
395 }
396
397 // The below is a guaranteed failure in Python 3 when PyUnicode_Check returns false
398 if (!PYBIND11_BYTES_CHECK(load_src.ptr()))
399 return false;
400
401 temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.ptr()));
402 if (!temp) {
403 PyErr_Clear();
404 return false;
405 }
406 load_src = temp;
407#endif
408 }
409
410#if PY_VERSION_HEX >= 0x03030000
411 // On Python >= 3.3, for UTF-8 we avoid the need for a temporary `bytes`
412 // object by using `PyUnicode_AsUTF8AndSize`.
414 Py_ssize_t size = -1;
415 const auto *buffer
416 = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
417 if (!buffer) {
418 PyErr_Clear();
419 return false;
420 }
421 value = StringType(buffer, static_cast<size_t>(size));
422 return true;
423 }
424#endif
425
426 auto utfNbytes
427 = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
428 UTF_N == 8 ? "utf-8"
429 : UTF_N == 16 ? "utf-16"
430 : "utf-32",
431 nullptr));
432 if (!utfNbytes) {
433 PyErr_Clear();
434 return false;
435 }
436
437 const auto *buffer
438 = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
439 size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
440 // Skip BOM for UTF-16/32
442 buffer++;
443 length--;
444 }
445 value = StringType(buffer, length);
446
447 // If we're loading a string_view we need to keep the encoded Python object alive:
448 if (IsView) {
450 }
451
452 return true;
453 }
454
455 static handle
456 cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
457 const char *buffer = reinterpret_cast<const char *>(src.data());
458 auto nbytes = ssize_t(src.size() * sizeof(CharT));
459 handle s = decode_utfN(buffer, nbytes);
460 if (!s) {
461 throw error_already_set();
462 }
463 return s;
464 }
465
467
468private:
469 static handle decode_utfN(const char *buffer, ssize_t nbytes) {
470#if !defined(PYPY_VERSION)
471 return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
472 : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
473 : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
474#else
475 // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
476 // well), so bypass the whole thing by just passing the encoding as a string value, which
477 // works properly:
478 return PyUnicode_Decode(buffer,
479 nbytes,
480 UTF_N == 8 ? "utf-8"
481 : UTF_N == 16 ? "utf-16"
482 : "utf-32",
483 nullptr);
484#endif
485 }
486
487 // When loading into a std::string or char*, accept a bytes object as-is (i.e.
488 // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
489 // which supports loading a unicode from a str, doesn't take this path.
490 template <typename C = CharT>
491 bool load_bytes(enable_if_t<std::is_same<C, char>::value, handle> src) {
492 if (PYBIND11_BYTES_CHECK(src.ptr())) {
493 // We were passed a Python 3 raw bytes; accept it into a std::string or char*
494 // without any encoding attempt.
495 const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
496 if (bytes) {
497 value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
498 return true;
499 }
500 }
501
502 return false;
503 }
504
505 template <typename C = CharT>
506 bool load_bytes(enable_if_t<!std::is_same<C, char>::value, handle>) {
507 return false;
508 }
509};
510
511template <typename CharT, class Traits, class Allocator>
512struct type_caster<std::basic_string<CharT, Traits, Allocator>,
513 enable_if_t<is_std_char_type<CharT>::value>>
514 : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
515
516#ifdef PYBIND11_HAS_STRING_VIEW
517template <typename CharT, class Traits>
518struct type_caster<std::basic_string_view<CharT, Traits>,
519 enable_if_t<is_std_char_type<CharT>::value>>
520 : string_caster<std::basic_string_view<CharT, Traits>, true> {};
521#endif
522
523// Type caster for C-style strings. We basically use a std::string type caster, but also add the
524// ability to use None as a nullptr char* (which the string caster doesn't allow).
525template <typename CharT>
527 using StringType = std::basic_string<CharT>;
530 bool none = false;
531 CharT one_char = 0;
532
533public:
534 bool load(handle src, bool convert) {
535 if (!src) {
536 return false;
537 }
538 if (src.is_none()) {
539 // Defer accepting None to other overloads (if we aren't in convert mode):
540 if (!convert) {
541 return false;
542 }
543 none = true;
544 return true;
545 }
546 return str_caster.load(src, convert);
547 }
548
549 static handle cast(const CharT *src, return_value_policy policy, handle parent) {
550 if (src == nullptr) {
551 return pybind11::none().inc_ref();
552 }
553 return StringCaster::cast(StringType(src), policy, parent);
554 }
555
556 static handle cast(CharT src, return_value_policy policy, handle parent) {
557 if (std::is_same<char, CharT>::value) {
558 handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
559 if (!s) {
560 throw error_already_set();
561 }
562 return s;
563 }
564 return StringCaster::cast(StringType(1, src), policy, parent);
565 }
566
567 explicit operator CharT *() {
568 return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
569 }
570 explicit operator CharT &() {
571 if (none) {
572 throw value_error("Cannot convert None to a character");
573 }
574
575 auto &value = static_cast<StringType &>(str_caster);
576 size_t str_len = value.size();
577 if (str_len == 0) {
578 throw value_error("Cannot convert empty string to a character");
579 }
580
581 // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
582 // is too high, and one for multiple unicode characters (caught later), so we need to
583 // figure out how long the first encoded character is in bytes to distinguish between these
584 // two errors. We also allow want to allow unicode characters U+0080 through U+00FF, as
585 // those can fit into a single char value.
586 if (PYBIND11_SILENCE_MSVC_C4127(StringCaster::UTF_N == 8) && str_len > 1 && str_len <= 4) {
587 auto v0 = static_cast<unsigned char>(value[0]);
588 // low bits only: 0-127
589 // 0b110xxxxx - start of 2-byte sequence
590 // 0b1110xxxx - start of 3-byte sequence
591 // 0b11110xxx - start of 4-byte sequence
592 size_t char0_bytes = (v0 & 0x80) == 0 ? 1
593 : (v0 & 0xE0) == 0xC0 ? 2
594 : (v0 & 0xF0) == 0xE0 ? 3
595 : 4;
596
597 if (char0_bytes == str_len) {
598 // If we have a 128-255 value, we can decode it into a single char:
599 if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
600 one_char = static_cast<CharT>(((v0 & 3) << 6)
601 + (static_cast<unsigned char>(value[1]) & 0x3F));
602 return one_char;
603 }
604 // Otherwise we have a single character, but it's > U+00FF
605 throw value_error("Character code point not in range(0x100)");
606 }
607 }
608
609 // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
610 // surrogate pair with total length 2 instantly indicates a range error (but not a "your
611 // string was too long" error).
612 else if (PYBIND11_SILENCE_MSVC_C4127(StringCaster::UTF_N == 16) && str_len == 2) {
613 one_char = static_cast<CharT>(value[0]);
614 if (one_char >= 0xD800 && one_char < 0xE000) {
615 throw value_error("Character code point not in range(0x10000)");
616 }
617 }
618
619 if (str_len != 1) {
620 throw value_error("Expected a character, but multi-character string found");
621 }
622
623 one_char = value[0];
624 return one_char;
625 }
626
627 static constexpr auto name = const_name(PYBIND11_STRING_NAME);
628 template <typename _T>
629 using cast_op_type = pybind11::detail::cast_op_type<_T>;
630};
631
632// Base implementation for std::tuple and std::pair
633template <template <typename...> class Tuple, typename... Ts>
635 using type = Tuple<Ts...>;
636 static constexpr auto size = sizeof...(Ts);
638
639public:
640 bool load(handle src, bool convert) {
641 if (!isinstance<sequence>(src)) {
642 return false;
643 }
644 const auto seq = reinterpret_borrow<sequence>(src);
645 if (seq.size() != size) {
646 return false;
647 }
648 return load_impl(seq, convert, indices{});
649 }
650
651 template <typename T>
652 static handle cast(T &&src, return_value_policy policy, handle parent) {
653 return cast_impl(std::forward<T>(src), policy, parent, indices{});
654 }
655
656 // copied from the PYBIND11_TYPE_CASTER macro
657 template <typename T>
658 static handle cast(T *src, return_value_policy policy, handle parent) {
659 if (!src) {
660 return none().release();
661 }
662 if (policy == return_value_policy::take_ownership) {
663 auto h = cast(std::move(*src), policy, parent);
664 delete src;
665 return h;
666 }
667 return cast(*src, policy, parent);
668 }
669
670 static constexpr auto name
671 = const_name("Tuple[") + concat(make_caster<Ts>::name...) + const_name("]");
672
673 template <typename T>
675
676 explicit operator type() & { return implicit_cast(indices{}); }
677 explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
678
679protected:
680 template <size_t... Is>
682 return type(cast_op<Ts>(std::get<Is>(subcasters))...);
683 }
684 template <size_t... Is>
686 return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
687 }
688
689 static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
690
691 template <size_t... Is>
692 bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
693#ifdef __cpp_fold_expressions
694 if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
695 return false;
696 }
697#else
698 for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
699 if (!r) {
700 return false;
701 }
702 }
703#endif
704 return true;
705 }
706
707 /* Implementation: Convert a C++ tuple into a Python tuple */
708 template <typename T, size_t... Is>
709 static handle
711 PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
713 std::array<object, size> entries{{reinterpret_steal<object>(
714 make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
715 for (const auto &entry : entries) {
716 if (!entry) {
717 return handle();
718 }
719 }
720 tuple result(size);
721 int counter = 0;
722 for (auto &entry : entries) {
723 PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
724 }
725 return result.release();
726 }
727
728 Tuple<make_caster<Ts>...> subcasters;
729};
730
731template <typename T1, typename T2>
732class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
733
734template <typename... Ts>
735class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
736
739template <typename T>
741 static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
742};
743
749template <typename type, typename holder_type, typename SFINAE = void>
751public:
753 static_assert(std::is_base_of<base, type_caster<type>>::value,
754 "Holder classes are only supported for custom types");
755 using base::base;
756 using base::cast;
757 using base::typeinfo;
758 using base::value;
759
760 bool load(handle src, bool convert) {
761 return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
762 }
763
764 explicit operator type *() { return this->value; }
765 // static_cast works around compiler error with MSVC 17 and CUDA 10.2
766 // see issue #2180
767 explicit operator type &() { return *(static_cast<type *>(this->value)); }
768 explicit operator holder_type *() { return std::addressof(holder); }
769 explicit operator holder_type &() { return holder; }
770
771 static handle cast(const holder_type &src, return_value_policy, handle) {
772 const auto *ptr = holder_helper<holder_type>::get(src);
773 return type_caster_base<type>::cast_holder(ptr, &src);
774 }
775
776protected:
780 throw cast_error("Unable to load a custom holder type from a default-holder instance");
781 }
782 }
783
785 if (v_h.holder_constructed()) {
786 value = v_h.value_ptr();
787 holder = v_h.template holder<holder_type>();
788 return true;
789 }
790 throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
791#if defined(NDEBUG)
792 "(compile in debug mode for type information)");
793#else
794 "of type '"
795 + type_id<holder_type>() + "''");
796#endif
797 }
798
799 template <typename T = holder_type,
800 detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
802 return false;
803 }
804
805 template <typename T = holder_type,
806 detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
807 bool try_implicit_casts(handle src, bool convert) {
808 for (auto &cast : typeinfo->implicit_casts) {
809 copyable_holder_caster sub_caster(*cast.first);
810 if (sub_caster.load(src, convert)) {
811 value = cast.second(sub_caster.value);
812 holder = holder_type(sub_caster.holder, (type *) value);
813 return true;
814 }
815 }
816 return false;
817 }
818
819 static bool try_direct_conversions(handle) { return false; }
820
821 holder_type holder;
822};
823
825template <typename T>
826class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
827
831template <typename type, typename holder_type, typename SFINAE = void>
833 static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
834 "Holder classes are only supported for custom types");
835
836 static handle cast(holder_type &&src, return_value_policy, handle) {
837 auto *ptr = holder_helper<holder_type>::get(src);
838 return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
839 }
840 static constexpr auto name = type_caster_base<type>::name;
841};
842
843template <typename type, typename deleter>
844class type_caster<std::unique_ptr<type, deleter>>
845 : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
846
847template <typename type, typename holder_type>
851
852template <typename T, bool Value = false>
854 static constexpr bool value = Value;
855};
856
858#define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
859 namespace pybind11 { \
860 namespace detail { \
861 template <typename type> \
862 struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { \
863 }; \
864 template <typename type> \
865 class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
866 : public type_caster_holder<type, holder_type> {}; \
867 } \
868 }
869
870// PYBIND11_DECLARE_HOLDER_TYPE holder types:
871template <typename base, typename holder>
873 : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
874// Specialization for always-supported unique_ptr holders:
875template <typename base, typename deleter>
876struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
877
878template <typename T>
880 static constexpr auto name = const_name<T>();
881};
882template <>
884 static constexpr auto name = const_name("bool");
885};
886template <>
888 static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
889};
890template <>
892 static constexpr auto name = const_name("int");
893};
894template <>
896 static constexpr auto name = const_name("Iterable");
897};
898template <>
900 static constexpr auto name = const_name("Iterator");
901};
902template <>
904 static constexpr auto name = const_name("float");
905};
906template <>
908 static constexpr auto name = const_name("None");
909};
910template <>
912 static constexpr auto name = const_name("*args");
913};
914template <>
916 static constexpr auto name = const_name("**kwargs");
917};
918
919template <typename type>
921 template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
922 bool load(handle src, bool /* convert */) {
923 value = src;
924 return static_cast<bool>(value);
925 }
926
927 template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
928 bool load(handle src, bool /* convert */) {
929#if PY_MAJOR_VERSION < 3 && !defined(PYBIND11_STR_LEGACY_PERMISSIVE)
930 // For Python 2, without this implicit conversion, Python code would
931 // need to be cluttered with six.ensure_text() or similar, only to be
932 // un-cluttered later after Python 2 support is dropped.
933 if (PYBIND11_SILENCE_MSVC_C4127(std::is_same<T, str>::value) && isinstance<bytes>(src)) {
934 PyObject *str_from_bytes = PyUnicode_FromEncodedObject(src.ptr(), "utf-8", nullptr);
935 if (!str_from_bytes)
936 throw error_already_set();
937 value = reinterpret_steal<type>(str_from_bytes);
938 return true;
939 }
940#endif
941 if (!isinstance<type>(src)) {
942 return false;
943 }
944 value = reinterpret_borrow<type>(src);
945 return true;
946 }
947
948 static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
949 return src.inc_ref();
950 }
952};
953
954template <typename T>
956
957// Our conditions for enabling moving are quite restrictive:
958// At compile time:
959// - T needs to be a non-const, non-pointer, non-reference type
960// - type_caster<T>::operator T&() must exist
961// - the type must be move constructible (obviously)
962// At run-time:
963// - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
964// must have ref_count() == 1)h
965// If any of the above are not satisfied, we fall back to copying.
966template <typename T>
969template <typename T, typename SFINAE = void>
970struct move_always : std::false_type {};
971template <typename T>
973 T,
977 std::is_move_constructible<T>,
978 std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
979 : std::true_type {};
980template <typename T, typename SFINAE = void>
981struct move_if_unreferenced : std::false_type {};
982template <typename T>
984 T,
988 std::is_move_constructible<T>,
989 std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
990 : std::true_type {};
991template <typename T>
993
994// Detect whether returning a `type` from a cast on type's type_caster is going to result in a
995// reference or pointer to a local variable of the type_caster. Basically, only
996// non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
997// everything else returns a reference/pointer to a local variable.
998template <typename type>
1000 = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
1001 && !std::is_base_of<type_caster_generic, make_caster<type>>::value
1002 && !std::is_same<intrinsic_t<type>, void>::value>;
1003
1004// When a value returned from a C++ function is being cast back to Python, we almost always want to
1005// force `policy = move`, regardless of the return value policy the function/method was declared
1006// with.
1007template <typename Return, typename SFINAE = void>
1010};
1011
1012template <typename Return>
1014 Return,
1015 detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1017 return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
1018 ? return_value_policy::move
1019 : p;
1020 }
1021};
1022
1023// Basic python -> C++ casting; throws if casting fails
1024template <typename T, typename SFINAE>
1026 if (!conv.load(handle, true)) {
1027#if defined(NDEBUG)
1028 throw cast_error(
1029 "Unable to cast Python instance to C++ type (compile in debug mode for details)");
1030#else
1031 throw cast_error("Unable to cast Python instance of type "
1032 + (std::string) str(type::handle_of(handle)) + " to C++ type '"
1033 + type_id<T>() + "'");
1034#endif
1035 }
1036 return conv;
1037}
1038// Wrapper around the above that also constructs and returns a type_caster
1039template <typename T>
1041 make_caster<T> conv;
1042 load_type(conv, handle);
1043 return conv;
1044}
1045
1047
1048// pytype -> C++ type
1049template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1050T cast(const handle &handle) {
1051 using namespace detail;
1053 "Unable to cast type to reference: value is local to type caster");
1054 return cast_op<T>(load_type<T>(handle));
1055}
1056
1057// pytype -> pytype (calls converting constructor)
1058template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
1059T cast(const handle &handle) {
1060 return T(reinterpret_borrow<object>(handle));
1061}
1062
1063// C++ type -> py::object
1064template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1065object cast(T &&value,
1067 handle parent = handle()) {
1068 using no_ref_T = typename std::remove_reference<T>::type;
1069 if (policy == return_value_policy::automatic) {
1070 policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
1071 : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1073 } else if (policy == return_value_policy::automatic_reference) {
1074 policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
1075 : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1077 }
1078 return reinterpret_steal<object>(
1079 detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
1080}
1081
1082template <typename T>
1083T handle::cast() const {
1084 return pybind11::cast<T>(*this);
1085}
1086template <>
1087inline void handle::cast() const {
1088 return;
1089}
1090
1091template <typename T>
1092detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
1093 if (obj.ref_count() > 1) {
1094#if defined(NDEBUG)
1095 throw cast_error(
1096 "Unable to cast Python instance to C++ rvalue: instance has multiple references"
1097 " (compile in debug mode for details)");
1098#else
1099 throw cast_error("Unable to move from Python " + (std::string) str(type::handle_of(obj))
1100 + " instance to C++ " + type_id<T>()
1101 + " instance: instance has multiple references");
1102#endif
1103 }
1104
1105 // Move into a temporary and return that, because the reference may be a local value of `conv`
1106 T ret = std::move(detail::load_type<T>(obj).operator T &());
1107 return ret;
1108}
1109
1110// Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
1111// - If we have to move (because T has no copy constructor), do it. This will fail if the moved
1112// object has multiple references, but trying to copy will fail to compile.
1113// - If both movable and copyable, check ref count: if 1, move; otherwise copy
1114// - Otherwise (not movable), copy.
1115template <typename T>
1116detail::enable_if_t<detail::move_always<T>::value, T> cast(object &&object) {
1117 return move<T>(std::move(object));
1118}
1119template <typename T>
1120detail::enable_if_t<detail::move_if_unreferenced<T>::value, T> cast(object &&object) {
1121 if (object.ref_count() > 1) {
1122 return cast<T>(object);
1123 }
1124 return move<T>(std::move(object));
1125}
1126template <typename T>
1127detail::enable_if_t<detail::move_never<T>::value, T> cast(object &&object) {
1128 return cast<T>(object);
1129}
1130
1131template <typename T>
1132T object::cast() const & {
1133 return pybind11::cast<T>(*this);
1134}
1135template <typename T>
1137 return pybind11::cast<T>(std::move(*this));
1138}
1139template <>
1140inline void object::cast() const & {
1141 return;
1142}
1143template <>
1144inline void object::cast() && {
1145 return;
1146}
1147
1149
1150// Declared in pytypes.h:
1151template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
1152object object_or_cast(T &&o) {
1153 return pybind11::cast(std::forward<T>(o));
1154}
1155
1156// Placeholder type for the unneeded (and dead code) static variable in the
1157// PYBIND11_OVERRIDE_OVERRIDE macro
1159template <typename ret_type>
1163
1164// Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
1165// store the result in the given variable. For other types, this is a no-op.
1166template <typename T>
1168 make_caster<T> &caster) {
1169 return cast_op<T>(load_type(caster, o));
1170}
1171template <typename T>
1173 override_unused &) {
1174 pybind11_fail("Internal error: cast_ref fallback invoked");
1175}
1176
1177// Trampoline use: Having a pybind11::cast with an invalid reference type is going to
1178// static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
1179// that only does anything in cases where pybind11::cast is valid.
1180template <typename T>
1182 return pybind11::cast<T>(std::move(o));
1183}
1184template <typename T>
1186 pybind11_fail("Internal error: cast_safe fallback invoked");
1187}
1188template <>
1189inline void cast_safe<void>(object &&) {}
1190
1192
1193// The overloads could coexist, i.e. the #if is not strictly speaking needed,
1194// but it is an easy minor optimization.
1195#if defined(NDEBUG)
1196inline cast_error cast_error_unable_to_convert_call_arg() {
1197 return cast_error(
1198 "Unable to convert call argument to Python object (compile in debug mode for details)");
1199}
1200#else
1201inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
1202 const std::string &type) {
1203 return cast_error("Unable to convert call argument '" + name + "' of type '" + type
1204 + "' to Python object");
1205}
1206#endif
1207
1208template <return_value_policy policy = return_value_policy::automatic_reference>
1210 return tuple(0);
1211}
1212
1213template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1214tuple make_tuple(Args &&...args_) {
1215 constexpr size_t size = sizeof...(Args);
1216 std::array<object, size> args{{reinterpret_steal<object>(
1217 detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
1218 for (size_t i = 0; i < args.size(); i++) {
1219 if (!args[i]) {
1220#if defined(NDEBUG)
1222#else
1223 std::array<std::string, size> argtypes{{type_id<Args>()...}};
1224 throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
1225#endif
1226 }
1227 }
1228 tuple result(size);
1229 int counter = 0;
1230 for (auto &arg_value : args) {
1231 PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1232 }
1233 return result;
1234}
1235
1238struct arg {
1241 constexpr explicit arg(const char *name = nullptr)
1242 : name(name), flag_noconvert(false), flag_none(true) {}
1244 template <typename T>
1245 arg_v operator=(T &&value) const;
1247 arg &noconvert(bool flag = true) {
1248 flag_noconvert = flag;
1249 return *this;
1250 }
1252 arg &none(bool flag = true) {
1253 flag_none = flag;
1254 return *this;
1255 }
1256
1257 const char *name;
1260 bool flag_none : 1;
1261};
1262
1265struct arg_v : arg {
1266private:
1267 template <typename T>
1268 arg_v(arg &&base, T &&x, const char *descr = nullptr)
1270 detail::make_caster<T>::cast(x, return_value_policy::automatic, {}))),
1271 descr(descr)
1272#if !defined(NDEBUG)
1273 ,
1274 type(type_id<T>())
1275#endif
1276 {
1277 // Workaround! See:
1278 // https://github.com/pybind/pybind11/issues/2336
1279 // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
1280 if (PyErr_Occurred()) {
1281 PyErr_Clear();
1282 }
1283 }
1284
1285public:
1287 template <typename T>
1288 arg_v(const char *name, T &&x, const char *descr = nullptr)
1289 : arg_v(arg(name), std::forward<T>(x), descr) {}
1290
1292 template <typename T>
1293 arg_v(const arg &base, T &&x, const char *descr = nullptr)
1294 : arg_v(arg(base), std::forward<T>(x), descr) {}
1295
1297 arg_v &noconvert(bool flag = true) {
1298 arg::noconvert(flag);
1299 return *this;
1300 }
1301
1303 arg_v &none(bool flag = true) {
1304 arg::none(flag);
1305 return *this;
1306 }
1307
1309 object value;
1311 const char *descr;
1312#if !defined(NDEBUG)
1314 std::string type;
1315#endif
1316};
1317
1321struct kw_only {};
1322
1326struct pos_only {};
1327
1328template <typename T>
1329arg_v arg::operator=(T &&value) const {
1330 return {*this, std::forward<T>(value)};
1331}
1332
1334template <typename /*unused*/>
1335using arg_t = arg_v;
1336
1337inline namespace literals {
1341constexpr arg operator"" _a(const char *name, size_t) { return arg(name); }
1342} // namespace literals
1343
1345
1346template <typename T>
1347using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
1348template <typename T>
1349using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
1350
1351// forward declaration (definition in attr.h)
1352struct function_record;
1353
1356 function_call(const function_record &f, handle p); // Implementation in attr.h
1357
1360
1362 std::vector<handle> args;
1363
1365 std::vector<bool> args_convert;
1366
1370
1373
1376};
1377
1379template <typename... Args>
1381 using indices = make_index_sequence<sizeof...(Args)>;
1382
1383 template <typename Arg>
1384 using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
1385 template <typename Arg>
1386 using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
1387 // Get kwargs argument position, or -1 if not present:
1388 static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
1389
1390 static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
1391 "py::kwargs is only permitted as the last argument of a function");
1392
1393public:
1394 static constexpr bool has_kwargs = kwargs_pos != -1;
1395
1396 // py::args argument position; -1 if not present.
1397 static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
1398
1399 static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
1400 "py::args cannot be specified more than once");
1401
1403
1405
1406 template <typename Return, typename Guard, typename Func>
1407 // NOLINTNEXTLINE(readability-const-return-type)
1409 return std::move(*this).template call_impl<remove_cv_t<Return>>(
1410 std::forward<Func>(f), indices{}, Guard{});
1411 }
1412
1413 template <typename Return, typename Guard, typename Func>
1415 std::move(*this).template call_impl<remove_cv_t<Return>>(
1416 std::forward<Func>(f), indices{}, Guard{});
1417 return void_type();
1418 }
1419
1420private:
1421 static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
1422
1423 template <size_t... Is>
1425#ifdef __cpp_fold_expressions
1426 if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
1427 return false;
1428 }
1429#else
1430 for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
1431 if (!r) {
1432 return false;
1433 }
1434 }
1435#endif
1436 return true;
1437 }
1438
1439 template <typename Return, typename Func, size_t... Is, typename Guard>
1440 Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
1441 return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
1442 }
1443
1444 std::tuple<make_caster<Args>...> argcasters;
1445};
1446
1449template <return_value_policy policy>
1451public:
1452 template <typename... Ts>
1453 explicit simple_collector(Ts &&...values)
1454 : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) {}
1455
1456 const tuple &args() const & { return m_args; }
1457 dict kwargs() const { return {}; }
1458
1459 tuple args() && { return std::move(m_args); }
1460
1462 object call(PyObject *ptr) const {
1463 PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
1464 if (!result) {
1465 throw error_already_set();
1466 }
1467 return reinterpret_steal<object>(result);
1468 }
1469
1470private:
1472};
1473
1475template <return_value_policy policy>
1477public:
1478 template <typename... Ts>
1479 explicit unpacking_collector(Ts &&...values) {
1480 // Tuples aren't (easily) resizable so a list is needed for collection,
1481 // but the actual function call strictly requires a tuple.
1482 auto args_list = list();
1483 using expander = int[];
1484 (void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...};
1485
1486 m_args = std::move(args_list);
1487 }
1488
1489 const tuple &args() const & { return m_args; }
1490 const dict &kwargs() const & { return m_kwargs; }
1491
1492 tuple args() && { return std::move(m_args); }
1493 dict kwargs() && { return std::move(m_kwargs); }
1494
1496 object call(PyObject *ptr) const {
1497 PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
1498 if (!result) {
1499 throw error_already_set();
1500 }
1501 return reinterpret_steal<object>(result);
1502 }
1503
1504private:
1505 template <typename T>
1506 void process(list &args_list, T &&x) {
1507 auto o = reinterpret_steal<object>(
1508 detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
1509 if (!o) {
1510#if defined(NDEBUG)
1512#else
1513 throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()),
1514 type_id<T>());
1515#endif
1516 }
1517 args_list.append(o);
1518 }
1519
1520 void process(list &args_list, detail::args_proxy ap) {
1521 for (auto a : ap) {
1522 args_list.append(a);
1523 }
1524 }
1525
1526 void process(list & /*args_list*/, arg_v a) {
1527 if (!a.name) {
1528#if defined(NDEBUG)
1530#else
1532#endif
1533 }
1534 if (m_kwargs.contains(a.name)) {
1535#if defined(NDEBUG)
1537#else
1539#endif
1540 }
1541 if (!a.value) {
1542#if defined(NDEBUG)
1544#else
1546#endif
1547 }
1548 m_kwargs[a.name] = a.value;
1549 }
1550
1551 void process(list & /*args_list*/, detail::kwargs_proxy kp) {
1552 if (!kp) {
1553 return;
1554 }
1555 for (auto k : reinterpret_borrow<dict>(kp)) {
1556 if (m_kwargs.contains(k.first)) {
1557#if defined(NDEBUG)
1559#else
1560 multiple_values_error(str(k.first));
1561#endif
1562 }
1563 m_kwargs[k.first] = k.second;
1564 }
1565 }
1566
1567 [[noreturn]] static void nameless_argument_error() {
1568 throw type_error("Got kwargs without a name; only named arguments "
1569 "may be passed via py::arg() to a python function call. "
1570 "(compile in debug mode for details)");
1571 }
1572 [[noreturn]] static void nameless_argument_error(const std::string &type) {
1573 throw type_error("Got kwargs without a name of type '" + type
1574 + "'; only named "
1575 "arguments may be passed via py::arg() to a python function call. ");
1576 }
1577 [[noreturn]] static void multiple_values_error() {
1578 throw type_error("Got multiple values for keyword argument "
1579 "(compile in debug mode for details)");
1580 }
1581
1582 [[noreturn]] static void multiple_values_error(const std::string &name) {
1583 throw type_error("Got multiple values for keyword argument '" + name + "'");
1584 }
1585
1586private:
1589};
1590
1591// [workaround(intel)] Separate function required here
1592// We need to put this into a separate function because the Intel compiler
1593// fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
1594// (tested with ICC 2021.1 Beta 20200827).
1595template <typename... Args>
1596constexpr bool args_are_all_positional() {
1597 return all_of<is_positional<Args>...>::value;
1598}
1599
1601template <return_value_policy policy,
1602 typename... Args,
1603 typename = enable_if_t<args_are_all_positional<Args...>()>>
1605 return simple_collector<policy>(std::forward<Args>(args)...);
1606}
1607
1609template <return_value_policy policy,
1610 typename... Args,
1611 typename = enable_if_t<!args_are_all_positional<Args...>()>>
1613 // Following argument order rules for generalized unpacking according to PEP 448
1614 static_assert(constexpr_last<is_positional, Args...>()
1615 < constexpr_first<is_keyword_or_ds, Args...>()
1616 && constexpr_last<is_s_unpacking, Args...>()
1617 < constexpr_first<is_ds_unpacking, Args...>(),
1618 "Invalid function call: positional args must precede keywords and ** unpacking; "
1619 "* unpacking must precede ** unpacking");
1620 return unpacking_collector<policy>(std::forward<Args>(args)...);
1621}
1622
1623template <typename Derived>
1624template <return_value_policy policy, typename... Args>
1625object object_api<Derived>::operator()(Args &&...args) const {
1626#if !defined(NDEBUG) && PY_VERSION_HEX >= 0x03060000
1627 if (!PyGILState_Check()) {
1628 pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
1629 }
1630#endif
1631 return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
1632}
1633
1634template <typename Derived>
1635template <return_value_policy policy, typename... Args>
1636object object_api<Derived>::call(Args &&...args) const {
1637 return operator()<policy>(std::forward<Args>(args)...);
1638}
1639
1641
1642template <typename T>
1644 static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
1645 "py::type::of<T> only supports the case where T is a registered C++ types.");
1646
1647 return detail::get_type_handle(typeid(T), true);
1648}
1649
1650#define PYBIND11_MAKE_OPAQUE(...) \
1651 namespace pybind11 { \
1652 namespace detail { \
1653 template <> \
1654 class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
1655 } \
1656 }
1657
1661#define PYBIND11_TYPE(...) __VA_ARGS__
1662
Definition: pytypes.h:1776
Helper class which loads arguments for C++ functions called from Python.
Definition: cast.h:1380
bool load_impl_sequence(function_call &call, index_sequence< Is... >)
Definition: cast.h:1424
Return call_impl(Func &&f, index_sequence< Is... >, Guard &&) &&
Definition: cast.h:1440
enable_if_t< std::is_void< Return >::value, void_type > call(Func &&f) &&
Definition: cast.h:1414
std::is_same< intrinsic_t< Arg >, args > argument_is_args
Definition: cast.h:1384
static bool load_impl_sequence(function_call &, index_sequence<>)
Definition: cast.h:1421
make_index_sequence< sizeof...(Args)> indices
Definition: cast.h:1381
static constexpr auto arg_names
Definition: cast.h:1402
std::tuple< make_caster< Args >... > argcasters
Definition: cast.h:1444
static constexpr int args_pos
Definition: cast.h:1397
std::is_same< intrinsic_t< Arg >, kwargs > argument_is_kwargs
Definition: cast.h:1386
bool load_args(function_call &call)
Definition: cast.h:1404
enable_if_t<!std::is_void< Return >::value, Return > call(Func &&f) &&
Definition: cast.h:1408
static constexpr auto kwargs_pos
Definition: cast.h:1388
static constexpr bool has_kwargs
Definition: cast.h:1394
Definition: pytypes.h:1694
bool contains(T &&key) const
Definition: pytypes.h:1715
Fetch and hold an error which was already set in Python.
Definition: pytypes.h:379
\rst Holds a reference to a Python object (no reference counting)
Definition: pytypes.h:194
const handle & inc_ref() const &
\rst Manually increase the reference count of the Python object.
Definition: pytypes.h:211
T cast() const
\rst Attempt to cast the Python object into the given C++ type.
Definition: cast.h:1083
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:203
Definition: pytypes.h:1475
\rst Wraps a Python iterator so that it can also be used as a C++ input iterator
Definition: pytypes.h:1102
Definition: pytypes.h:1746
void append(T &&val)
Definition: pytypes.h:1764
size_t size() const
Definition: pytypes.h:1757
static PYBIND11_NOINLINE void add_patient(handle h)
This can only be used inside a pybind11-bound function, either by argument_loader at argument prepara...
Definition: pytypes.h:1422
\rst A mixin class which adds common functions to handle, object and various accessors.
Definition: pytypes.h:69
object operator()(Args &&...args) const
\rst Assuming the Python object is a function or implements the __call__ protocol,...
Definition: cast.h:1625
\rst Holds a reference to a Python object (with reference counting)
Definition: pytypes.h:259
handle release()
\rst Resets the internal pointer to nullptr without decreasing the object's reference count.
Definition: pytypes.h:283
Helper class which collects only positional arguments for a Python function call.
Definition: cast.h:1450
simple_collector(Ts &&...values)
Definition: cast.h:1453
dict kwargs() const
Definition: cast.h:1457
object call(PyObject *ptr) const
Call a Python function and pass the collected arguments.
Definition: cast.h:1462
tuple args() &&
Definition: cast.h:1459
const tuple & args() const &
Definition: cast.h:1456
tuple m_args
Definition: cast.h:1471
Definition: pytypes.h:1200
static handle cast(T *src, return_value_policy policy, handle parent)
Definition: cast.h:658
static constexpr auto size
Definition: cast.h:636
type cast_op_type
Definition: cast.h:674
type implicit_cast(index_sequence< Is... >) &&
Definition: cast.h:685
bool load(handle src, bool convert)
Definition: cast.h:640
static constexpr bool load_impl(const sequence &, bool, index_sequence<>)
Definition: cast.h:689
static handle cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence< Is... >)
Definition: cast.h:710
bool load_impl(const sequence &seq, bool convert, index_sequence< Is... >)
Definition: cast.h:692
type implicit_cast(index_sequence< Is... >) &
Definition: cast.h:681
Tuple< make_caster< Ts >... > subcasters
Definition: cast.h:728
static handle cast(T &&src, return_value_policy policy, handle parent)
Definition: cast.h:652
Tuple< Ts... > type
Definition: cast.h:635
make_index_sequence< size > indices
Definition: cast.h:637
size_t size() const
Definition: pytypes.h:1678
PYBIND11_TYPE_CASTER(bool, const_name("bool"))
bool load(handle src, bool convert)
Definition: cast.h:312
static handle cast(bool src, return_value_policy, handle)
Definition: cast.h:353
static handle cast(const std::reference_wrapper< type > &src, return_value_policy policy, handle parent)
Definition: cast.h:69
std::reference_wrapper< type > cast_op_type
Definition: cast.h:78
typename caster_t::template cast_op_type< reference_t > subcaster_cast_op_type
Definition: cast.h:57
bool load(handle src, bool convert)
Definition: cast.h:66
bool load(handle h, bool)
Definition: cast.h:264
void *& cast_op_type
Definition: cast.h:298
static handle cast(const void *ptr, return_value_policy, handle)
Definition: cast.h:290
Generic type caster for objects stored on the heap.
static handle cast_holder(const itype *src, const void *holder)
static handle cast(const itype &src, return_value_policy policy, handle parent)
const type_info * typeinfo
static PYBIND11_NOINLINE handle cast(const void *_src, return_value_policy policy, handle parent, const detail::type_info *tinfo, void *(*copy_constructor)(const void *), void *(*move_constructor)(const void *), const void *existing_holder=nullptr)
bool load(handle src, bool convert)
Definition: pytypes.h:1167
static handle handle_of()
Convert C++ type to handle if previously registered.
Definition: cast.h:1643
Helper class which collects positional, keyword, * and ** arguments for a Python function call.
Definition: cast.h:1476
static void multiple_values_error()
Definition: cast.h:1577
static void nameless_argument_error()
Definition: cast.h:1567
static void multiple_values_error(const std::string &name)
Definition: cast.h:1582
void process(list &, detail::kwargs_proxy kp)
Definition: cast.h:1551
object call(PyObject *ptr) const
Call a Python function and pass the collected arguments.
Definition: cast.h:1496
const tuple & args() const &
Definition: cast.h:1489
unpacking_collector(Ts &&...values)
Definition: cast.h:1479
const dict & kwargs() const &
Definition: cast.h:1490
tuple args() &&
Definition: cast.h:1492
void process(list &args_list, detail::args_proxy ap)
Definition: cast.h:1520
static void nameless_argument_error(const std::string &type)
Definition: cast.h:1572
void process(list &args_list, T &&x)
Definition: cast.h:1506
dict kwargs() &&
Definition: cast.h:1493
void process(list &, arg_v a)
Definition: cast.h:1526
bool hasattr(handle obj, handle name)
Definition: pytypes.h:517
conditional_t< is_copy_constructible< holder_type >::value, copyable_holder_caster< type, holder_type >, move_only_holder_caster< type, holder_type > > type_caster_holder
Definition: cast.h:850
std::is_same< intrinsic_t< T >, pos_only > is_pos_only
Definition: cast.h:1349
bool_constant<(std::is_reference< type >::value||std::is_pointer< type >::value) &&!std::is_base_of< type_caster_generic, make_caster< type > >::value &&!std::is_same< intrinsic_t< type >, void >::value > cast_is_temporary_value_reference
Definition: cast.h:1002
constexpr bool args_are_all_positional()
Definition: cast.h:1596
T cast(const handle &handle)
Definition: cast.h:1050
cast_error cast_error_unable_to_convert_call_arg(const std::string &name, const std::string &type)
Definition: cast.h:1201
object object_or_cast(T &&o)
Definition: cast.h:1152
conditional_t< cast_is_temporary_value_reference< ret_type >::value, make_caster< ret_type >, override_unused > override_caster_t
Definition: cast.h:1162
enable_if_t< cast_is_temporary_value_reference< T >::value, T > cast_ref(object &&o, make_caster< T > &caster)
Definition: cast.h:1167
tuple make_tuple()
Definition: cast.h:1209
enable_if_t<!cast_is_temporary_value_reference< T >::value, T > cast_safe(object &&o)
Definition: cast.h:1181
void cast_safe< void >(object &&)
Definition: cast.h:1189
make_caster< T >::template cast_op_type< T > cast_op(make_caster< T > &caster)
Definition: cast.h:41
simple_collector< policy > collect_arguments(Args &&...args)
Collect only positional arguments for a Python function call.
Definition: cast.h:1604
std::is_same< intrinsic_t< T >, kw_only > is_kw_only
Definition: cast.h:1347
type_caster< T, SFINAE > & load_type(type_caster< T, SFINAE > &conv, const handle &handle)
Definition: cast.h:1025
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
Definition: common.h:625
std::integral_constant< bool, B > bool_constant
Backports of std::bool_constant and std::negation to accommodate older compilers.
Definition: common.h:678
#define PYBIND11_LONG_AS_LONGLONG(o)
Definition: common.h:312
PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Thrown when pybind11::cast or.
Definition: common.h:992
constexpr int constexpr_first()
Return the index of the first type in Ts which satisfies Predicate<T>.
Definition: common.h:811
typename intrinsic_type< T >::type intrinsic_t
Definition: common.h:770
#define PYBIND11_STRING_NAME
Definition: common.h:317
#define PYBIND11_BYTES_SIZE
Definition: common.h:310
std::size_t size_t
Definition: common.h:461
#define PYBIND11_BYTES_CHECK
Definition: common.h:305
#define PYBIND11_LONG_CHECK(o)
Definition: common.h:311
typename std::remove_cv< T >::type remove_cv_t
Definition: common.h:629
#define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
Definition: common.h:1187
#define PYBIND11_NAMESPACE_END(name)
Definition: common.h:21
#define PYBIND11_BYTES_NAME
Definition: common.h:316
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: common.h:20
#define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)
Definition: common.h:1195
#define PYBIND11_BYTES_AS_STRING
Definition: common.h:309
typename make_index_sequence_impl< N >::type make_index_sequence
Definition: common.h:660
Py_ssize_t ssize_t
Definition: common.h:460
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... > > all_of
Definition: common.h:707
typename std::conditional< B, T, F >::type conditional_t
Definition: common.h:627
#define PYBIND11_BOOL_ATTR
Definition: common.h:321
constexpr int constexpr_last()
Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
Definition: common.h:817
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
Definition: common.h:470
@ copy
Create a new copy of the returned object, which will be owned by Python.
@ automatic_reference
As above, but use policy return_value_policy::reference when the return value is a pointer.
@ automatic
This is the default return value policy, which falls back to the policy return_value_policy::take_own...
@ move
Use std::move to move the return value contents into a new instance that will be owned by Python.
@ take_ownership
Reference an existing object (i.e.
@ reference
Reference an existing object, but do not take ownership.
#define PYBIND11_LONG_FROM_UNSIGNED(o)
Definition: common.h:315
#define PYBIND11_SILENCE_MSVC_C4127(...)
Definition: common.h:1206
#define PYBIND11_NB_BOOL(ptr)
Definition: common.h:322
#define PYBIND11_LONG_FROM_SIGNED(o)
Definition: common.h:314
constexpr descr< N - 1 > const_name(char const (&text)[N])
Definition: descr.h:60
constexpr descr< N+2, Ts... > type_descr(const descr< N, Ts... > &descr)
Definition: descr.h:153
constexpr descr< 0 > concat()
Definition: descr.h:139
const char * c_str(Args &&...args)
Constructs a std::string with the given arguments, stores it in internals, and returns its c_str().
Definition: internals.h:534
conditional_t< std::is_pointer< remove_reference_t< T > >::value, typename std::add_pointer< intrinsic_t< T > >::type, typename std::add_lvalue_reference< intrinsic_t< T > >::type > cast_op_type
Determine suitable casting operator for pointer-or-lvalue-casting type casters.
const std::vector< detail::type_info * > & all_type_info(PyTypeObject *type)
Extracts vector of type_info pointers of pybind-registered roots of the given Python type.
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
Definition: pytypes.h:62
T reinterpret_steal(handle h)
\rst Like reinterpret_borrow, but steals the reference.
Definition: pytypes.h:361
std::is_same< args_proxy, T > is_s_unpacking
Definition: pytypes.h:1016
satisfies_none_of< T, is_keyword, is_s_unpacking, is_ds_unpacking > is_positional
Definition: pytypes.h:1020
T cast(const handle &handle)
Definition: cast.h:1042
cast_error cast_error_unable_to_convert_call_arg(const std::string &name, const std::string &type)
Definition: cast.h:1203
tuple make_tuple()
Definition: cast.h:1211
static constexpr bool value
Definition: cast.h:854
Annotation for arguments with values.
Definition: cast.h:1265
arg_v(const arg &base, T &&x, const char *descr=nullptr)
Called internally when invoking py::arg("a") = value
Definition: cast.h:1293
arg_v & none(bool flag=true)
Same as arg::nonone(), but returns *this as arg_v&, not arg&.
Definition: cast.h:1303
arg_v & noconvert(bool flag=true)
Same as arg::noconvert(), but returns *this as arg_v&, not arg&.
Definition: cast.h:1297
object value
The default value.
Definition: cast.h:1309
std::string type
The C++ type name of the default value (only available when compiled in debug mode)
Definition: cast.h:1314
arg_v(const char *name, T &&x, const char *descr=nullptr)
Direct construction with name, default, and description.
Definition: cast.h:1288
arg_v(arg &&base, T &&x, const char *descr=nullptr)
Definition: cast.h:1268
const char * descr
The (optional) description of the default value.
Definition: cast.h:1311
Annotation for arguments.
Definition: cast.h:1238
arg & noconvert(bool flag=true)
Indicate that the type should not be converted in the type caster.
Definition: cast.h:1247
const char * name
If non-null, this is a named kwargs argument.
Definition: cast.h:1257
arg & none(bool flag=true)
Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
Definition: cast.h:1252
bool flag_none
If set (the default), allow None to be passed to this argument.
Definition: cast.h:1260
constexpr arg(const char *name=nullptr)
Constructs an argument with the name of the argument; if null or omitted, this is a positional argume...
Definition: cast.h:1241
arg_v operator=(T &&value) const
Assign a value to this argument.
Definition: cast.h:1329
bool flag_noconvert
If set, do not allow conversion (requires a supporting type caster!)
Definition: cast.h:1258
Annotation indicating that a class derives from another given type.
Definition: attr.h:60
Type caster for holder types like std::shared_ptr, etc.
Definition: cast.h:750
bool load_value(value_and_holder &&v_h)
Definition: cast.h:784
bool load(handle src, bool convert)
Definition: cast.h:760
void check_holder_compat()
Definition: cast.h:778
holder_type holder
Definition: cast.h:821
static bool try_direct_conversions(handle)
Definition: cast.h:819
bool try_implicit_casts(handle src, bool convert)
Definition: cast.h:807
bool try_implicit_casts(handle, bool)
Definition: cast.h:801
static handle cast(const holder_type &src, return_value_policy, handle)
Definition: cast.h:771
Definition: descr.h:25
Internal data associated with a single function call.
Definition: cast.h:1355
object args_ref
Extra references for the optional py::args and/or py::kwargs arguments (which, if present,...
Definition: cast.h:1369
object kwargs_ref
Definition: cast.h:1369
handle parent
The parent, if any.
Definition: cast.h:1372
std::vector< bool > args_convert
The convert value the arguments should be loaded with.
Definition: cast.h:1365
handle init_self
If this is a call to an initializer, this argument contains self
Definition: cast.h:1375
const function_record & func
The function data:
Definition: cast.h:1359
std::vector< handle > args
Arguments passed to the function:
Definition: cast.h:1362
Internal data structure which holds metadata about a bound function (signature, overloads,...
Definition: attr.h:188
Helper class which abstracts away certain actions.
Definition: cast.h:740
static auto get(const T &p) -> decltype(p.get())
Definition: cast.h:741
Index sequences.
Definition: common.h:652
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
Definition: common.h:554
Annotation indicating that all following arguments are keyword-only; the is the equivalent of an unna...
Definition: cast.h:1321
Type caster for holder types like std::unique_ptr.
Definition: cast.h:832
static handle cast(holder_type &&src, return_value_policy, handle)
Definition: cast.h:836
Annotation for function names.
Definition: attr.h:47
Annotation indicating that all previous arguments are positional-only; the is the equivalent of an un...
Definition: cast.h:1326
PYBIND11_TYPE_CASTER(type, handle_type_name< type >::name)
bool load(handle src, bool)
Definition: cast.h:922
static handle cast(const handle &src, return_value_policy, handle)
Definition: cast.h:948
static return_value_policy policy(return_value_policy p)
Definition: cast.h:1009
typename StringType::value_type CharT
Definition: cast.h:362
static handle decode_utfN(const char *buffer, ssize_t nbytes)
Definition: cast.h:469
static constexpr size_t UTF_N
Definition: cast.h:379
bool load(handle src, bool)
Definition: cast.h:381
static handle cast(const StringType &src, return_value_policy, handle)
Definition: cast.h:456
bool load_bytes(enable_if_t< std::is_same< C, char >::value, handle > src)
Definition: cast.h:491
bool load_bytes(enable_if_t<!std::is_same< C, char >::value, handle >)
Definition: cast.h:506
PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME))
static handle cast(const CharT *src, return_value_policy policy, handle parent)
Definition: cast.h:549
static handle cast(CharT src, return_value_policy policy, handle parent)
Definition: cast.h:556
conditional_t< sizeof(T)<=sizeof(long), long, long long > _py_type_0
Definition: cast.h:121
static std::enable_if<!std::is_floating_point< U >::value &&std::is_unsigned< U >::value &&(sizeof(U)>sizeof(unsignedlong)), handle >::type cast(U src, return_value_policy, handle)
Definition: cast.h:234
conditional_t< std::is_floating_point< T >::value, double, _py_type_1 > py_type
Definition: cast.h:125
static std::enable_if<!std::is_floating_point< U >::value &&std::is_signed< U >::value &&(sizeof(U)>sizeof(long)), handle >::type cast(U src, return_value_policy, handle)
Definition: cast.h:226
PYBIND11_TYPE_CASTER(T, const_name< std::is_integral< T >::value >("int", "float"))
static std::enable_if<!std::is_floating_point< U >::value &&std::is_unsigned< U >::value &&(sizeof(U)<=sizeof(unsignedlong)), handle >::type cast(U src, return_value_policy, handle)
Definition: cast.h:218
static std::enable_if<!std::is_floating_point< U >::value &&std::is_signed< U >::value &&(sizeof(U)<=sizeof(long)), handle >::type cast(U src, return_value_policy, handle)
Definition: cast.h:210
static std::enable_if< std::is_floating_point< U >::value, handle >::type cast(U src, return_value_policy, handle)
Definition: cast.h:202
conditional_t< std::is_signed< T >::value, _py_type_0, typename std::make_unsigned< _py_type_0 >::type > _py_type_1
Definition: cast.h:124
std::vector< std::pair< const std::type_info *, void *(*)(void *)> > implicit_casts
Definition: internals.h:204
bool default_holder
Definition: internals.h:217
V *& value_ptr() const
PYBIND11_TYPE_CASTER(T, const_name("None"))
static handle cast(T, return_value_policy, handle)
Definition: cast.h:250
bool load(handle src, bool)
Definition: cast.h:244
Helper type to replace 'void' in some expressions.
Definition: common.h:773