μHAL (v2.8.17)
Part of the IPbus software repository
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
pybind11.h
Go to the documentation of this file.
1/*
2 pybind11/pybind11.h: Main header file of the C++11 python
3 binding generator library
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/class.h"
14#include "detail/init.h"
15#include "attr.h"
16#include "gil.h"
17#include "options.h"
18
19#include <cstdlib>
20#include <cstring>
21#include <memory>
22#include <new>
23#include <string>
24#include <utility>
25#include <vector>
26
27#if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914))
28# define PYBIND11_STD_LAUNDER std::launder
29# define PYBIND11_HAS_STD_LAUNDER 1
30#else
31# define PYBIND11_STD_LAUNDER
32# define PYBIND11_HAS_STD_LAUNDER 0
33#endif
34#if defined(__GNUG__) && !defined(__clang__)
35# include <cxxabi.h>
36#endif
37
38/* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning
39 This warning is about ABI compatibility, not code health.
40 It is only actually needed in a couple places, but apparently GCC 7 "generates this warning if
41 and only if the first template instantiation ... involves noexcept" [stackoverflow], therefore
42 it could get triggered from seemingly random places, depending on user code.
43 No other GCC version generates this warning.
44 */
45#if defined(__GNUC__) && __GNUC__ == 7
46# pragma GCC diagnostic push
47# pragma GCC diagnostic ignored "-Wnoexcept-type"
48#endif
49
51
53
54// Apply all the extensions translators from a list
55// Return true if one of the translators completed without raising an exception
56// itself. Return of false indicates that if there are other translators
57// available, they should be tried.
58inline bool apply_exception_translators(std::forward_list<ExceptionTranslator> &translators) {
59 auto last_exception = std::current_exception();
60
61 for (auto &translator : translators) {
62 try {
63 translator(last_exception);
64 return true;
65 } catch (...) {
66 last_exception = std::current_exception();
67 }
68 }
69 return false;
70}
71
72#if defined(_MSC_VER)
73# define PYBIND11_COMPAT_STRDUP _strdup
74#else
75# define PYBIND11_COMPAT_STRDUP strdup
76#endif
77
79
80
81class cpp_function : public function {
82public:
83 cpp_function() = default;
84 // NOLINTNEXTLINE(google-explicit-constructor)
85 cpp_function(std::nullptr_t) {}
86
88 template <typename Return, typename... Args, typename... Extra>
89 // NOLINTNEXTLINE(google-explicit-constructor)
90 cpp_function(Return (*f)(Args...), const Extra &...extra) {
91 initialize(f, f, extra...);
92 }
93
95 template <typename Func,
96 typename... Extra,
97 typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
98 // NOLINTNEXTLINE(google-explicit-constructor)
99 cpp_function(Func &&f, const Extra &...extra) {
100 initialize(
101 std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...);
102 }
103
105 template <typename Return, typename Class, typename... Arg, typename... Extra>
106 // NOLINTNEXTLINE(google-explicit-constructor)
107 cpp_function(Return (Class::*f)(Arg...), const Extra &...extra) {
108 initialize(
109 [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
110 (Return(*)(Class *, Arg...)) nullptr,
111 extra...);
112 }
113
117 template <typename Return, typename Class, typename... Arg, typename... Extra>
118 // NOLINTNEXTLINE(google-explicit-constructor)
119 cpp_function(Return (Class::*f)(Arg...) &, const Extra &...extra) {
120 initialize(
121 [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
122 (Return(*)(Class *, Arg...)) nullptr,
123 extra...);
124 }
125
127 template <typename Return, typename Class, typename... Arg, typename... Extra>
128 // NOLINTNEXTLINE(google-explicit-constructor)
129 cpp_function(Return (Class::*f)(Arg...) const, const Extra &...extra) {
130 initialize([f](const Class *c,
131 Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
132 (Return(*)(const Class *, Arg...)) nullptr,
133 extra...);
134 }
135
139 template <typename Return, typename Class, typename... Arg, typename... Extra>
140 // NOLINTNEXTLINE(google-explicit-constructor)
141 cpp_function(Return (Class::*f)(Arg...) const &, const Extra &...extra) {
142 initialize([f](const Class *c,
143 Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
144 (Return(*)(const Class *, Arg...)) nullptr,
145 extra...);
146 }
147
149 object name() const { return attr("__name__"); }
150
151protected:
153 // `destruct(function_record, false)`: `initialize_generic` copies strings and
154 // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`.
155 void operator()(detail::function_record *rec) { destruct(rec, false); }
156 };
158 = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
159
162 return unique_function_record(new detail::function_record());
163 }
164
166 template <typename Func, typename Return, typename... Args, typename... Extra>
167 void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) {
168 using namespace detail;
169 struct capture {
171 };
172
173 /* Store the function including any extra state it might have (e.g. a lambda capture
174 * object) */
175 // The unique_ptr makes sure nothing is leaked in case of an exception.
176 auto unique_rec = make_function_record();
177 auto *rec = unique_rec.get();
178
179 /* Store the capture object directly in the function record if there is enough space */
180 if (PYBIND11_SILENCE_MSVC_C4127(sizeof(capture) <= sizeof(rec->data))) {
181 /* Without these pragmas, GCC warns that there might not be
182 enough space to use the placement new operator. However, the
183 'if' statement above ensures that this is the case. */
184#if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER)
185# pragma GCC diagnostic push
186# pragma GCC diagnostic ignored "-Wplacement-new"
187#endif
188 new ((capture *) &rec->data) capture{std::forward<Func>(f)};
189#if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER)
190# pragma GCC diagnostic pop
191#endif
192#if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER)
193# pragma GCC diagnostic push
194# pragma GCC diagnostic ignored "-Wstrict-aliasing"
195#endif
196 // UB without std::launder, but without breaking ABI and/or
197 // a significant refactoring it's "impossible" to solve.
198 if (!std::is_trivially_destructible<capture>::value) {
199 rec->free_data = [](function_record *r) {
200 auto data = PYBIND11_STD_LAUNDER((capture *) &r->data);
201 (void) data;
202 data->~capture();
203 };
204 }
205#if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER)
206# pragma GCC diagnostic pop
207#endif
208 } else {
209 rec->data[0] = new capture{std::forward<Func>(f)};
210 rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
211 }
212
213 /* Type casters for the function arguments and return value */
214 using cast_in = argument_loader<Args...>;
215 using cast_out
217
218 static_assert(
219 expected_num_args<Extra...>(
220 sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
221 "The number of argument annotations does not match the number of function arguments");
222
223 /* Dispatch code which converts function arguments and performs the actual function call */
224 rec->impl = [](function_call &call) -> handle {
225 cast_in args_converter;
226
227 /* Try to cast the function arguments into the C++ domain */
228 if (!args_converter.load_args(call)) {
230 }
231
232 /* Invoke call policy pre-call hook */
234
235 /* Get a pointer to the capture object */
236 const auto *data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data
237 : call.func.data[0]);
238 auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
239
240 /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
243
244 /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
245 using Guard = extract_guard_t<Extra...>;
246
247 /* Perform the function call */
248 handle result
249 = cast_out::cast(std::move(args_converter).template call<Return, Guard>(cap->f),
250 policy,
251 call.parent);
252
253 /* Invoke call policy post-call hook */
255
256 return result;
257 };
258
259 rec->nargs_pos = cast_in::args_pos >= 0
260 ? static_cast<std::uint16_t>(cast_in::args_pos)
261 : sizeof...(Args) - cast_in::has_kwargs; // Will get reduced more if
262 // we have a kw_only
263 rec->has_args = cast_in::args_pos >= 0;
264 rec->has_kwargs = cast_in::has_kwargs;
265
266 /* Process any user-provided function attributes */
268
269 {
270 constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
271 has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
272 has_arg_annotations = any_of<is_keyword<Extra>...>::value;
273 static_assert(has_arg_annotations || !has_kw_only_args,
274 "py::kw_only requires the use of argument annotations");
275 static_assert(has_arg_annotations || !has_pos_only_args,
276 "py::pos_only requires the use of argument annotations (for docstrings "
277 "and aligning the annotations to the argument)");
278
279 static_assert(constexpr_sum(is_kw_only<Extra>::value...) <= 1,
280 "py::kw_only may be specified only once");
281 static_assert(constexpr_sum(is_pos_only<Extra>::value...) <= 1,
282 "py::pos_only may be specified only once");
283 constexpr auto kw_only_pos = constexpr_first<is_kw_only, Extra...>();
284 constexpr auto pos_only_pos = constexpr_first<is_pos_only, Extra...>();
285 static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
286 "py::pos_only must come before py::kw_only");
287 }
288
289 /* Generate a readable signature describing the function's arguments and return
290 value types */
291 static constexpr auto signature
292 = const_name("(") + cast_in::arg_names + const_name(") -> ") + cast_out::name;
293 PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
294
295 /* Register the function with Python from generic (non-templated) code */
296 // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid.
297 initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));
298
299 /* Stash some additional information used by an important optimization in 'functional.h' */
300 using FunctionType = Return (*)(Args...);
301 constexpr bool is_function_ptr
302 = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *);
303 if (is_function_ptr) {
304 rec->is_stateless = true;
305 rec->data[1]
306 = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
307 }
308 }
309
310 // Utility class that keeps track of all duplicated strings, and cleans them up in its
311 // destructor, unless they are released. Basically a RAII-solution to deal with exceptions
312 // along the way.
314 public:
316 for (auto *s : strings) {
317 std::free(s);
318 }
319 }
320 char *operator()(const char *s) {
321 auto *t = PYBIND11_COMPAT_STRDUP(s);
322 strings.push_back(t);
323 return t;
324 }
325 void release() { strings.clear(); }
326
327 private:
328 std::vector<char *> strings;
329 };
330
333 const char *text,
334 const std::type_info *const *types,
335 size_t args) {
336 // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr,
337 // we do not want this to destruct the pointer. `initialize` (the caller) still relies on
338 // the pointee being alive after this call. Only move out if a `capsule` is going to keep
339 // it alive.
340 auto *rec = unique_rec.get();
341
342 // Keep track of strdup'ed strings, and clean them up as long as the function's capsule
343 // has not taken ownership yet (when `unique_rec.release()` is called).
344 // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the
345 // strings are only referenced before strdup'ing. So only *after* the following block could
346 // `destruct` safely be called, but even then, `repr` could still throw in the middle of
347 // copying all strings.
348 strdup_guard guarded_strdup;
349
350 /* Create copies of all referenced C-style strings */
351 rec->name = guarded_strdup(rec->name ? rec->name : "");
352 if (rec->doc) {
353 rec->doc = guarded_strdup(rec->doc);
354 }
355 for (auto &a : rec->args) {
356 if (a.name) {
357 a.name = guarded_strdup(a.name);
358 }
359 if (a.descr) {
360 a.descr = guarded_strdup(a.descr);
361 } else if (a.value) {
362 a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());
363 }
364 }
365
366 rec->is_constructor = (std::strcmp(rec->name, "__init__") == 0)
367 || (std::strcmp(rec->name, "__setstate__") == 0);
368
369#if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
370 if (rec->is_constructor && !rec->is_new_style_constructor) {
371 const auto class_name
372 = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
373 const auto func_name = std::string(rec->name);
374 PyErr_WarnEx(PyExc_FutureWarning,
375 ("pybind11-bound class '" + class_name
376 + "' is using an old-style "
377 "placement-new '"
378 + func_name
379 + "' which has been deprecated. See "
380 "the upgrade guide in pybind11's docs. This message is only visible "
381 "when compiled in debug mode.")
382 .c_str(),
383 0);
384 }
385#endif
386
387 /* Generate a proper function signature */
388 std::string signature;
389 size_t type_index = 0, arg_index = 0;
390 bool is_starred = false;
391 for (const auto *pc = text; *pc != '\0'; ++pc) {
392 const auto c = *pc;
393
394 if (c == '{') {
395 // Write arg name for everything except *args and **kwargs.
396 is_starred = *(pc + 1) == '*';
397 if (is_starred) {
398 continue;
399 }
400 // Separator for keyword-only arguments, placed before the kw
401 // arguments start (unless we are already putting an *args)
402 if (!rec->has_args && arg_index == rec->nargs_pos) {
403 signature += "*, ";
404 }
405 if (arg_index < rec->args.size() && rec->args[arg_index].name) {
406 signature += rec->args[arg_index].name;
407 } else if (arg_index == 0 && rec->is_method) {
408 signature += "self";
409 } else {
410 signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
411 }
412 signature += ": ";
413 } else if (c == '}') {
414 // Write default value if available.
415 if (!is_starred && arg_index < rec->args.size() && rec->args[arg_index].descr) {
416 signature += " = ";
417 signature += rec->args[arg_index].descr;
418 }
419 // Separator for positional-only arguments (placed after the
420 // argument, rather than before like *
421 if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
422 signature += ", /";
423 }
424 if (!is_starred) {
425 arg_index++;
426 }
427 } else if (c == '%') {
428 const std::type_info *t = types[type_index++];
429 if (!t) {
430 pybind11_fail("Internal error while parsing type signature (1)");
431 }
432 if (auto *tinfo = detail::get_type_info(*t)) {
433 handle th((PyObject *) tinfo->type);
434 signature += th.attr("__module__").cast<std::string>() + "." +
435 // Python 3.3+, but we backport it to earlier versions
436 th.attr("__qualname__").cast<std::string>();
437 } else if (rec->is_new_style_constructor && arg_index == 0) {
438 // A new-style `__init__` takes `self` as `value_and_holder`.
439 // Rewrite it to the proper class type.
440 signature += rec->scope.attr("__module__").cast<std::string>() + "."
441 + rec->scope.attr("__qualname__").cast<std::string>();
442 } else {
443 std::string tname(t->name());
444 detail::clean_type_id(tname);
445 signature += tname;
446 }
447 } else {
448 signature += c;
449 }
450 }
451
452 if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] != nullptr) {
453 pybind11_fail("Internal error while parsing type signature (2)");
454 }
455
456#if PY_MAJOR_VERSION < 3
457 if (std::strcmp(rec->name, "__next__") == 0) {
458 std::free(rec->name);
459 rec->name = guarded_strdup("next");
460 } else if (std::strcmp(rec->name, "__bool__") == 0) {
461 std::free(rec->name);
462 rec->name = guarded_strdup("__nonzero__");
463 }
464#endif
465 rec->signature = guarded_strdup(signature.c_str());
466 rec->args.shrink_to_fit();
467 rec->nargs = (std::uint16_t) args;
468
469 if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) {
470 rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
471 }
472
473 detail::function_record *chain = nullptr, *chain_start = rec;
474 if (rec->sibling) {
475 if (PyCFunction_Check(rec->sibling.ptr())) {
476 auto *self = PyCFunction_GET_SELF(rec->sibling.ptr());
477 capsule rec_capsule = isinstance<capsule>(self) ? reinterpret_borrow<capsule>(self)
478 : capsule(self);
479 chain = (detail::function_record *) rec_capsule;
480 /* Never append a method to an overload chain of a parent class;
481 instead, hide the parent's overloads in this case */
482 if (!chain->scope.is(rec->scope)) {
483 chain = nullptr;
484 }
485 }
486 // Don't trigger for things like the default __init__, which are wrapper_descriptors
487 // that we are intentionally replacing
488 else if (!rec->sibling.is_none() && rec->name[0] != '_') {
489 pybind11_fail("Cannot overload existing non-function object \""
490 + std::string(rec->name) + "\" with a function of the same name");
491 }
492 }
493
494 if (!chain) {
495 /* No existing overload was found, create a new function object */
496 rec->def = new PyMethodDef();
497 std::memset(rec->def, 0, sizeof(PyMethodDef));
498 rec->def->ml_name = rec->name;
499 rec->def->ml_meth
500 = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher));
501 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
502
503 capsule rec_capsule(unique_rec.release(),
504 [](void *ptr) { destruct((detail::function_record *) ptr); });
505 guarded_strdup.release();
506
507 object scope_module;
508 if (rec->scope) {
509 if (hasattr(rec->scope, "__module__")) {
510 scope_module = rec->scope.attr("__module__");
511 } else if (hasattr(rec->scope, "__name__")) {
512 scope_module = rec->scope.attr("__name__");
513 }
514 }
515
516 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
517 if (!m_ptr) {
518 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
519 }
520 } else {
521 /* Append at the beginning or end of the overload chain */
522 m_ptr = rec->sibling.ptr();
523 inc_ref();
524 if (chain->is_method != rec->is_method) {
526 "overloading a method with both static and instance methods is not supported; "
527#if defined(NDEBUG)
528 "compile in debug mode for more details"
529#else
530 "error while attempting to bind "
531 + std::string(rec->is_method ? "instance" : "static") + " method "
532 + std::string(pybind11::str(rec->scope.attr("__name__"))) + "."
533 + std::string(rec->name) + signature
534#endif
535 );
536 }
537
538 if (rec->prepend) {
539 // Beginning of chain; we need to replace the capsule's current head-of-the-chain
540 // pointer with this one, then make this one point to the previous head of the
541 // chain.
542 chain_start = rec;
543 rec->next = chain;
544 auto rec_capsule
545 = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self);
546 rec_capsule.set_pointer(unique_rec.release());
547 guarded_strdup.release();
548 } else {
549 // Or end of chain (normal behavior)
550 chain_start = chain;
551 while (chain->next) {
552 chain = chain->next;
553 }
554 chain->next = unique_rec.release();
555 guarded_strdup.release();
556 }
557 }
558
559 std::string signatures;
560 int index = 0;
561 /* Create a nice pydoc rec including all signatures and
562 docstrings of the functions in the overload chain */
563 if (chain && options::show_function_signatures()) {
564 // First a generic signature
565 signatures += rec->name;
566 signatures += "(*args, **kwargs)\n";
567 signatures += "Overloaded function.\n\n";
568 }
569 // Then specific overload signatures
570 bool first_user_def = true;
571 for (auto *it = chain_start; it != nullptr; it = it->next) {
573 if (index > 0) {
574 signatures += "\n";
575 }
576 if (chain) {
577 signatures += std::to_string(++index) + ". ";
578 }
579 signatures += rec->name;
580 signatures += it->signature;
581 signatures += "\n";
582 }
583 if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) {
584 // If we're appending another docstring, and aren't printing function signatures,
585 // we need to append a newline first:
587 if (first_user_def) {
588 first_user_def = false;
589 } else {
590 signatures += "\n";
591 }
592 }
594 signatures += "\n";
595 }
596 signatures += it->doc;
598 signatures += "\n";
599 }
600 }
601 }
602
603 /* Install docstring */
604 auto *func = (PyCFunctionObject *) m_ptr;
605 std::free(const_cast<char *>(func->m_ml->ml_doc));
606 // Install docstring if it's non-empty (when at least one option is enabled)
607 func->m_ml->ml_doc
608 = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());
609
610 if (rec->is_method) {
611 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
612 if (!m_ptr) {
614 "cpp_function::cpp_function(): Could not allocate instance method object");
615 }
616 Py_DECREF(func);
617 }
618 }
619
621 static void destruct(detail::function_record *rec, bool free_strings = true) {
622// If on Python 3.9, check the interpreter "MICRO" (patch) version.
623// If this is running on 3.9.0, we have to work around a bug.
624#if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
625 static bool is_zero = Py_GetVersion()[4] == '0';
626#endif
627
628 while (rec) {
629 detail::function_record *next = rec->next;
630 if (rec->free_data) {
631 rec->free_data(rec);
632 }
633 // During initialization, these strings might not have been copied yet,
634 // so they cannot be freed. Once the function has been created, they can.
635 // Check `make_function_record` for more details.
636 if (free_strings) {
637 std::free((char *) rec->name);
638 std::free((char *) rec->doc);
639 std::free((char *) rec->signature);
640 for (auto &arg : rec->args) {
641 std::free(const_cast<char *>(arg.name));
642 std::free(const_cast<char *>(arg.descr));
643 }
644 }
645 for (auto &arg : rec->args) {
646 arg.value.dec_ref();
647 }
648 if (rec->def) {
649 std::free(const_cast<char *>(rec->def->ml_doc));
650// Python 3.9.0 decref's these in the wrong order; rec->def
651// If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)
652// See https://github.com/python/cpython/pull/22670
653#if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
654 if (!is_zero) {
655 delete rec->def;
656 }
657#else
658 delete rec->def;
659#endif
660 }
661 delete rec;
662 rec = next;
663 }
664 }
665
667 static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
668 using namespace detail;
669
670 /* Iterator over the list of potentially admissible overloads */
671 const function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
672 *it = overloads;
673
674 /* Need to know how many arguments + keyword arguments there are to pick the right
675 overload */
676 const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
677
678 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
680
681 auto self_value_and_holder = value_and_holder();
682 if (overloads->is_constructor) {
683 if (!parent
684 || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
685 PyErr_SetString(
686 PyExc_TypeError,
687 "__init__(self, ...) called with invalid or missing `self` argument");
688 return nullptr;
689 }
690
691 auto *const tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
692 auto *const pi = reinterpret_cast<instance *>(parent.ptr());
693 self_value_and_holder = pi->get_value_and_holder(tinfo, true);
694
695 // If this value is already registered it must mean __init__ is invoked multiple times;
696 // we really can't support that in C++, so just ignore the second __init__.
697 if (self_value_and_holder.instance_registered()) {
698 return none().release().ptr();
699 }
700 }
701
702 try {
703 // We do this in two passes: in the first pass, we load arguments with `convert=false`;
704 // in the second, we allow conversion (except for arguments with an explicit
705 // py::arg().noconvert()). This lets us prefer calls without conversion, with
706 // conversion as a fallback.
707 std::vector<function_call> second_pass;
708
709 // However, if there are no overloads, we can just skip the no-convert pass entirely
710 const bool overloaded = it != nullptr && it->next != nullptr;
711
712 for (; it != nullptr; it = it->next) {
713
714 /* For each overload:
715 1. Copy all positional arguments we were given, also checking to make sure that
716 named positional arguments weren't *also* specified via kwarg.
717 2. If we weren't given enough, try to make up the omitted ones by checking
718 whether they were provided by a kwarg matching the `py::arg("name")` name. If
719 so, use it (and remove it from kwargs); if not, see if the function binding
720 provided a default that we can use.
721 3. Ensure that either all keyword arguments were "consumed", or that the
722 function takes a kwargs argument to accept unconsumed kwargs.
723 4. Any positional arguments still left get put into a tuple (for args), and any
724 leftover kwargs get put into a dict.
725 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
726 extra tuple or dict at the end of the positional arguments.
727 6. Call the function call dispatcher (function_record::impl)
728
729 If one of these fail, move on to the next overload and keep trying until we get
730 a result other than PYBIND11_TRY_NEXT_OVERLOAD.
731 */
732
733 const function_record &func = *it;
734 size_t num_args = func.nargs; // Number of positional arguments that we need
735 if (func.has_args) {
736 --num_args; // (but don't count py::args
737 }
738 if (func.has_kwargs) {
739 --num_args; // or py::kwargs)
740 }
741 size_t pos_args = func.nargs_pos;
742
743 if (!func.has_args && n_args_in > pos_args) {
744 continue; // Too many positional arguments for this overload
745 }
746
747 if (n_args_in < pos_args && func.args.size() < pos_args) {
748 continue; // Not enough positional arguments given, and not enough defaults to
749 // fill in the blanks
750 }
751
752 function_call call(func, parent);
753
754 // Protect std::min with parentheses
755 size_t args_to_copy = (std::min)(pos_args, n_args_in);
756 size_t args_copied = 0;
757
758 // 0. Inject new-style `self` argument
759 if (func.is_new_style_constructor) {
760 // The `value` may have been preallocated by an old-style `__init__`
761 // if it was a preceding candidate for overload resolution.
762 if (self_value_and_holder) {
763 self_value_and_holder.type->dealloc(self_value_and_holder);
764 }
765
766 call.init_self = PyTuple_GET_ITEM(args_in, 0);
767 call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
768 call.args_convert.push_back(false);
769 ++args_copied;
770 }
771
772 // 1. Copy any position arguments given.
773 bool bad_arg = false;
774 for (; args_copied < args_to_copy; ++args_copied) {
775 const argument_record *arg_rec
776 = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
777 if (kwargs_in && arg_rec && arg_rec->name
778 && dict_getitemstring(kwargs_in, arg_rec->name)) {
779 bad_arg = true;
780 break;
781 }
782
783 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
784 if (arg_rec && !arg_rec->none && arg.is_none()) {
785 bad_arg = true;
786 break;
787 }
788 call.args.push_back(arg);
789 call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
790 }
791 if (bad_arg) {
792 continue; // Maybe it was meant for another overload (issue #688)
793 }
794
795 // Keep track of how many position args we copied out in case we need to come back
796 // to copy the rest into a py::args argument.
797 size_t positional_args_copied = args_copied;
798
799 // We'll need to copy this if we steal some kwargs for defaults
800 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
801
802 // 1.5. Fill in any missing pos_only args from defaults if they exist
803 if (args_copied < func.nargs_pos_only) {
804 for (; args_copied < func.nargs_pos_only; ++args_copied) {
805 const auto &arg_rec = func.args[args_copied];
806 handle value;
807
808 if (arg_rec.value) {
809 value = arg_rec.value;
810 }
811 if (value) {
812 call.args.push_back(value);
813 call.args_convert.push_back(arg_rec.convert);
814 } else {
815 break;
816 }
817 }
818
819 if (args_copied < func.nargs_pos_only) {
820 continue; // Not enough defaults to fill the positional arguments
821 }
822 }
823
824 // 2. Check kwargs and, failing that, defaults that may help complete the list
825 if (args_copied < num_args) {
826 bool copied_kwargs = false;
827
828 for (; args_copied < num_args; ++args_copied) {
829 const auto &arg_rec = func.args[args_copied];
830
831 handle value;
832 if (kwargs_in && arg_rec.name) {
833 value = dict_getitemstring(kwargs.ptr(), arg_rec.name);
834 }
835
836 if (value) {
837 // Consume a kwargs value
838 if (!copied_kwargs) {
839 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
840 copied_kwargs = true;
841 }
842 if (PyDict_DelItemString(kwargs.ptr(), arg_rec.name) == -1) {
843 throw error_already_set();
844 }
845 } else if (arg_rec.value) {
846 value = arg_rec.value;
847 }
848
849 if (!arg_rec.none && value.is_none()) {
850 break;
851 }
852
853 if (value) {
854 // If we're at the py::args index then first insert a stub for it to be
855 // replaced later
856 if (func.has_args && call.args.size() == func.nargs_pos) {
857 call.args.push_back(none());
858 }
859
860 call.args.push_back(value);
861 call.args_convert.push_back(arg_rec.convert);
862 } else {
863 break;
864 }
865 }
866
867 if (args_copied < num_args) {
868 continue; // Not enough arguments, defaults, or kwargs to fill the
869 // positional arguments
870 }
871 }
872
873 // 3. Check everything was consumed (unless we have a kwargs arg)
874 if (kwargs && !kwargs.empty() && !func.has_kwargs) {
875 continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
876 }
877
878 // 4a. If we have a py::args argument, create a new tuple with leftovers
879 if (func.has_args) {
880 tuple extra_args;
881 if (args_to_copy == 0) {
882 // We didn't copy out any position arguments from the args_in tuple, so we
883 // can reuse it directly without copying:
884 extra_args = reinterpret_borrow<tuple>(args_in);
885 } else if (positional_args_copied >= n_args_in) {
886 extra_args = tuple(0);
887 } else {
888 size_t args_size = n_args_in - positional_args_copied;
889 extra_args = tuple(args_size);
890 for (size_t i = 0; i < args_size; ++i) {
891 extra_args[i] = PyTuple_GET_ITEM(args_in, positional_args_copied + i);
892 }
893 }
894 if (call.args.size() <= func.nargs_pos) {
895 call.args.push_back(extra_args);
896 } else {
897 call.args[func.nargs_pos] = extra_args;
898 }
899 call.args_convert.push_back(false);
900 call.args_ref = std::move(extra_args);
901 }
902
903 // 4b. If we have a py::kwargs, pass on any remaining kwargs
904 if (func.has_kwargs) {
905 if (!kwargs.ptr()) {
906 kwargs = dict(); // If we didn't get one, send an empty one
907 }
908 call.args.push_back(kwargs);
909 call.args_convert.push_back(false);
910 call.kwargs_ref = std::move(kwargs);
911 }
912
913// 5. Put everything in a vector. Not technically step 5, we've been building it
914// in `call.args` all along.
915#if !defined(NDEBUG)
916 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) {
917 pybind11_fail("Internal error: function call dispatcher inserted wrong number "
918 "of arguments!");
919 }
920#endif
921
922 std::vector<bool> second_pass_convert;
923 if (overloaded) {
924 // We're in the first no-convert pass, so swap out the conversion flags for a
925 // set of all-false flags. If the call fails, we'll swap the flags back in for
926 // the conversion-allowed call below.
927 second_pass_convert.resize(func.nargs, false);
928 call.args_convert.swap(second_pass_convert);
929 }
930
931 // 6. Call the function.
932 try {
933 loader_life_support guard{};
934 result = func.impl(call);
935 } catch (reference_cast_error &) {
937 }
938
939 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
940 break;
941 }
942
943 if (overloaded) {
944 // The (overloaded) call failed; if the call has at least one argument that
945 // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
946 // then add this call to the list of second pass overloads to try.
947 for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
948 if (second_pass_convert[i]) {
949 // Found one: swap the converting flags back in and store the call for
950 // the second pass.
951 call.args_convert.swap(second_pass_convert);
952 second_pass.push_back(std::move(call));
953 break;
954 }
955 }
956 }
957 }
958
959 if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
960 // The no-conversion pass finished without success, try again with conversion
961 // allowed
962 for (auto &call : second_pass) {
963 try {
964 loader_life_support guard{};
965 result = call.func.impl(call);
966 } catch (reference_cast_error &) {
968 }
969
970 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
971 // The error reporting logic below expects 'it' to be valid, as it would be
972 // if we'd encountered this failure in the first-pass loop.
973 if (!result) {
974 it = &call.func;
975 }
976 break;
977 }
978 }
979 }
980 } catch (error_already_set &e) {
981 e.restore();
982 return nullptr;
983#ifdef __GLIBCXX__
984 } catch (abi::__forced_unwind &) {
985 throw;
986#endif
987 } catch (...) {
988 /* When an exception is caught, give each registered exception
989 translator a chance to translate it to a Python exception. First
990 all module-local translators will be tried in reverse order of
991 registration. If none of the module-locale translators handle
992 the exception (or there are no module-locale translators) then
993 the global translators will be tried, also in reverse order of
994 registration.
995
996 A translator may choose to do one of the following:
997
998 - catch the exception and call PyErr_SetString or PyErr_SetObject
999 to set a standard (or custom) Python exception, or
1000 - do nothing and let the exception fall through to the next translator, or
1001 - delegate translation to the next translator by throwing a new type of exception.
1002 */
1003
1004 auto &local_exception_translators
1006 if (detail::apply_exception_translators(local_exception_translators)) {
1007 return nullptr;
1008 }
1009 auto &exception_translators = get_internals().registered_exception_translators;
1010 if (detail::apply_exception_translators(exception_translators)) {
1011 return nullptr;
1012 }
1013
1014 PyErr_SetString(PyExc_SystemError,
1015 "Exception escaped from default exception translator!");
1016 return nullptr;
1017 }
1018
1019 auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
1020 if (msg.find("std::") != std::string::npos) {
1021 msg += "\n\n"
1022 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1023 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1024 "conversions are optional and require extra headers to be included\n"
1025 "when compiling your pybind11 module.";
1026 }
1027 };
1028
1029 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
1030 if (overloads->is_operator) {
1031 return handle(Py_NotImplemented).inc_ref().ptr();
1032 }
1033
1034 std::string msg = std::string(overloads->name) + "(): incompatible "
1035 + std::string(overloads->is_constructor ? "constructor" : "function")
1036 + " arguments. The following argument types are supported:\n";
1037
1038 int ctr = 0;
1039 for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
1040 msg += " " + std::to_string(++ctr) + ". ";
1041
1042 bool wrote_sig = false;
1043 if (overloads->is_constructor) {
1044 // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as
1045 // `Object(arg0, ...)`
1046 std::string sig = it2->signature;
1047 size_t start = sig.find('(') + 7; // skip "(self: "
1048 if (start < sig.size()) {
1049 // End at the , for the next argument
1050 size_t end = sig.find(", "), next = end + 2;
1051 size_t ret = sig.rfind(" -> ");
1052 // Or the ), if there is no comma:
1053 if (end >= sig.size()) {
1054 next = end = sig.find(')');
1055 }
1056 if (start < end && next < sig.size()) {
1057 msg.append(sig, start, end - start);
1058 msg += '(';
1059 msg.append(sig, next, ret - next);
1060 wrote_sig = true;
1061 }
1062 }
1063 }
1064 if (!wrote_sig) {
1065 msg += it2->signature;
1066 }
1067
1068 msg += "\n";
1069 }
1070 msg += "\nInvoked with: ";
1071 auto args_ = reinterpret_borrow<tuple>(args_in);
1072 bool some_args = false;
1073 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
1074 if (!some_args) {
1075 some_args = true;
1076 } else {
1077 msg += ", ";
1078 }
1079 try {
1080 msg += pybind11::repr(args_[ti]);
1081 } catch (const error_already_set &) {
1082 msg += "<repr raised Error>";
1083 }
1084 }
1085 if (kwargs_in) {
1086 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
1087 if (!kwargs.empty()) {
1088 if (some_args) {
1089 msg += "; ";
1090 }
1091 msg += "kwargs: ";
1092 bool first = true;
1093 for (auto kwarg : kwargs) {
1094 if (first) {
1095 first = false;
1096 } else {
1097 msg += ", ";
1098 }
1099 msg += pybind11::str("{}=").format(kwarg.first);
1100 try {
1101 msg += pybind11::repr(kwarg.second);
1102 } catch (const error_already_set &) {
1103 msg += "<repr raised Error>";
1104 }
1105 }
1106 }
1107 }
1108
1109 append_note_if_missing_header_is_suspected(msg);
1110#if PY_VERSION_HEX >= 0x03030000
1111 // Attach additional error info to the exception if supported
1112 if (PyErr_Occurred()) {
1113 // #HelpAppreciated: unit test coverage for this branch.
1114 raise_from(PyExc_TypeError, msg.c_str());
1115 return nullptr;
1116 }
1117#endif
1118 PyErr_SetString(PyExc_TypeError, msg.c_str());
1119 return nullptr;
1120 }
1121 if (!result) {
1122 std::string msg = "Unable to convert function return value to a "
1123 "Python type! The signature was\n\t";
1124 msg += it->signature;
1125 append_note_if_missing_header_is_suspected(msg);
1126#if PY_VERSION_HEX >= 0x03030000
1127 // Attach additional error info to the exception if supported
1128 if (PyErr_Occurred()) {
1129 raise_from(PyExc_TypeError, msg.c_str());
1130 return nullptr;
1131 }
1132#endif
1133 PyErr_SetString(PyExc_TypeError, msg.c_str());
1134 return nullptr;
1135 }
1136 if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
1137 auto *pi = reinterpret_cast<instance *>(parent.ptr());
1138 self_value_and_holder.type->init_instance(pi, nullptr);
1139 }
1140 return result.ptr();
1141 }
1142};
1143
1145class module_ : public object {
1146public:
1147 PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)
1148
1149
1150 PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead")
1151 explicit module_(const char *name, const char *doc = nullptr) {
1152#if PY_MAJOR_VERSION >= 3
1153 *this = create_extension_module(name, doc, new PyModuleDef());
1154#else
1155 *this = create_extension_module(name, doc, nullptr);
1156#endif
1157 }
1158
1164 template <typename Func, typename... Extra>
1165 module_ &def(const char *name_, Func &&f, const Extra &...extra) {
1166 cpp_function func(std::forward<Func>(f),
1167 name(name_),
1168 scope(*this),
1169 sibling(getattr(*this, name_, none())),
1170 extra...);
1171 // NB: allow overwriting here because cpp_function sets up a chain with the intention of
1172 // overwriting (and has already checked internally that it isn't overwriting
1173 // non-functions).
1174 add_object(name_, func, true /* overwrite */);
1175 return *this;
1176 }
1177
1188 module_ def_submodule(const char *name, const char *doc = nullptr) {
1189 std::string full_name
1190 = std::string(PyModule_GetName(m_ptr)) + std::string(".") + std::string(name);
1191 auto result = reinterpret_borrow<module_>(PyImport_AddModule(full_name.c_str()));
1193 result.attr("__doc__") = pybind11::str(doc);
1194 }
1195 attr(name) = result;
1196 return result;
1197 }
1198
1200 static module_ import(const char *name) {
1201 PyObject *obj = PyImport_ImportModule(name);
1202 if (!obj) {
1203 throw error_already_set();
1204 }
1205 return reinterpret_steal<module_>(obj);
1206 }
1207
1209 void reload() {
1210 PyObject *obj = PyImport_ReloadModule(ptr());
1211 if (!obj) {
1212 throw error_already_set();
1213 }
1214 *this = reinterpret_steal<module_>(obj);
1215 }
1216
1224 PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
1225 if (!overwrite && hasattr(*this, name)) {
1227 "Error during initialization: multiple incompatible definitions with name \""
1228 + std::string(name) + "\"");
1229 }
1230
1231 PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
1232 }
1233
1234#if PY_MAJOR_VERSION >= 3
1235 using module_def = PyModuleDef;
1236#else
1237 struct module_def {};
1238#endif
1239
1246 static module_ create_extension_module(const char *name, const char *doc, module_def *def) {
1247#if PY_MAJOR_VERSION >= 3
1248 // module_def is PyModuleDef
1249 // Placement new (not an allocation).
1250 def = new (def)
1251 PyModuleDef{/* m_base */ PyModuleDef_HEAD_INIT,
1252 /* m_name */ name,
1253 /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr,
1254 /* m_size */ -1,
1255 /* m_methods */ nullptr,
1256 /* m_slots */ nullptr,
1257 /* m_traverse */ nullptr,
1258 /* m_clear */ nullptr,
1259 /* m_free */ nullptr};
1260 auto *m = PyModule_Create(def);
1261#else
1262 // Ignore module_def *def; only necessary for Python 3
1263 (void) def;
1264 auto m = Py_InitModule3(
1265 name, nullptr, options::show_user_defined_docstrings() ? doc : nullptr);
1266#endif
1267 if (m == nullptr) {
1268 if (PyErr_Occurred()) {
1269 throw error_already_set();
1270 }
1271 pybind11_fail("Internal error in module_::create_extension_module()");
1272 }
1273 // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when
1274 // returned from PyInit_...
1275 // For Python 2, reinterpret_borrow is correct.
1276 return reinterpret_borrow<module_>(m);
1277 }
1278};
1279
1280// When inside a namespace (or anywhere as long as it's not the first item on a line),
1281// C++20 allows "module" to be used. This is provided for backward compatibility, and for
1282// simplicity, if someone wants to use py::module for example, that is perfectly safe.
1284
1288inline dict globals() {
1289 PyObject *p = PyEval_GetGlobals();
1290 return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
1291}
1292
1293#if PY_VERSION_HEX >= 0x03030000
1294template <typename... Args, typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>>
1295PYBIND11_DEPRECATED("make_simple_namespace should be replaced with "
1296 "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
1297object make_simple_namespace(Args &&...args_) {
1298 return module_::import("types").attr("SimpleNamespace")(std::forward<Args>(args_)...);
1299}
1300#endif
1301
1304class generic_type : public object {
1305public:
1306 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
1307protected:
1308 void initialize(const type_record &rec) {
1309 if (rec.scope && hasattr(rec.scope, "__dict__")
1310 && rec.scope.attr("__dict__").contains(rec.name)) {
1311 pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name)
1312 + "\": an object with that name is already defined");
1313 }
1314
1316 != nullptr) {
1317 pybind11_fail("generic_type: type \"" + std::string(rec.name)
1318 + "\" is already registered!");
1319 }
1320
1321 m_ptr = make_new_python_type(rec);
1322
1323 /* Register supplemental type information in C++ dict */
1324 auto *tinfo = new detail::type_info();
1325 tinfo->type = (PyTypeObject *) m_ptr;
1326 tinfo->cpptype = rec.type;
1327 tinfo->type_size = rec.type_size;
1328 tinfo->type_align = rec.type_align;
1329 tinfo->operator_new = rec.operator_new;
1330 tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
1331 tinfo->init_instance = rec.init_instance;
1332 tinfo->dealloc = rec.dealloc;
1333 tinfo->simple_type = true;
1334 tinfo->simple_ancestors = true;
1335 tinfo->default_holder = rec.default_holder;
1336 tinfo->module_local = rec.module_local;
1337
1338 auto &internals = get_internals();
1339 auto tindex = std::type_index(*rec.type);
1340 tinfo->direct_conversions = &internals.direct_conversions[tindex];
1341 if (rec.module_local) {
1342 get_local_internals().registered_types_cpp[tindex] = tinfo;
1343 } else {
1344 internals.registered_types_cpp[tindex] = tinfo;
1345 }
1346 internals.registered_types_py[(PyTypeObject *) m_ptr] = {tinfo};
1347
1348 if (rec.bases.size() > 1 || rec.multiple_inheritance) {
1349 mark_parents_nonsimple(tinfo->type);
1350 tinfo->simple_ancestors = false;
1351 } else if (rec.bases.size() == 1) {
1352 auto *parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
1353 assert(parent_tinfo != nullptr);
1354 bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1355 tinfo->simple_ancestors = parent_simple_ancestors;
1356 // The parent can no longer be a simple type if it has MI and has a child
1357 parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1358 }
1359
1360 if (rec.module_local) {
1361 // Stash the local typeinfo and loader so that external modules can access it.
1362 tinfo->module_local_load = &type_caster_generic::local_load;
1364 }
1365 }
1366
1368 void mark_parents_nonsimple(PyTypeObject *value) {
1369 auto t = reinterpret_borrow<tuple>(value->tp_bases);
1370 for (handle h : t) {
1371 auto *tinfo2 = get_type_info((PyTypeObject *) h.ptr());
1372 if (tinfo2) {
1373 tinfo2->simple_type = false;
1374 }
1375 mark_parents_nonsimple((PyTypeObject *) h.ptr());
1376 }
1377 }
1378
1379 void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *),
1380 void *get_buffer_data) {
1381 auto *type = (PyHeapTypeObject *) m_ptr;
1382 auto *tinfo = detail::get_type_info(&type->ht_type);
1383
1384 if (!type->ht_type.tp_as_buffer) {
1385 pybind11_fail("To be able to register buffer protocol support for the type '"
1386 + get_fully_qualified_tp_name(tinfo->type)
1387 + "' the associated class<>(..) invocation must "
1388 "include the pybind11::buffer_protocol() annotation!");
1389 }
1390
1391 tinfo->get_buffer = get_buffer;
1392 tinfo->get_buffer_data = get_buffer_data;
1393 }
1394
1395 // rec_func must be set for either fget or fset.
1397 handle fget,
1398 handle fset,
1399 detail::function_record *rec_func) {
1400 const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);
1401 const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)
1402 && pybind11::options::show_user_defined_docstrings();
1403 auto property = handle(
1404 (PyObject *) (is_static ? get_internals().static_property_type : &PyProperty_Type));
1405 attr(name) = property(fget.ptr() ? fget : none(),
1406 fset.ptr() ? fset : none(),
1407 /*deleter*/ none(),
1408 pybind11::str(has_doc ? rec_func->doc : ""));
1409 }
1410};
1411
1413template <typename T,
1414 typename = void_t<decltype(static_cast<void *(*) (size_t)>(T::operator new))>>
1416 r->operator_new = &T::operator new;
1417}
1418
1419template <typename>
1421
1422template <typename T, typename SFINAE = void>
1423struct has_operator_delete : std::false_type {};
1424template <typename T>
1426 : std::true_type {};
1427template <typename T, typename SFINAE = void>
1428struct has_operator_delete_size : std::false_type {};
1429template <typename T>
1431 T,
1432 void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type {
1433};
1435template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
1436void call_operator_delete(T *p, size_t, size_t) {
1437 T::operator delete(p);
1438}
1439template <
1440 typename T,
1442void call_operator_delete(T *p, size_t s, size_t) {
1443 T::operator delete(p, s);
1444}
1445
1446inline void call_operator_delete(void *p, size_t s, size_t a) {
1447 (void) s;
1448 (void) a;
1449#if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1450 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1451# ifdef __cpp_sized_deallocation
1452 ::operator delete(p, s, std::align_val_t(a));
1453# else
1454 ::operator delete(p, std::align_val_t(a));
1455# endif
1456 return;
1457 }
1458#endif
1459#ifdef __cpp_sized_deallocation
1460 ::operator delete(p, s);
1461#else
1462 ::operator delete(p);
1463#endif
1464}
1465
1466inline void add_class_method(object &cls, const char *name_, const cpp_function &cf) {
1467 cls.attr(cf.name()) = cf;
1468 if (std::strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) {
1469 cls.attr("__hash__") = none();
1470 }
1471}
1472
1474
1475
1477template <typename /*Derived*/, typename F>
1478auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
1479 return std::forward<F>(f);
1480}
1481
1482template <typename Derived, typename Return, typename Class, typename... Args>
1483auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
1484 static_assert(
1485 detail::is_accessible_base_of<Class, Derived>::value,
1486 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1487 return pmf;
1488}
1489
1490template <typename Derived, typename Return, typename Class, typename... Args>
1491auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
1492 static_assert(
1493 detail::is_accessible_base_of<Class, Derived>::value,
1494 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1495 return pmf;
1496}
1497
1498template <typename type_, typename... options>
1499class class_ : public detail::generic_type {
1500 template <typename T>
1501 using is_holder = detail::is_holder_type<type_, T>;
1502 template <typename T>
1503 using is_subtype = detail::is_strict_base_of<type_, T>;
1504 template <typename T>
1505 using is_base = detail::is_strict_base_of<T, type_>;
1506 // struct instead of using here to help MSVC:
1507 template <typename T>
1508 struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
1509
1510public:
1511 using type = type_;
1512 using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
1513 constexpr static bool has_alias = !std::is_void<type_alias>::value;
1514 using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
1515
1516 static_assert(detail::all_of<is_valid_class_option<options>...>::value,
1517 "Unknown/invalid class_ template parameters provided");
1518
1519 static_assert(!has_alias || std::is_polymorphic<type>::value,
1520 "Cannot use an alias class with a non-polymorphic type");
1521
1522 PYBIND11_OBJECT(class_, generic_type, PyType_Check)
1523
1524 template <typename... Extra>
1525 class_(handle scope, const char *name, const Extra &...extra) {
1526 using namespace detail;
1527
1528 // MI can only be specified via class_ template options, not constructor parameters
1529 static_assert(
1530 none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
1531 (constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
1532 constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
1533 // no multiple_inheritance attr
1535 "Error: multiple inheritance bases must be specified via class_ template options");
1536
1537 type_record record;
1538 record.scope = scope;
1539 record.name = name;
1540 record.type = &typeid(type);
1543 record.holder_size = sizeof(holder_type);
1545 record.dealloc = dealloc;
1546 record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
1547
1548 set_operator_new<type>(&record);
1549
1550 /* Register base classes specified via template arguments to class_, if any */
1551 PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
1552
1553 /* Process optional arguments, if any */
1554 process_attributes<Extra...>::init(extra..., &record);
1555
1557
1558 if (has_alias) {
1559 auto &instances = record.module_local ? get_local_internals().registered_types_cpp
1561 instances[std::type_index(typeid(type_alias))]
1562 = instances[std::type_index(typeid(type))];
1563 }
1564 }
1565
1566 template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
1567 static void add_base(detail::type_record &rec) {
1568 rec.add_base(typeid(Base), [](void *src) -> void * {
1569 return static_cast<Base *>(reinterpret_cast<type *>(src));
1570 });
1571 }
1572
1573 template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
1574 static void add_base(detail::type_record &) {}
1575
1576 template <typename Func, typename... Extra>
1577 class_ &def(const char *name_, Func &&f, const Extra &...extra) {
1578 cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
1579 name(name_),
1580 is_method(*this),
1581 sibling(getattr(*this, name_, none())),
1582 extra...);
1583 add_class_method(*this, name_, cf);
1584 return *this;
1585 }
1586
1587 template <typename Func, typename... Extra>
1588 class_ &def_static(const char *name_, Func &&f, const Extra &...extra) {
1589 static_assert(!std::is_member_function_pointer<Func>::value,
1590 "def_static(...) called with a non-static member function pointer");
1591 cpp_function cf(std::forward<Func>(f),
1592 name(name_),
1593 scope(*this),
1594 sibling(getattr(*this, name_, none())),
1595 extra...);
1596 attr(cf.name()) = staticmethod(cf);
1597 return *this;
1598 }
1599
1600 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
1601 class_ &def(const detail::op_<id, ot, L, R> &op, const Extra &...extra) {
1602 op.execute(*this, extra...);
1603 return *this;
1604 }
1605
1606 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
1607 class_ &def_cast(const detail::op_<id, ot, L, R> &op, const Extra &...extra) {
1608 op.execute_cast(*this, extra...);
1609 return *this;
1610 }
1611
1612 template <typename... Args, typename... Extra>
1613 class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra &...extra) {
1615 init.execute(*this, extra...);
1616 return *this;
1617 }
1618
1619 template <typename... Args, typename... Extra>
1620 class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra &...extra) {
1622 init.execute(*this, extra...);
1623 return *this;
1624 }
1625
1626 template <typename... Args, typename... Extra>
1627 class_ &def(detail::initimpl::factory<Args...> &&init, const Extra &...extra) {
1628 std::move(init).execute(*this, extra...);
1629 return *this;
1630 }
1631
1632 template <typename... Args, typename... Extra>
1633 class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
1634 std::move(pf).execute(*this, extra...);
1635 return *this;
1636 }
1637
1638 template <typename Func>
1639 class_ &def_buffer(Func &&func) {
1640 struct capture {
1641 Func func;
1642 };
1643 auto *ptr = new capture{std::forward<Func>(func)};
1644 install_buffer_funcs(
1645 [](PyObject *obj, void *ptr) -> buffer_info * {
1646 detail::make_caster<type> caster;
1647 if (!caster.load(obj, false)) {
1648 return nullptr;
1649 }
1650 return new buffer_info(((capture *) ptr)->func(caster));
1651 },
1652 ptr);
1653 weakref(m_ptr, cpp_function([ptr](handle wr) {
1654 delete ptr;
1655 wr.dec_ref();
1656 }))
1657 .release();
1658 return *this;
1659 }
1660
1661 template <typename Return, typename Class, typename... Args>
1662 class_ &def_buffer(Return (Class::*func)(Args...)) {
1663 return def_buffer([func](type &obj) { return (obj.*func)(); });
1664 }
1665
1666 template <typename Return, typename Class, typename... Args>
1667 class_ &def_buffer(Return (Class::*func)(Args...) const) {
1668 return def_buffer([func](const type &obj) { return (obj.*func)(); });
1669 }
1670
1671 template <typename C, typename D, typename... Extra>
1672 class_ &def_readwrite(const char *name, D C::*pm, const Extra &...extra) {
1673 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
1674 "def_readwrite() requires a class member (or base class member)");
1675 cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this)),
1676 fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
1677 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
1678 return *this;
1679 }
1680
1681 template <typename C, typename D, typename... Extra>
1682 class_ &def_readonly(const char *name, const D C::*pm, const Extra &...extra) {
1683 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
1684 "def_readonly() requires a class member (or base class member)");
1685 cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this));
1686 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
1687 return *this;
1688 }
1689
1690 template <typename D, typename... Extra>
1691 class_ &def_readwrite_static(const char *name, D *pm, const Extra &...extra) {
1692 cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)),
1693 fset([pm](const object &, const D &value) { *pm = value; }, scope(*this));
1694 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
1695 return *this;
1696 }
1697
1698 template <typename D, typename... Extra>
1699 class_ &def_readonly_static(const char *name, const D *pm, const Extra &...extra) {
1700 cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this));
1701 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
1702 return *this;
1703 }
1704
1706 template <typename Getter, typename... Extra>
1707 class_ &def_property_readonly(const char *name, const Getter &fget, const Extra &...extra) {
1709 cpp_function(method_adaptor<type>(fget)),
1710 return_value_policy::reference_internal,
1711 extra...);
1712 }
1713
1715 template <typename... Extra>
1716 class_ &
1717 def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra) {
1718 return def_property(name, fget, nullptr, extra...);
1719 }
1720
1722 template <typename Getter, typename... Extra>
1723 class_ &
1724 def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra) {
1726 name, cpp_function(fget), return_value_policy::reference, extra...);
1727 }
1728
1730 template <typename... Extra>
1732 const cpp_function &fget,
1733 const Extra &...extra) {
1734 return def_property_static(name, fget, nullptr, extra...);
1735 }
1736
1738 template <typename Getter, typename Setter, typename... Extra>
1739 class_ &
1740 def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) {
1741 return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
1742 }
1743 template <typename Getter, typename... Extra>
1745 const Getter &fget,
1746 const cpp_function &fset,
1747 const Extra &...extra) {
1748 return def_property(name,
1749 cpp_function(method_adaptor<type>(fget)),
1750 fset,
1751 return_value_policy::reference_internal,
1752 extra...);
1753 }
1754
1756 template <typename... Extra>
1758 const cpp_function &fget,
1759 const cpp_function &fset,
1760 const Extra &...extra) {
1761 return def_property_static(name, fget, fset, is_method(*this), extra...);
1762 }
1763
1765 template <typename Getter, typename... Extra>
1767 const Getter &fget,
1768 const cpp_function &fset,
1769 const Extra &...extra) {
1770 return def_property_static(
1771 name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1772 }
1773
1775 template <typename... Extra>
1777 const cpp_function &fget,
1778 const cpp_function &fset,
1779 const Extra &...extra) {
1780 static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
1781 "Argument annotations are not allowed for properties");
1782 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1783 auto *rec_active = rec_fget;
1784 if (rec_fget) {
1785 char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific
1786 documentation string */
1787 detail::process_attributes<Extra...>::init(extra..., rec_fget);
1788 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1789 std::free(doc_prev);
1790 rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc);
1791 }
1792 }
1793 if (rec_fset) {
1794 char *doc_prev = rec_fset->doc;
1795 detail::process_attributes<Extra...>::init(extra..., rec_fset);
1796 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1797 std::free(doc_prev);
1798 rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc);
1799 }
1800 if (!rec_active) {
1801 rec_active = rec_fset;
1802 }
1803 }
1804 def_property_static_impl(name, fget, fset, rec_active);
1805 return *this;
1806 }
1807
1808private:
1810 template <typename T>
1811 static void init_holder(detail::instance *inst,
1812 detail::value_and_holder &v_h,
1813 const holder_type * /* unused */,
1814 const std::enable_shared_from_this<T> * /* dummy */) {
1815
1816 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1817 detail::try_get_shared_from_this(v_h.value_ptr<type>()));
1818 if (sh) {
1819 new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
1820 v_h.set_holder_constructed();
1821 }
1822
1823 if (!v_h.holder_constructed() && inst->owned) {
1824 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1825 v_h.set_holder_constructed();
1826 }
1827 }
1828
1829 static void init_holder_from_existing(const detail::value_and_holder &v_h,
1830 const holder_type *holder_ptr,
1831 std::true_type /*is_copy_constructible*/) {
1832 new (std::addressof(v_h.holder<holder_type>()))
1833 holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1834 }
1835
1836 static void init_holder_from_existing(const detail::value_and_holder &v_h,
1837 const holder_type *holder_ptr,
1838 std::false_type /*is_copy_constructible*/) {
1839 new (std::addressof(v_h.holder<holder_type>()))
1840 holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1841 }
1842
1845 static void init_holder(detail::instance *inst,
1846 detail::value_and_holder &v_h,
1847 const holder_type *holder_ptr,
1848 const void * /* dummy -- not enable_shared_from_this<T>) */) {
1849 if (holder_ptr) {
1850 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1851 v_h.set_holder_constructed();
1852 } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
1853 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1854 v_h.set_holder_constructed();
1855 }
1856 }
1857
1862 static void init_instance(detail::instance *inst, const void *holder_ptr) {
1863 auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
1864 if (!v_h.instance_registered()) {
1865 register_instance(inst, v_h.value_ptr(), v_h.type);
1866 v_h.set_instance_registered();
1867 }
1868 init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
1869 }
1870
1872 static void dealloc(detail::value_and_holder &v_h) {
1873 // We could be deallocating because we are cleaning up after a Python exception.
1874 // If so, the Python error indicator will be set. We need to clear that before
1875 // running the destructor, in case the destructor code calls more Python.
1876 // If we don't, the Python API will exit with an exception, and pybind11 will
1877 // throw error_already_set from the C++ destructor which is forbidden and triggers
1878 // std::terminate().
1880 if (v_h.holder_constructed()) {
1881 v_h.holder<holder_type>().~holder_type();
1882 v_h.set_holder_constructed(false);
1883 } else {
1884 detail::call_operator_delete(
1885 v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align);
1886 }
1887 v_h.value_ptr() = nullptr;
1888 }
1889
1890 static detail::function_record *get_function_record(handle h) {
1891 h = detail::get_function(h);
1892 return h ? (detail::function_record *) reinterpret_borrow<capsule>(
1893 PyCFunction_GET_SELF(h.ptr()))
1894 : nullptr;
1895 }
1896};
1897
1899template <typename... Args>
1900detail::initimpl::constructor<Args...> init() {
1901 return {};
1902}
1905template <typename... Args>
1906detail::initimpl::alias_constructor<Args...> init_alias() {
1907 return {};
1908}
1909
1911template <typename Func, typename Ret = detail::initimpl::factory<Func>>
1912Ret init(Func &&f) {
1913 return {std::forward<Func>(f)};
1914}
1915
1919template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1920Ret init(CFunc &&c, AFunc &&a) {
1921 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1922}
1923
1926template <typename GetState, typename SetState>
1927detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
1928 return {std::forward<GetState>(g), std::forward<SetState>(s)};
1929}
1930
1932
1934 dict entries = arg.get_type().attr("__entries");
1935 for (auto kv : entries) {
1936 if (handle(kv.second[int_(0)]).equal(arg)) {
1937 return pybind11::str(kv.first);
1938 }
1939 }
1940 return "???";
1941}
1942
1944 enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) {}
1945
1946 PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
1947 m_base.attr("__entries") = dict();
1948 auto property = handle((PyObject *) &PyProperty_Type);
1949 auto static_property = handle((PyObject *) get_internals().static_property_type);
1950
1951 m_base.attr("__repr__") = cpp_function(
1952 [](const object &arg) -> str {
1954 object type_name = type.attr("__name__");
1955 return pybind11::str("<{}.{}: {}>").format(type_name, enum_name(arg), int_(arg));
1956 },
1957 name("__repr__"),
1958 is_method(m_base));
1959
1960 m_base.attr("name") = property(cpp_function(&enum_name, name("name"), is_method(m_base)));
1961
1962 m_base.attr("__str__") = cpp_function(
1963 [](handle arg) -> str {
1964 object type_name = type::handle_of(arg).attr("__name__");
1965 return pybind11::str("{}.{}").format(type_name, enum_name(arg));
1966 },
1967 name("name"),
1968 is_method(m_base));
1969
1970 m_base.attr("__doc__") = static_property(
1972 [](handle arg) -> std::string {
1973 std::string docstring;
1974 dict entries = arg.attr("__entries");
1975 if (((PyTypeObject *) arg.ptr())->tp_doc) {
1976 docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) + "\n\n";
1977 }
1978 docstring += "Members:";
1979 for (auto kv : entries) {
1980 auto key = std::string(pybind11::str(kv.first));
1981 auto comment = kv.second[int_(1)];
1982 docstring += "\n\n " + key;
1983 if (!comment.is_none()) {
1984 docstring += " : " + (std::string) pybind11::str(comment);
1985 }
1986 }
1987 return docstring;
1988 },
1989 name("__doc__")),
1990 none(),
1991 none(),
1992 "");
1993
1994 m_base.attr("__members__") = static_property(cpp_function(
1995 [](handle arg) -> dict {
1996 dict entries = arg.attr("__entries"),
1997 m;
1998 for (auto kv : entries) {
1999 m[kv.first] = kv.second[int_(0)];
2000 }
2001 return m;
2002 },
2003 name("__members__")),
2004 none(),
2005 none(),
2006 "");
2007
2008#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
2009 m_base.attr(op) = cpp_function( \
2010 [](const object &a, const object &b) { \
2011 if (!type::handle_of(a).is(type::handle_of(b))) \
2012 strict_behavior; /* NOLINT(bugprone-macro-parentheses) */ \
2013 return expr; \
2014 }, \
2015 name(op), \
2016 is_method(m_base), \
2017 arg("other"))
2018
2019#define PYBIND11_ENUM_OP_CONV(op, expr) \
2020 m_base.attr(op) = cpp_function( \
2021 [](const object &a_, const object &b_) { \
2022 int_ a(a_), b(b_); \
2023 return expr; \
2024 }, \
2025 name(op), \
2026 is_method(m_base), \
2027 arg("other"))
2028
2029#define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
2030 m_base.attr(op) = cpp_function( \
2031 [](const object &a_, const object &b) { \
2032 int_ a(a_); \
2033 return expr; \
2034 }, \
2035 name(op), \
2036 is_method(m_base), \
2037 arg("other"))
2038
2039 if (is_convertible) {
2040 PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
2041 PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
2042
2043 if (is_arithmetic) {
2044 PYBIND11_ENUM_OP_CONV("__lt__", a < b);
2045 PYBIND11_ENUM_OP_CONV("__gt__", a > b);
2046 PYBIND11_ENUM_OP_CONV("__le__", a <= b);
2047 PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
2048 PYBIND11_ENUM_OP_CONV("__and__", a & b);
2049 PYBIND11_ENUM_OP_CONV("__rand__", a & b);
2050 PYBIND11_ENUM_OP_CONV("__or__", a | b);
2051 PYBIND11_ENUM_OP_CONV("__ror__", a | b);
2052 PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
2053 PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
2054 m_base.attr("__invert__")
2055 = cpp_function([](const object &arg) { return ~(int_(arg)); },
2056 name("__invert__"),
2057 is_method(m_base));
2058 }
2059 } else {
2060 PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
2061 PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
2062
2063 if (is_arithmetic) {
2064#define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
2065 PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
2066 PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
2067 PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
2068 PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
2069#undef PYBIND11_THROW
2070 }
2071 }
2072
2073#undef PYBIND11_ENUM_OP_CONV_LHS
2074#undef PYBIND11_ENUM_OP_CONV
2075#undef PYBIND11_ENUM_OP_STRICT
2076
2077 m_base.attr("__getstate__") = cpp_function(
2078 [](const object &arg) { return int_(arg); }, name("__getstate__"), is_method(m_base));
2079
2080 m_base.attr("__hash__") = cpp_function(
2081 [](const object &arg) { return int_(arg); }, name("__hash__"), is_method(m_base));
2082 }
2083
2084 PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc = nullptr) {
2085 dict entries = m_base.attr("__entries");
2086 str name(name_);
2087 if (entries.contains(name)) {
2088 std::string type_name = (std::string) str(m_base.attr("__name__"));
2089 throw value_error(type_name + ": element \"" + std::string(name_)
2090 + "\" already exists!");
2091 }
2092
2093 entries[name] = std::make_pair(value, doc);
2094 m_base.attr(name) = value;
2095 }
2096
2098 dict entries = m_base.attr("__entries");
2099 for (auto kv : entries) {
2100 m_parent.attr(kv.first) = kv.second[int_(0)];
2101 }
2102 }
2103
2106};
2107
2108template <bool is_signed, size_t length>
2110template <>
2111struct equivalent_integer<true, 1> {
2112 using type = int8_t;
2113};
2114template <>
2115struct equivalent_integer<false, 1> {
2116 using type = uint8_t;
2117};
2118template <>
2119struct equivalent_integer<true, 2> {
2120 using type = int16_t;
2121};
2122template <>
2123struct equivalent_integer<false, 2> {
2124 using type = uint16_t;
2125};
2126template <>
2127struct equivalent_integer<true, 4> {
2128 using type = int32_t;
2129};
2130template <>
2131struct equivalent_integer<false, 4> {
2132 using type = uint32_t;
2133};
2134template <>
2135struct equivalent_integer<true, 8> {
2136 using type = int64_t;
2137};
2138template <>
2139struct equivalent_integer<false, 8> {
2140 using type = uint64_t;
2141};
2142
2143template <typename IntLike>
2146
2148
2149
2150template <typename Type>
2151class enum_ : public class_<Type> {
2152public:
2154 using Base::attr;
2155 using Base::def;
2158 using Underlying = typename std::underlying_type<Type>::type;
2159 // Scalar is the integer representation of underlying type
2160 using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2161 std::is_same<Underlying, bool>>::value,
2162 detail::equivalent_integer_t<Underlying>,
2163 Underlying>;
2164
2165 template <typename... Extra>
2166 enum_(const handle &scope, const char *name, const Extra &...extra)
2167 : class_<Type>(scope, name, extra...), m_base(*this, scope) {
2168 constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
2169 constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
2170 m_base.init(is_arithmetic, is_convertible);
2171
2172 def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
2173 def_property_readonly("value", [](Type value) { return (Scalar) value; });
2174 def("__int__", [](Type value) { return (Scalar) value; });
2175 def("__index__", [](Type value) { return (Scalar) value; });
2176#if PY_MAJOR_VERSION < 3
2177 def("__long__", [](Type value) { return (Scalar) value; });
2178#endif
2179 attr("__setstate__") = cpp_function(
2180 [](detail::value_and_holder &v_h, Scalar arg) {
2181 detail::initimpl::setstate<Base>(
2182 v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type);
2183 },
2184 detail::is_new_style_constructor(),
2185 pybind11::name("__setstate__"),
2186 is_method(*this),
2187 arg("state"));
2188 }
2189
2192 m_base.export_values();
2193 return *this;
2194 }
2195
2197 enum_ &value(char const *name, Type value, const char *doc = nullptr) {
2198 m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
2199 return *this;
2200 }
2201
2202private:
2203 detail::enum_base m_base;
2204};
2205
2207
2209 if (!nurse || !patient) {
2210 pybind11_fail("Could not activate keep_alive!");
2211 }
2212
2213 if (patient.is_none() || nurse.is_none()) {
2214 return; /* Nothing to keep alive or nothing to be kept alive by */
2215 }
2216
2217 auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
2218 if (!tinfo.empty()) {
2219 /* It's a pybind-registered type, so we can store the patient in the
2220 * internal list. */
2221 add_patient(nurse.ptr(), patient.ptr());
2222 } else {
2223 /* Fall back to clever approach based on weak references taken from
2224 * Boost.Python. This is not used for pybind-registered types because
2225 * the objects can be destroyed out-of-order in a GC pass. */
2226 cpp_function disable_lifesupport([patient](handle weakref) {
2227 patient.dec_ref();
2228 weakref.dec_ref();
2229 });
2230
2231 weakref wr(nurse, disable_lifesupport);
2232
2233 patient.inc_ref(); /* reference patient and leak the weak reference */
2234 (void) wr.release();
2235 }
2236}
2237
2239keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
2240 auto get_arg = [&](size_t n) {
2241 if (n == 0) {
2242 return ret;
2243 }
2244 if (n == 1 && call.init_self) {
2245 return call.init_self;
2246 }
2247 if (n <= call.args.size()) {
2248 return call.args[n - 1];
2249 }
2250 return handle();
2251 };
2252
2253 keep_alive_impl(get_arg(Nurse), get_arg(Patient));
2254}
2255
2256inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
2258 auto res = get_internals()
2260#ifdef __cpp_lib_unordered_map_try_emplace
2261 .try_emplace(type);
2262#else
2263 .emplace(type, std::vector<detail::type_info *>());
2264#endif
2265 if (res.second) {
2266 // New cache entry created; set up a weak reference to automatically remove it if the type
2267 // gets destroyed:
2268 weakref((PyObject *) type, cpp_function([type](handle wr) {
2270
2271 // TODO consolidate the erasure code in pybind11_meta_dealloc() in class.h
2272 auto &cache = get_internals().inactive_override_cache;
2273 for (auto it = cache.begin(), last = cache.end(); it != last;) {
2274 if (it->first == reinterpret_cast<PyObject *>(type)) {
2275 it = cache.erase(it);
2276 } else {
2277 ++it;
2278 }
2279 }
2280
2281 wr.dec_ref();
2282 }))
2283 .release();
2284 }
2285
2286 return res;
2287}
2288
2289/* There are a large number of apparently unused template arguments because
2290 * each combination requires a separate py::class_ registration.
2291 */
2292template <typename Access,
2293 return_value_policy Policy,
2294 typename Iterator,
2295 typename Sentinel,
2296 typename ValueType,
2297 typename... Extra>
2299 Iterator it;
2300 Sentinel end;
2302};
2303
2304// Note: these helpers take the iterator by non-const reference because some
2305// iterators in the wild can't be dereferenced when const. The & after Iterator
2306// is required for MSVC < 16.9. SFINAE cannot be reused for result_type due to
2307// bugs in ICC, NVCC, and PGI compilers. See PR #3293.
2308template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
2310 using result_type = decltype(*std::declval<Iterator &>());
2311 // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
2312 result_type operator()(Iterator &it) const { return *it; }
2313};
2314
2315template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).first)>
2317private:
2318 using pair_type = decltype(*std::declval<Iterator &>());
2319
2320public:
2321 /* If either the pair itself or the element of the pair is a reference, we
2322 * want to return a reference, otherwise a value. When the decltype
2323 * expression is parenthesized it is based on the value category of the
2324 * expression; otherwise it is the declared type of the pair member.
2325 * The use of declval<pair_type> in the second branch rather than directly
2326 * using *std::declval<Iterator &>() is a workaround for nvcc
2327 * (it's not used in the first branch because going via decltype and back
2328 * through declval does not perfectly preserve references).
2329 */
2332 decltype(((*std::declval<Iterator &>()).first)),
2333 decltype(std::declval<pair_type>().first)>;
2334 result_type operator()(Iterator &it) const { return (*it).first; }
2335};
2336
2337template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
2339private:
2340 using pair_type = decltype(*std::declval<Iterator &>());
2341
2342public:
2345 decltype(((*std::declval<Iterator &>()).second)),
2346 decltype(std::declval<pair_type>().second)>;
2347 result_type operator()(Iterator &it) const { return (*it).second; }
2348};
2349
2350template <typename Access,
2351 return_value_policy Policy,
2352 typename Iterator,
2353 typename Sentinel,
2354 typename ValueType,
2355 typename... Extra>
2356iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra) {
2357 using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
2358 // TODO: state captures only the types of Extra, not the values
2359
2360 if (!detail::get_type_info(typeid(state), false)) {
2361 class_<state>(handle(), "iterator", pybind11::module_local())
2362 .def("__iter__", [](state &s) -> state & { return s; })
2363 .def(
2364 "__next__",
2365 [](state &s) -> ValueType {
2366 if (!s.first_or_done) {
2367 ++s.it;
2368 } else {
2369 s.first_or_done = false;
2370 }
2371 if (s.it == s.end) {
2372 s.first_or_done = true;
2373 throw stop_iteration();
2374 }
2375 return Access()(s.it);
2376 // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
2377 },
2378 std::forward<Extra>(extra)...,
2379 Policy);
2380 }
2381
2382 return cast(state{first, last, true});
2383}
2384
2386
2387
2389 typename Iterator,
2390 typename Sentinel,
2391 typename ValueType = typename detail::iterator_access<Iterator>::result_type,
2392 typename... Extra>
2393iterator make_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2394 return detail::make_iterator_impl<detail::iterator_access<Iterator>,
2395 Policy,
2396 Iterator,
2397 Sentinel,
2398 ValueType,
2399 Extra...>(first, last, std::forward<Extra>(extra)...);
2400}
2401
2405 typename Iterator,
2406 typename Sentinel,
2407 typename KeyType = typename detail::iterator_key_access<Iterator>::result_type,
2408 typename... Extra>
2409iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2410 return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
2411 Policy,
2412 Iterator,
2413 Sentinel,
2414 KeyType,
2415 Extra...>(first, last, std::forward<Extra>(extra)...);
2416}
2417
2421 typename Iterator,
2422 typename Sentinel,
2423 typename ValueType = typename detail::iterator_value_access<Iterator>::result_type,
2424 typename... Extra>
2425iterator make_value_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2426 return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
2427 Policy,
2428 Iterator,
2429 Sentinel,
2430 ValueType,
2431 Extra...>(first, last, std::forward<Extra>(extra)...);
2432}
2433
2437 typename Type,
2438 typename... Extra>
2439iterator make_iterator(Type &value, Extra &&...extra) {
2440 return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
2441}
2442
2446 typename Type,
2447 typename... Extra>
2448iterator make_key_iterator(Type &value, Extra &&...extra) {
2449 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
2450}
2451
2455 typename Type,
2456 typename... Extra>
2457iterator make_value_iterator(Type &value, Extra &&...extra) {
2458 return make_value_iterator<Policy>(std::begin(value), std::end(value), extra...);
2459}
2460
2461template <typename InputType, typename OutputType>
2463 struct set_flag {
2464 bool &flag;
2465 explicit set_flag(bool &flag_) : flag(flag_) { flag_ = true; }
2466 ~set_flag() { flag = false; }
2467 };
2468 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
2469 static bool currently_used = false;
2470 if (currently_used) { // implicit conversions are non-reentrant
2471 return nullptr;
2472 }
2473 set_flag flag_helper(currently_used);
2474 if (!detail::make_caster<InputType>().load(obj, false)) {
2475 return nullptr;
2476 }
2477 tuple args(1);
2478 args[0] = obj;
2479 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
2480 if (result == nullptr) {
2481 PyErr_Clear();
2482 }
2483 return result;
2484 };
2485
2486 if (auto *tinfo = detail::get_type_info(typeid(OutputType))) {
2487 tinfo->implicit_conversions.push_back(implicit_caster);
2488 } else {
2489 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
2490 }
2491}
2492
2494 detail::get_internals().registered_exception_translators.push_front(
2495 std::forward<ExceptionTranslator>(translator));
2496}
2497
2505 detail::get_local_internals().registered_exception_translators.push_front(
2506 std::forward<ExceptionTranslator>(translator));
2507}
2508
2516template <typename type>
2517class exception : public object {
2518public:
2519 exception() = default;
2520 exception(handle scope, const char *name, handle base = PyExc_Exception) {
2521 std::string full_name
2522 = scope.attr("__name__").cast<std::string>() + std::string(".") + name;
2523 m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), NULL);
2524 if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name)) {
2525 pybind11_fail("Error during initialization: multiple incompatible "
2526 "definitions with name \""
2527 + std::string(name) + "\"");
2528 }
2529 scope.attr(name) = *this;
2530 }
2531
2532 // Sets the current python exception to this exception object with the given message
2533 void operator()(const char *message) { PyErr_SetString(m_ptr, message); }
2534};
2535
2537// Returns a reference to a function-local static exception object used in the simple
2538// register_exception approach below. (It would be simpler to have the static local variable
2539// directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
2540template <typename CppException>
2542 static exception<CppException> ex;
2543 return ex;
2544}
2545
2546// Helper function for register_exception and register_local_exception
2547template <typename CppException>
2549register_exception_impl(handle scope, const char *name, handle base, bool isLocal) {
2550 auto &ex = detail::get_exception_object<CppException>();
2551 if (!ex) {
2553 }
2554
2555 auto register_func
2557
2558 register_func([](std::exception_ptr p) {
2559 if (!p) {
2560 return;
2561 }
2562 try {
2563 std::rethrow_exception(p);
2564 } catch (const CppException &e) {
2565 detail::get_exception_object<CppException>()(e.what());
2566 }
2567 });
2568 return ex;
2569}
2570
2572
2573
2579template <typename CppException>
2581register_exception(handle scope, const char *name, handle base = PyExc_Exception) {
2582 return detail::register_exception_impl<CppException>(scope, name, base, false /* isLocal */);
2583}
2584
2593template <typename CppException>
2595register_local_exception(handle scope, const char *name, handle base = PyExc_Exception) {
2596 return detail::register_exception_impl<CppException>(scope, name, base, true /* isLocal */);
2597}
2598
2600PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) {
2601 auto strings = tuple(args.size());
2602 for (size_t i = 0; i < args.size(); ++i) {
2603 strings[i] = str(args[i]);
2604 }
2605 auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
2606 auto line = sep.attr("join")(strings);
2607
2608 object file;
2609 if (kwargs.contains("file")) {
2610 file = kwargs["file"].cast<object>();
2611 } else {
2612 try {
2613 file = module_::import("sys").attr("stdout");
2614 } catch (const error_already_set &) {
2615 /* If print() is called from code that is executed as
2616 part of garbage collection during interpreter shutdown,
2617 importing 'sys' can fail. Give up rather than crashing the
2618 interpreter in this case. */
2619 return;
2620 }
2621 }
2622
2623 auto write = file.attr("write");
2624 write(line);
2625 write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
2626
2627 if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) {
2628 file.attr("flush")();
2629 }
2630}
2632
2633template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
2634void print(Args &&...args) {
2635 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
2636 detail::print(c.args(), c.kwargs());
2637}
2638
2640 if (m_type) {
2646 }
2647}
2648
2650inline function
2651get_type_override(const void *this_ptr, const type_info *this_type, const char *name) {
2652 handle self = get_object_handle(this_ptr, this_type);
2653 if (!self) {
2654 return function();
2655 }
2657 auto key = std::make_pair(type.ptr(), name);
2658
2659 /* Cache functions that aren't overridden in Python to avoid
2660 many costly Python dictionary lookups below */
2661 auto &cache = get_internals().inactive_override_cache;
2662 if (cache.find(key) != cache.end()) {
2663 return function();
2664 }
2665
2666 function override = getattr(self, name, function());
2667 if (override.is_cpp_function()) {
2668 cache.insert(key);
2669 return function();
2670 }
2671
2672 /* Don't call dispatch code if invoked from overridden function.
2673 Unfortunately this doesn't work on PyPy. */
2674#if !defined(PYPY_VERSION)
2675# if PY_VERSION_HEX >= 0x03090000
2676 PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
2677 if (frame != nullptr) {
2678 PyCodeObject *f_code = PyFrame_GetCode(frame);
2679 // f_code is guaranteed to not be NULL
2680 if ((std::string) str(f_code->co_name) == name && f_code->co_argcount > 0) {
2681 PyObject *locals = PyEval_GetLocals();
2682 if (locals != nullptr) {
2683 PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code, "co_varnames");
2684 PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
2685 Py_DECREF(co_varnames);
2686 PyObject *self_caller = dict_getitem(locals, self_arg);
2687 if (self_caller == self.ptr()) {
2688 Py_DECREF(f_code);
2689 Py_DECREF(frame);
2690 return function();
2691 }
2692 }
2693 }
2694 Py_DECREF(f_code);
2695 Py_DECREF(frame);
2696 }
2697# else
2698 PyFrameObject *frame = PyThreadState_Get()->frame;
2699 if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name
2700 && frame->f_code->co_argcount > 0) {
2701 PyFrame_FastToLocals(frame);
2702 PyObject *self_caller
2703 = dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2704 if (self_caller == self.ptr()) {
2705 return function();
2706 }
2707 }
2708# endif
2709
2710#else
2711 /* PyPy currently doesn't provide a detailed cpyext emulation of
2712 frame objects, so we have to emulate this using Python. This
2713 is going to be slow..*/
2714 dict d;
2715 d["self"] = self;
2716 d["name"] = pybind11::str(name);
2717 PyObject *result
2718 = PyRun_String("import inspect\n"
2719 "frame = inspect.currentframe()\n"
2720 "if frame is not None:\n"
2721 " frame = frame.f_back\n"
2722 " if frame is not None and str(frame.f_code.co_name) == name and "
2723 "frame.f_code.co_argcount > 0:\n"
2724 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2725 " if self_caller == self:\n"
2726 " self = None\n",
2727 Py_file_input,
2728 d.ptr(),
2729 d.ptr());
2730 if (result == nullptr)
2731 throw error_already_set();
2732 Py_DECREF(result);
2733 if (d["self"].is_none())
2734 return function();
2735#endif
2736
2737 return override;
2738}
2740
2741
2750template <class T>
2751function get_override(const T *this_ptr, const char *name) {
2752 auto *tinfo = detail::get_type_info(typeid(T));
2753 return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
2754}
2755
2756#define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
2757 do { \
2758 pybind11::gil_scoped_acquire gil; \
2759 pybind11::function override \
2760 = pybind11::get_override(static_cast<const cname *>(this), name); \
2761 if (override) { \
2762 auto o = override(__VA_ARGS__); \
2763 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
2764 static pybind11::detail::override_caster_t<ret_type> caster; \
2765 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
2766 } \
2767 return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2768 } \
2769 } while (false)
2770
2789#define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
2790 do { \
2791 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2792 return cname::fn(__VA_ARGS__); \
2793 } while (false)
2794
2799#define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
2800 do { \
2801 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2802 pybind11::pybind11_fail( \
2803 "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
2804 } while (false)
2805
2831#define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
2832 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2833
2838#define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
2839 PYBIND11_OVERRIDE_PURE_NAME( \
2840 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2841
2842// Deprecated versions
2843
2844PYBIND11_DEPRECATED("get_type_overload has been deprecated")
2845inline function
2846get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
2847 return detail::get_type_override(this_ptr, this_type, name);
2848}
2849
2850template <class T>
2851inline function get_overload(const T *this_ptr, const char *name) {
2852 return get_override(this_ptr, name);
2853}
2854
2855#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
2856 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
2857#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
2858 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
2859#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
2860 PYBIND11_OVERRIDE_PURE_NAME( \
2861 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
2862#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
2863 PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
2864#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2865 PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
2866
2868
2869#if defined(__GNUC__) && __GNUC__ == 7
2870# pragma GCC diagnostic pop // -Wnoexcept-type
2871#endif
Definition: pytypes.h:1776
Helper class which loads arguments for C++ functions called from Python.
Definition: cast.h:1380
class_ & def(detail::initimpl::pickle_factory< Args... > &&pf, const Extra &...extra)
Definition: pybind11.h:1633
class_ & def_property_readonly_static(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
Definition: pybind11.h:1731
static void init_holder(detail::instance *inst, detail::value_and_holder &v_h, const holder_type *, const std::enable_shared_from_this< T > *)
Initialize holder object, variant 1: object derives from enable_shared_from_this.
Definition: pybind11.h:1811
static void add_base(detail::type_record &rec)
Definition: pybind11.h:1567
class_ & def_static(const char *name_, Func &&f, const Extra &...extra)
Definition: pybind11.h:1588
detail::exactly_one_t< is_subtype, void, options... > type_alias
Definition: pybind11.h:1512
class_ & def_readonly_static(const char *name, const D *pm, const Extra &...extra)
Definition: pybind11.h:1699
detail::is_strict_base_of< T, type_ > is_base
Definition: pybind11.h:1505
static void init_instance(detail::instance *inst, const void *holder_ptr)
Performs instance initialization including constructing a holder and registering the known instance.
Definition: pybind11.h:1862
class_ & def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
Definition: pybind11.h:1757
detail::is_holder_type< type_, T > is_holder
Definition: pybind11.h:1501
static detail::function_record * get_function_record(handle h)
Definition: pybind11.h:1890
class_ & def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
Uses return_value_policy::reference by default.
Definition: pybind11.h:1766
class_ & def(detail::initimpl::factory< Args... > &&init, const Extra &...extra)
Definition: pybind11.h:1627
class_ & def(const char *name_, Func &&f, const Extra &...extra)
Definition: pybind11.h:1577
static void add_base(detail::type_record &)
Definition: pybind11.h:1574
static constexpr bool has_alias
Definition: pybind11.h:1513
class_ & def_readwrite(const char *name, D C::*pm, const Extra &...extra)
Definition: pybind11.h:1672
class_ & def_buffer(Return(Class::*func)(Args...))
Definition: pybind11.h:1662
class_ & def_readonly(const char *name, const D C::*pm, const Extra &...extra)
Definition: pybind11.h:1682
class_ & def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
Definition: pybind11.h:1776
class_ & def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
Definition: pybind11.h:1744
class_ & def_cast(const detail::op_< id, ot, L, R > &op, const Extra &...extra)
Definition: pybind11.h:1607
static void dealloc(detail::value_and_holder &v_h)
Deallocates an instance; via holder, if constructed; otherwise via operator delete.
Definition: pybind11.h:1872
class_ & def_buffer(Return(Class::*func)(Args...) const)
Definition: pybind11.h:1667
class_ & def_readwrite_static(const char *name, D *pm, const Extra &...extra)
Definition: pybind11.h:1691
class_ & def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
Definition: pybind11.h:1717
class_(handle scope, const char *name, const Extra &...extra)
Definition: pybind11.h:1525
type_ type
Definition: pybind11.h:1511
class_ & def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
Definition: pybind11.h:1740
class_ & def_property_readonly(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
Definition: pybind11.h:1707
class_ & def(const detail::op_< id, ot, L, R > &op, const Extra &...extra)
Definition: pybind11.h:1601
class_ & def(const detail::initimpl::constructor< Args... > &init, const Extra &...extra)
Definition: pybind11.h:1613
class_ & def_buffer(Func &&func)
Definition: pybind11.h:1639
static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::true_type)
Definition: pybind11.h:1829
class_ & def(const detail::initimpl::alias_constructor< Args... > &init, const Extra &...extra)
Definition: pybind11.h:1620
detail::exactly_one_t< is_holder, std::unique_ptr< type >, options... > holder_type
Definition: pybind11.h:1514
class_ & def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference by default.
Definition: pybind11.h:1724
static void init_holder(detail::instance *inst, detail::value_and_holder &v_h, const holder_type *holder_ptr, const void *)
Initialize holder object, variant 2: try to construct from existing holder object,...
Definition: pybind11.h:1845
static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::false_type)
Definition: pybind11.h:1836
detail::is_strict_base_of< type_, T > is_subtype
Definition: pybind11.h:1503
char * operator()(const char *s)
Definition: pybind11.h:320
std::vector< char * > strings
Definition: pybind11.h:328
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
Definition: pybind11.h:81
std::unique_ptr< detail::function_record, InitializingFunctionRecordDeleter > unique_function_record
Definition: pybind11.h:158
static PyObject * dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in)
Main dispatch logic for calls to functions bound using pybind11.
Definition: pybind11.h:667
cpp_function(Return(Class::*f)(Arg...) const, const Extra &...extra)
Construct a cpp_function from a class method (const, no ref-qualifier)
Definition: pybind11.h:129
void initialize(Func &&f, Return(*)(Args...), const Extra &...extra)
Special internal constructor for functors, lambda functions, etc.
Definition: pybind11.h:167
cpp_function(Return(Class::*f)(Arg...) const &, const Extra &...extra)
Construct a cpp_function from a class method (const, lvalue ref-qualifier) A copy of the overload for...
Definition: pybind11.h:141
cpp_function()=default
object name() const
Return the function name.
Definition: pybind11.h:149
cpp_function(std::nullptr_t)
Definition: pybind11.h:85
cpp_function(Return(Class::*f)(Arg...) &, const Extra &...extra)
Construct a cpp_function from a class method (non-const, lvalue ref-qualifier) A copy of the overload...
Definition: pybind11.h:119
void initialize_generic(unique_function_record &&unique_rec, const char *text, const std::type_info *const *types, size_t args)
Register a function call with Python (generic non-templated code goes here)
Definition: pybind11.h:332
PYBIND11_NOINLINE unique_function_record make_function_record()
Space optimization: don't inline this frequently instantiated fragment.
Definition: pybind11.h:161
cpp_function(Func &&f, const Extra &...extra)
Construct a cpp_function from a lambda function (possibly with internal state)
Definition: pybind11.h:99
cpp_function(Return(Class::*f)(Arg...), const Extra &...extra)
Construct a cpp_function from a class method (non-const, no ref-qualifier)
Definition: pybind11.h:107
static void destruct(detail::function_record *rec, bool free_strings=true)
When a cpp_function is GCed, release any memory allocated by pybind11.
Definition: pybind11.h:621
cpp_function(Return(*f)(Args...), const Extra &...extra)
Construct a cpp_function from a vanilla function pointer.
Definition: pybind11.h:90
Definition: pytypes.h:1694
bool empty() const
Definition: pytypes.h:1710
bool contains(T &&key) const
Definition: pytypes.h:1715
Binds C++ enumerations and enumeration classes to Python.
Definition: pybind11.h:2151
detail::enum_base m_base
Definition: pybind11.h:2203
enum_ & value(char const *name, Type value, const char *doc=nullptr)
Add an enumeration entry.
Definition: pybind11.h:2197
detail::conditional_t< detail::any_of< detail::is_std_char_type< Underlying >, std::is_same< Underlying, bool > >::value, detail::equivalent_integer_t< Underlying >, Underlying > Scalar
Definition: pybind11.h:2163
typename std::underlying_type< Type >::type Underlying
Definition: pybind11.h:2158
enum_ & export_values()
Export enumeration entries into the parent scope.
Definition: pybind11.h:2191
enum_(const handle &scope, const char *name, const Extra &...extra)
Definition: pybind11.h:2166
Fetch and hold an error which was already set in Python.
Definition: pytypes.h:379
object m_trace
Definition: pytypes.h:431
void restore()
Give the currently-held error back to Python, if any.
Definition: pytypes.h:395
~error_already_set() override
Definition: pybind11.h:2639
object m_value
Definition: pytypes.h:431
Wrapper to generate a new Python exception type.
Definition: pybind11.h:2517
exception()=default
exception(handle scope, const char *name, handle base=PyExc_Exception)
Definition: pybind11.h:2520
void operator()(const char *message)
Definition: pybind11.h:2533
Generic support for creating new Python heap types.
Definition: pybind11.h:1304
void initialize(const type_record &rec)
Definition: pybind11.h:1308
void mark_parents_nonsimple(PyTypeObject *value)
Helper function which tags all parents of a type using mult. inheritance.
Definition: pybind11.h:1368
void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *), void *get_buffer_data)
Definition: pybind11.h:1379
void def_property_static_impl(const char *name, handle fget, handle fset, detail::function_record *rec_func)
Definition: pybind11.h:1396
\rst Holds a reference to a Python object (no reference counting)
Definition: pytypes.h:194
PyObject * m_ptr
Definition: pytypes.h:246
const handle & inc_ref() const &
\rst Manually increase the reference count of the Python object.
Definition: pytypes.h:211
const handle & dec_ref() const &
\rst Manually decrease the reference count of the Python object.
Definition: pytypes.h:221
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
result_type operator()(Iterator &it) const
Definition: pybind11.h:2334
decltype(*std::declval< Iterator & >()) pair_type
Definition: pybind11.h:2318
conditional_t< std::is_reference< decltype(*std::declval< Iterator & >())>::value, decltype(((*std::declval< Iterator & >()).first)), decltype(std::declval< pair_type >().first)> result_type
Definition: pybind11.h:2333
result_type operator()(Iterator &it) const
Definition: pybind11.h:2347
decltype(*std::declval< Iterator & >()) pair_type
Definition: pybind11.h:2340
conditional_t< std::is_reference< decltype(*std::declval< Iterator & >())>::value, decltype(((*std::declval< Iterator & >()).second)), decltype(std::declval< pair_type >().second)> result_type
Definition: pybind11.h:2346
\rst Wraps a Python iterator so that it can also be used as a C++ input iterator
Definition: pytypes.h:1102
size_t size() const
Definition: pytypes.h:1757
A life support system for temporary objects created by type_caster::load().
Wrapper for Python extension modules.
Definition: pybind11.h:1145
module_ def_submodule(const char *name, const char *doc=nullptr)
\rst Create and return a new Python submodule with the given name and docstring.
Definition: pybind11.h:1188
static module_ create_extension_module(const char *name, const char *doc, module_def *def)
\rst Create a new top-level module that can be used as the main module of a C extension.
Definition: pybind11.h:1246
static module_ import(const char *name)
Import and return a module or throws error_already_set.
Definition: pybind11.h:1200
PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite=false)
\rst Adds an object to the module using the given name.
Definition: pybind11.h:1224
void reload()
Reload the module or throws error_already_set.
Definition: pybind11.h:1209
module_ & def(const char *name_, Func &&f, const Extra &...extra)
\rst Create Python binding for a new function within the module scope.
Definition: pybind11.h:1165
Definition: pytypes.h:1422
\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
T cast() const &
static bool show_function_signatures()
Definition: options.h:56
static bool show_user_defined_docstrings()
Definition: options.h:52
Definition: pytypes.h:1200
size_t size() const
Definition: pytypes.h:1678
static PYBIND11_NOINLINE void * local_load(PyObject *src, const type_info *ti)
Definition: pytypes.h:1167
static handle handle_of()
Convert C++ type to handle if previously registered.
Definition: cast.h:1643
dict globals()
Return a dictionary representing the global variables in the current execution frame,...
Definition: pybind11.h:1288
object getattr(handle obj, handle name)
Definition: pytypes.h:537
str repr(handle h)
Definition: pytypes.h:2027
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:569
bool hasattr(handle obj, handle name)
Definition: pytypes.h:517
constexpr bool args_are_all_keyword_or_ds()
Definition: pytypes.h:1690
_Type< T > Type()
typename exactly_one_t< is_call_guard, call_guard<>, Extra... >::type extract_guard_t
Extract the type from the first call_guard in Extras... (or void_type if none found)
Definition: attr.h:663
constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs)
Check the number of named arguments at compile time.
Definition: attr.h:669
std::is_same< intrinsic_t< T >, pos_only > is_pos_only
Definition: cast.h:1349
T cast(const handle &handle)
Definition: cast.h:1050
std::is_same< intrinsic_t< T >, kw_only > is_kw_only
Definition: cast.h:1347
std::string get_fully_qualified_tp_name(PyTypeObject *type)
Definition: class.h:28
void register_instance(instance *self, void *valptr, const type_info *tinfo)
Definition: class.h:325
PyObject * make_new_python_type(const type_record &rec)
Create a brand new Python type according to the type_record specification.
Definition: class.h:626
void add_patient(PyObject *nurse, PyObject *patient)
Definition: class.h:376
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
Definition: common.h:625
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_)
Include Python header, disable linking to pythonX_d.lib on Windows in debug mode.
Definition: common.h:302
constexpr int last(int, int result)
Definition: common.h:801
static constexpr size_t size_in_ptrs(size_t s)
Definition: common.h:528
PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Thrown when pybind11::cast or.
Definition: common.h:992
#define PYBIND11_NOINLINE
Definition: common.h:129
typename std::remove_reference< T >::type remove_reference_t
Definition: common.h:631
constexpr int constexpr_first()
Return the index of the first type in Ts which satisfies Predicate<T>.
Definition: common.h:811
#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)
Definition: common.h:948
constexpr int first(int i)
Implementation details for constexpr functions.
Definition: common.h:795
std::size_t size_t
Definition: common.h:461
constexpr size_t constexpr_sum()
Compile-time integer sum.
Definition: common.h:786
#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION
Definition: common.h:304
#define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
Definition: common.h:1187
#define PYBIND11_NAMESPACE_END(name)
Definition: common.h:21
#define PYBIND11_TRY_NEXT_OVERLOAD
Definition: common.h:342
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: common.h:20
#define PYBIND11_INSTANCE_METHOD_CHECK
Definition: common.h:303
typename void_t_impl< Ts... >::type void_t
Definition: common.h:694
typename std::conditional< B, T, F >::type conditional_t
Definition: common.h:627
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
Definition: common.h:470
@ automatic_reference
As above, but use policy return_value_policy::reference when the return value is a pointer.
@ reference_internal
This policy only applies to methods and properties.
#define PYBIND11_DEPRECATED(reason)
Definition: common.h:139
#define PYBIND11_SILENCE_MSVC_C4127(...)
Definition: common.h:1206
constexpr descr< N - 1 > const_name(char const (&text)[N])
Definition: descr.h:60
#define PYBIND11_DESCR_CONSTEXPR
Definition: descr.h:18
#define PYBIND11_MODULE_LOCAL_ID
Definition: internals.h:285
void(*)(std::exception_ptr) ExceptionTranslator
Definition: internals.h:36
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
Definition: internals.h:416
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
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
Definition: internals.h:524
PYBIND11_NOINLINE detail::type_info * get_type_info(PyTypeObject *type)
Gets a single pybind11 type info for a python type.
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.
detail::type_info * get_global_type_info(const std::type_index &tp)
PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type)
detail::type_info * get_local_type_info(const std::type_index &tp)
static const self_t self
Definition: operators.h:72
iterator make_value_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator over the values (.second) of a iterator over pairs from a first and past-the-...
Definition: pybind11.h:2425
typename equivalent_integer< std::is_signed< IntLike >::value, sizeof(IntLike)>::type equivalent_integer_t
Definition: pybind11.h:2145
auto method_adaptor(F &&f) -> decltype(std::forward< F >(f))
Given a pointer to a member function, cast it to its Derived version.
Definition: pybind11.h:1478
void implicitly_convertible()
Definition: pybind11.h:2462
exception< CppException > & get_exception_object()
Definition: pybind11.h:2541
#define PYBIND11_COMPAT_STRDUP
Definition: pybind11.h:75
bool apply_exception_translators(std::forward_list< ExceptionTranslator > &translators)
Definition: pybind11.h:58
void register_local_exception_translator(ExceptionTranslator &&translator)
Add a new module-local exception translator.
Definition: pybind11.h:2504
detail::initimpl::alias_constructor< Args... > init_alias()
Like init<Args...>(), but the instance is always constructed through the alias class (even when not i...
Definition: pybind11.h:1906
iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra)
Definition: pybind11.h:2356
str enum_name(handle arg)
Definition: pybind11.h:1933
exception< CppException > & register_local_exception(handle scope, const char *name, handle base=PyExc_Exception)
Registers a Python exception in m of the given name and installs a translator to translate the C++ ex...
Definition: pybind11.h:2595
void call_operator_delete(T *p, size_t, size_t)
Call class-specific delete if it exists or global otherwise. Can also be an overload set.
Definition: pybind11.h:1436
PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient)
Definition: pybind11.h:2208
function get_overload(const T *this_ptr, const char *name)
Definition: pybind11.h:2851
exception< CppException > & register_exception_impl(handle scope, const char *name, handle base, bool isLocal)
Definition: pybind11.h:2549
function get_override(const T *this_ptr, const char *name)
\rst Try to retrieve a python method by the provided name from the instance pointed to by the this_pt...
Definition: pybind11.h:2751
#define PYBIND11_STD_LAUNDER
Definition: pybind11.h:31
exception< CppException > & register_exception(handle scope, const char *name, handle base=PyExc_Exception)
Registers a Python exception in m of the given name and installs a translator to translate the C++ ex...
Definition: pybind11.h:2581
function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name)
Definition: pybind11.h:2846
function get_type_override(const void *this_ptr, const type_info *this_type, const char *name)
Definition: pybind11.h:2651
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
Definition: pybind11.h:1900
detail::initimpl::pickle_factory< GetState, SetState > pickle(GetState &&g, SetState &&s)
Binds pickling functions __getstate__ and __setstate__ and ensures that the type returned by __getsta...
Definition: pybind11.h:1927
iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator over the keys (.first) of a iterator over pairs from a first and past-the-end...
Definition: pybind11.h:2409
void register_exception_translator(ExceptionTranslator &&translator)
Definition: pybind11.h:2493
void set_operator_new(type_record *r)
Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
Definition: pybind11.h:1415
iterator make_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator from a first and past-the-end C++ InputIterator.
Definition: pybind11.h:2393
std::pair< decltype(internals::registered_types_py)::iterator, bool > all_type_info_get_cache(PyTypeObject *type)
Definition: pybind11.h:2257
void add_class_method(object &cls, const char *name_, const cpp_function &cf)
Definition: pybind11.h:1466
PyObject * dict_getitemstring(PyObject *v, const char *key)
Definition: pytypes.h:610
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
Definition: pytypes.h:1087
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
Definition: pytypes.h:62
PyObject * dict_getitem(PyObject *v, PyObject *key)
Definition: pytypes.h:629
#define PYBIND11_OBJECT(Name, Parent, CheckFun)
Definition: pytypes.h:1073
arr data(const arr &a, Ix... index)
#define PYBIND11_ENUM_OP_CONV_LHS(op, expr)
#define PYBIND11_COMPAT_STRDUP
Definition: pybind11.h:76
str enum_name(handle arg)
Definition: pybind11.h:1937
#define PYBIND11_ENUM_OP_CONV(op, expr)
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
Definition: pybind11.h:1904
#define PYBIND11_THROW
#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)
void add_class_method(object &cls, const char *name_, const cpp_function &cf)
Definition: pybind11.h:1456
void raise_from(PyObject *type, const char *message)
Replaces the current Python error indicator with the chosen error, performing a 'raise from' to indic...
Definition: pytypes.h:721
Annotation for arguments.
Definition: cast.h:1238
const char * name
If non-null, this is a named kwargs argument.
Definition: cast.h:1257
Internal data structure which holds metadata about a keyword argument.
Definition: attr.h:175
const char * name
Argument name.
Definition: attr.h:176
bool none
True if None is allowed when loading.
Definition: attr.h:180
bool convert
True if the argument is allowed to convert when loading.
Definition: attr.h:179
Annotation indicating that a class derives from another given type.
Definition: attr.h:60
Information record describing a Python buffer object.
Definition: buffer_info.h:43
void operator()(detail::function_record *rec)
Definition: pybind11.h:155
Annotation for documentation.
Definition: attr.h:41
PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible)
Definition: pybind11.h:1946
enum_base(const handle &base, const handle &parent)
Definition: pybind11.h:1944
handle m_base
Definition: pybind11.h:2104
PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc=nullptr)
Definition: pybind11.h:2084
handle m_parent
Definition: pybind11.h:2105
PYBIND11_NOINLINE void export_values()
Definition: pybind11.h:2097
RAII wrapper that temporarily clears any Python error state.
Definition: common.h:1044
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
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
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
function_record * next
Pointer to next overload.
Definition: attr.h:262
bool is_constructor
True if name == 'init'.
Definition: attr.h:219
bool is_operator
True if this is an operator (add), etc.
Definition: attr.h:228
char * name
Function name.
Definition: attr.h:195
handle scope
Python handle to the parent scope (a class or a module)
Definition: attr.h:256
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
Definition: common.h:554
value_and_holder get_value_and_holder(const type_info *find_type=nullptr, bool throw_if_missing=true)
Returns the value_and_holder wrapper for the given type (or the first, if find_type omitted).
Internal data structure used to track registered instances and types.
Definition: internals.h:150
type_map< type_info * > registered_types_cpp
Definition: internals.h:152
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
Definition: internals.h:154
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
Definition: internals.h:158
std::forward_list< ExceptionTranslator > registered_exception_translators
Definition: internals.h:160
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
Definition: internals.h:157
Annotation for methods.
Definition: attr.h:23
result_type operator()(Iterator &it) const
Definition: pybind11.h:2312
decltype(*std::declval< Iterator & >()) result_type
Definition: pybind11.h:2310
Sentinel end
Definition: pybind11.h:2300
Iterator it
Definition: pybind11.h:2299
bool first_or_done
Definition: pybind11.h:2301
type_map< type_info * > registered_types_cpp
Definition: internals.h:486
std::forward_list< ExceptionTranslator > registered_exception_translators
Definition: internals.h:487
Annotation for function names.
Definition: attr.h:47
static void precall(function_call &call)
Definition: attr.h:643
static void init(const Args &...args, function_record *r)
Definition: attr.h:629
static void postcall(function_call &call, handle fn_ret)
Definition: attr.h:649
static return_value_policy policy(return_value_policy p)
Definition: cast.h:1009
Annotation for parent scope.
Definition: attr.h:35
Annotation indicating that a function is an overload associated with a given "sibling".
Definition: attr.h:53
Additional type information which does not fit into the PyTypeObject.
Definition: internals.h:196
Special data structure which (temporarily) holds metadata about a bound class.
Definition: attr.h:266
bool multiple_inheritance
Multiple inheritance marker.
Definition: attr.h:311
bool default_holder
Is the default (unique_ptr) holder type used?
Definition: attr.h:320
const char * name
Name of the class.
Definition: attr.h:275
size_t holder_size
How large is the type's holder?
Definition: attr.h:287
const std::type_info * type
Definition: attr.h:278
bool module_local
Is the class definition local to the module shared object?
Definition: attr.h:323
void(* init_instance)(instance *, const void *)
Function pointer to class_<..>::init_instance.
Definition: attr.h:293
size_t type_size
How large is the underlying C++ type?
Definition: attr.h:281
handle scope
Handle to the parent scope.
Definition: attr.h:272
size_t type_align
What is the alignment of the underlying C++ type?
Definition: attr.h:284
list bases
List of base classes of the newly created type.
Definition: attr.h:299
void *(* operator_new)(size_t)
The global operator new can be overridden with a class-specific variant.
Definition: attr.h:290
void(* dealloc)(detail::value_and_holder &)
Function pointer to class_<..>::dealloc.
Definition: attr.h:296
Helper type to replace 'void' in some expressions.
Definition: common.h:773