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