29 #if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914))
30 # define PYBIND11_STD_LAUNDER std::launder
31 # define PYBIND11_HAS_STD_LAUNDER 1
33 # define PYBIND11_STD_LAUNDER
34 # define PYBIND11_HAS_STD_LAUNDER 0
36 #if defined(__GNUG__) && !defined(__clang__)
49 #if defined(__GNUC__) && __GNUC__ == 7
58 const char *whitespaces =
" \t\n\r\f\v";
60 bool previous_is_whitespace =
false;
64 char first_char =
result[0];
66 if (first_char == last_char && first_char ==
'\'') {
73 while (*
text !=
'\0') {
74 if (std::strchr(whitespaces, *
text)) {
75 if (!previous_is_whitespace) {
77 previous_is_whitespace =
true;
81 previous_is_whitespace =
false;
87 const size_t str_begin =
result.find_first_not_of(whitespaces);
88 if (str_begin == std::string::npos) {
92 const size_t str_end =
result.find_last_not_of(whitespaces);
93 const size_t str_range = str_end - str_begin + 1;
95 return result.substr(str_begin, str_range);
99 # define PYBIND11_COMPAT_STRDUP _strdup
101 # define PYBIND11_COMPAT_STRDUP strdup
115 template <
typename Return,
typename... Args,
typename... Extra>
122 template <
typename Func,
128 std::forward<Func>(
f), (detail::function_signature_t<Func> *)
nullptr, extra...);
132 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
136 [
f](
Class *
c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
137 (Return(*)(
Class *, Arg...))
nullptr,
144 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
148 [
f](
Class *
c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
149 (Return(*)(
Class *, Arg...))
nullptr,
154 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
158 Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
159 (Return(*)(
const Class *, Arg...))
nullptr,
166 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
170 Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
171 (Return(*)(
const Class *, Arg...))
nullptr,
176 object name()
const {
return attr(
"__name__"); }
185 = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
193 template <
typename Func,
typename Return,
typename... Args,
typename... Extra>
194 void initialize(Func &&
f, Return (*)(Args...),
const Extra &...extra) {
204 auto *rec = unique_rec.get();
207 if (
sizeof(
capture) <=
sizeof(rec->data)) {
211 PYBIND11_WARNING_PUSH
213 #if defined(__GNUG__) && __GNUC__ >= 6
219 #if !PYBIND11_HAS_STD_LAUNDER
234 rec->data[0] =
new capture{std::forward<Func>(
f)};
244 expected_num_args<Extra...>(
245 sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
246 "The number of argument annotations does not match the number of function arguments");
250 cast_in args_converter;
253 if (!args_converter.load_args(call)) {
261 const auto *
data = (
sizeof(
capture) <=
sizeof(call.func.data) ? &call.func.data
262 : call.func.data[0]);
274 if (call.func.is_setter) {
275 (void) std::move(args_converter).template call<Return, Guard>(cap->f);
279 std::move(args_converter).
template call<Return, Guard>(cap->f),
290 rec->nargs_pos = cast_in::args_pos >= 0
292 :
sizeof...(Args) - cast_in::has_kwargs;
294 rec->has_args = cast_in::args_pos >= 0;
295 rec->has_kwargs = cast_in::has_kwargs;
301 constexpr
bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>
::value,
302 has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>
::value,
303 has_arg_annotations = any_of<is_keyword<Extra>...>
::value;
304 static_assert(has_arg_annotations || !has_kw_only_args,
305 "py::kw_only requires the use of argument annotations");
306 static_assert(has_arg_annotations || !has_pos_only_args,
307 "py::pos_only requires the use of argument annotations (for docstrings "
308 "and aligning the annotations to the argument)");
311 "py::kw_only may be specified only once");
313 "py::pos_only may be specified only once");
316 static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
317 "py::pos_only must come before py::kw_only");
322 static constexpr
auto signature
328 initialize_generic(std::move(unique_rec), signature.text, types.data(),
sizeof...(Args));
331 using FunctionType = Return (*)(Args...);
332 constexpr
bool is_function_ptr
334 if (is_function_ptr) {
335 rec->is_stateless =
true;
337 =
const_cast<void *
>(
reinterpret_cast<const void *
>(&
typeid(FunctionType)));
369 const std::type_info *
const *types,
375 auto *rec = unique_rec.get();
386 rec->name = guarded_strdup(rec->name ? rec->name :
"");
388 rec->doc = guarded_strdup(rec->doc);
390 for (
auto &
a : rec->args) {
392 a.name = guarded_strdup(
a.name);
395 a.descr = guarded_strdup(
a.descr);
396 }
else if (
a.value) {
397 a.descr = guarded_strdup(
repr(
a.value).
cast<std::string>().c_str());
401 rec->is_constructor = (std::strcmp(rec->name,
"__init__") == 0)
402 || (std::strcmp(rec->name,
"__setstate__") == 0);
404 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
405 if (rec->is_constructor && !rec->is_new_style_constructor) {
406 const auto class_name
408 const auto func_name = std::string(rec->name);
409 PyErr_WarnEx(PyExc_FutureWarning,
410 (
"pybind11-bound class '" + class_name
411 +
"' is using an old-style "
414 +
"' which has been deprecated. See "
415 "the upgrade guide in pybind11's docs. This message is only visible "
416 "when compiled in debug mode.")
423 std::string signature;
424 size_t type_index = 0, arg_index = 0;
425 bool is_starred =
false;
426 for (
const auto *
pc =
text; *
pc !=
'\0'; ++
pc) {
431 is_starred = *(
pc + 1) ==
'*';
437 if (!rec->has_args && arg_index == rec->nargs_pos) {
440 if (arg_index < rec->
args.
size() && rec->args[arg_index].name) {
441 signature += rec->args[arg_index].name;
442 }
else if (arg_index == 0 && rec->is_method) {
445 signature +=
"arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
448 }
else if (
c ==
'}') {
450 if (!is_starred && arg_index < rec->
args.
size() && rec->args[arg_index].descr) {
456 if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
462 }
else if (
c ==
'%') {
463 const std::type_info *
t = types[type_index++];
465 pybind11_fail(
"Internal error while parsing type signature (1)");
468 handle th((PyObject *) tinfo->type);
469 signature += th.attr(
"__module__").
cast<std::string>() +
"."
470 + th.attr(
"__qualname__").
cast<std::string>();
471 }
else if (rec->is_new_style_constructor && arg_index == 0) {
474 signature += rec->scope.attr(
"__module__").cast<std::string>() +
"."
475 + rec->scope.attr(
"__qualname__").cast<std::string>();
484 if (arg_index !=
args - rec->has_args - rec->has_kwargs || types[type_index] !=
nullptr) {
485 pybind11_fail(
"Internal error while parsing type signature (2)");
488 rec->signature = guarded_strdup(signature.c_str());
489 rec->args.shrink_to_fit();
496 detail::function_record *chain =
nullptr, *chain_start = rec;
498 if (PyCFunction_Check(rec->sibling.ptr())) {
499 auto *
self = PyCFunction_GET_SELF(rec->sibling.ptr());
500 if (!isinstance<capsule>(
self)) {
503 auto rec_capsule = reinterpret_borrow<capsule>(
self);
505 chain = rec_capsule.get_pointer<detail::function_record>();
508 if (!chain->scope.is(rec->scope)) {
518 else if (!rec->sibling.is_none() && rec->name[0] !=
'_') {
519 pybind11_fail(
"Cannot overload existing non-function object \""
520 + std::string(rec->name) +
"\" with a function of the same name");
526 rec->def =
new PyMethodDef();
527 std::memset(rec->def, 0,
sizeof(PyMethodDef));
528 rec->def->ml_name = rec->name;
530 =
reinterpret_cast<PyCFunction
>(
reinterpret_cast<void (*)()
>(
dispatcher));
531 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
533 capsule rec_capsule(unique_rec.release(),
535 [](
void *
ptr) { destruct((detail::function_record *) ptr); });
540 if (
hasattr(rec->scope,
"__module__")) {
541 scope_module = rec->scope.attr(
"__module__");
542 }
else if (
hasattr(rec->scope,
"__name__")) {
543 scope_module = rec->scope.attr(
"__name__");
547 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.
ptr(), scope_module.ptr());
549 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate function object");
553 m_ptr = rec->sibling.ptr();
555 if (chain->is_method != rec->is_method) {
557 "overloading a method with both static and instance methods is not supported; "
559 "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more "
562 "error while attempting to bind "
563 + std::string(rec->is_method ?
"instance" :
"static") +
" method "
564 + std::string(
pybind11::str(rec->scope.attr(
"__name__"))) +
"."
565 + std::string(rec->name) + signature
577 = reinterpret_borrow<capsule>(((PyCFunctionObject *)
m_ptr)->m_self);
578 rec_capsule.set_pointer(unique_rec.release());
583 while (chain->next) {
586 chain->next = unique_rec.release();
591 std::string signatures;
596 && std::strcmp(rec->name,
"_pybind11_conduit_v1_") != 0) {
598 signatures += rec->name;
599 signatures +=
"(*args, **kwargs)\n";
600 signatures +=
"Overloaded function.\n\n";
603 bool first_user_def =
true;
604 for (
auto *it = chain_start; it !=
nullptr; it = it->next) {
606 && std::strcmp(rec->name,
"_pybind11_conduit_v1_") != 0) {
611 signatures += std::to_string(++index) +
". ";
613 signatures += rec->name;
614 signatures += it->signature;
621 if (first_user_def) {
622 first_user_def =
false;
630 signatures += it->doc;
638 auto *
func = (PyCFunctionObject *)
m_ptr;
639 std::free(
const_cast<char *
>(
func->m_ml->ml_doc));
644 if (rec->is_method) {
648 "cpp_function::cpp_function(): Could not allocate instance method object");
655 static void destruct(detail::function_record *rec,
bool free_strings =
true) {
658 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
659 static bool is_zero = Py_GetVersion()[4] ==
'0';
663 detail::function_record *next = rec->next;
664 if (rec->free_data) {
671 std::free((
char *) rec->name);
672 std::free((
char *) rec->doc);
673 std::free((
char *) rec->signature);
674 for (
auto &
arg : rec->args) {
675 std::free(
const_cast<char *
>(
arg.
name));
676 std::free(
const_cast<char *
>(
arg.descr));
679 for (
auto &
arg : rec->args) {
683 std::free(
const_cast<char *
>(rec->def->ml_doc));
687 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
701 static PyObject *
dispatcher(PyObject *
self, PyObject *args_in, PyObject *kwargs_in) {
703 assert(isinstance<capsule>(
self));
708 *current_overload = overloads;
709 assert(overloads !=
nullptr);
713 const auto n_args_in = (
size_t) PyTuple_GET_SIZE(args_in);
715 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) :
nullptr,
721 || !PyObject_TypeCheck(parent.
ptr(), (PyTypeObject *) overloads->
scope.
ptr())) {
723 "__init__(self, ...) called with invalid or missing `self` argument");
728 auto *
const pi =
reinterpret_cast<instance *
>(parent.
ptr());
733 if (self_value_and_holder.instance_registered()) {
743 std::vector<function_call> second_pass;
746 const bool overloaded
747 = current_overload !=
nullptr && current_overload->next !=
nullptr;
749 for (; current_overload !=
nullptr; current_overload = current_overload->next) {
771 size_t num_args =
func.nargs;
775 if (
func.has_kwargs) {
778 size_t pos_args =
func.nargs_pos;
780 if (!
func.has_args && n_args_in > pos_args) {
784 if (n_args_in < pos_args &&
func.args.size() < pos_args) {
792 size_t args_to_copy = (
std::min)(pos_args, n_args_in);
793 size_t args_copied = 0;
796 if (
func.is_new_style_constructor) {
799 if (self_value_and_holder) {
800 self_value_and_holder.type->dealloc(self_value_and_holder);
803 call.
init_self = PyTuple_GET_ITEM(args_in, 0);
804 call.
args.emplace_back(
reinterpret_cast<PyObject *
>(&self_value_and_holder));
810 bool bad_arg =
false;
811 for (; args_copied < args_to_copy; ++args_copied) {
813 = args_copied <
func.args.size() ? &
func.args[args_copied] :
nullptr;
814 if (kwargs_in && arg_rec && arg_rec->
name
820 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
821 if (arg_rec && !arg_rec->
none &&
arg.is_none()) {
834 size_t positional_args_copied = args_copied;
837 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
840 if (args_copied <
func.nargs_pos_only) {
841 for (; args_copied <
func.nargs_pos_only; ++args_copied) {
842 const auto &arg_rec =
func.args[args_copied];
846 value = arg_rec.value;
856 if (args_copied <
func.nargs_pos_only) {
862 if (args_copied < num_args) {
863 bool copied_kwargs =
false;
865 for (; args_copied < num_args; ++args_copied) {
866 const auto &arg_rec =
func.args[args_copied];
869 if (kwargs_in && arg_rec.name) {
875 if (!copied_kwargs) {
877 copied_kwargs =
true;
879 if (PyDict_DelItemString(
kwargs.
ptr(), arg_rec.name) == -1) {
882 }
else if (arg_rec.value) {
883 value = arg_rec.value;
886 if (!arg_rec.none &&
value.is_none()) {
893 if (
func.has_args && call.
args.size() ==
func.nargs_pos) {
904 if (args_copied < num_args) {
918 if (args_to_copy == 0) {
921 extra_args = reinterpret_borrow<tuple>(args_in);
922 }
else if (positional_args_copied >= n_args_in) {
923 extra_args =
tuple(0);
925 size_t args_size = n_args_in - positional_args_copied;
926 extra_args =
tuple(args_size);
927 for (
size_t i = 0;
i < args_size; ++
i) {
928 extra_args[
i] = PyTuple_GET_ITEM(args_in, positional_args_copied +
i);
931 if (call.
args.size() <=
func.nargs_pos) {
932 call.
args.push_back(extra_args);
934 call.
args[
func.nargs_pos] = extra_args;
937 call.
args_ref = std::move(extra_args);
941 if (
func.has_kwargs) {
952 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
954 pybind11_fail(
"Internal error: function call dispatcher inserted wrong number "
959 std::vector<bool> second_pass_convert;
964 second_pass_convert.resize(
func.nargs,
false);
972 }
catch (reference_cast_error &) {
984 for (
size_t i =
func.is_method ? 1 : 0;
i < pos_args;
i++) {
985 if (second_pass_convert[
i]) {
989 second_pass.push_back(std::move(call));
999 for (
auto &call : second_pass) {
1002 result = call.func.impl(call);
1003 }
catch (reference_cast_error &) {
1011 current_overload = &call.func;
1021 }
catch (abi::__forced_unwind &) {
1029 auto append_note_if_missing_header_is_suspected = [](std::string &
msg) {
1030 if (
msg.find(
"std::") != std::string::npos) {
1032 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1033 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1034 "conversions are optional and require extra headers to be included\n"
1035 "when compiling your pybind11 module.";
1041 return handle(Py_NotImplemented).inc_ref().ptr();
1044 std::string
msg = std::string(overloads->
name) +
"(): incompatible "
1045 + std::string(overloads->
is_constructor ?
"constructor" :
"function")
1046 +
" arguments. The following argument types are supported:\n";
1050 msg +=
" " + std::to_string(++ctr) +
". ";
1052 bool wrote_sig =
false;
1056 std::string sig = it2->signature;
1057 size_t start = sig.find(
'(') + 7;
1058 if (start < sig.size()) {
1060 size_t end = sig.find(
", "), next =
end + 2;
1061 size_t ret = sig.rfind(
" -> ");
1063 if (
end >= sig.size()) {
1064 next =
end = sig.find(
')');
1066 if (start <
end && next < sig.size()) {
1067 msg.append(sig, start,
end - start);
1069 msg.append(sig, next,
ret - next);
1075 msg += it2->signature;
1080 msg +=
"\nInvoked with: ";
1081 auto args_ = reinterpret_borrow<tuple>(args_in);
1082 bool some_args =
false;
1083 for (
size_t ti = overloads->
is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
1092 msg +=
"<repr raised Error>";
1096 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
1103 for (
const auto &kwarg :
kwargs) {
1113 msg +=
"<repr raised Error>";
1119 append_note_if_missing_header_is_suspected(
msg);
1121 if (PyErr_Occurred()) {
1130 std::string
msg =
"Unable to convert function return value to a "
1131 "Python type! The signature was\n\t";
1132 assert(current_overload !=
nullptr);
1133 msg += current_overload->signature;
1134 append_note_if_missing_header_is_suspected(
msg);
1136 if (PyErr_Occurred()) {
1143 if (overloads->
is_constructor && !self_value_and_holder.holder_constructed()) {
1144 auto *pi =
reinterpret_cast<instance *
>(parent.
ptr());
1145 self_value_and_holder.type->init_instance(pi,
nullptr);
1164 bool flag()
const {
return flag_; }
1178 *
this = create_extension_module(
name,
doc,
new PyModuleDef());
1186 template <
typename Func,
typename... Extra>
1196 add_object(name_,
func,
true );
1211 const char *this_name = PyModule_GetName(
m_ptr);
1212 if (this_name ==
nullptr) {
1215 std::string full_name = std::string(this_name) +
'.' +
name;
1216 handle submodule = PyImport_AddModule(full_name.c_str());
1220 auto result = reinterpret_borrow<module_>(submodule);
1230 PyObject *obj = PyImport_ImportModule(
name);
1234 return reinterpret_steal<module_>(obj);
1239 PyObject *obj = PyImport_ReloadModule(
ptr());
1243 *
this = reinterpret_steal<module_>(obj);
1256 "Error during initialization: multiple incompatible definitions with name \""
1257 + std::string(
name) +
"\"");
1278 PyModuleDef{ PyModuleDef_HEAD_INIT,
1287 auto *
m = PyModule_Create(def);
1289 if (PyErr_Occurred()) {
1292 pybind11_fail(
"Internal error in module_::create_extension_module()");
1294 if (gil_not_used.flag()) {
1295 #ifdef Py_GIL_DISABLED
1296 PyUnstable_Module_SetGIL(
m, Py_MOD_GIL_NOT_USED);
1302 return reinterpret_borrow<module_>(
m);
1324 #if PY_VERSION_HEX >= 0x030d0000
1325 PyObject *
p = PyEval_GetFrameGlobals();
1326 return p ? reinterpret_steal<dict>(
p)
1329 PyObject *
p = PyEval_GetGlobals();
1336 "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
1337 object make_simple_namespace(Args &&...args_) {
1338 return module_::import(
"types").attr(
"SimpleNamespace")(std::forward<Args>(args_)...);
1343 class generic_type : public
object {
1349 && rec.
scope.attr(
"__dict__").contains(rec.
name)) {
1351 +
"\": an object with that name is already defined");
1357 +
"\" is already registered!");
1363 auto *tinfo =
new detail::type_info();
1364 tinfo->type = (PyTypeObject *)
m_ptr;
1365 tinfo->cpptype = rec.
type;
1372 tinfo->simple_type =
true;
1373 tinfo->simple_ancestors =
true;
1378 auto tindex = std::type_index(*rec.
type);
1389 mark_parents_nonsimple(tinfo->type);
1390 tinfo->simple_ancestors =
false;
1391 }
else if (rec.
bases.size() == 1) {
1393 assert(parent_tinfo !=
nullptr);
1394 bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1395 tinfo->simple_ancestors = parent_simple_ancestors;
1397 parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1409 auto t = reinterpret_borrow<tuple>(
value->tp_bases);
1413 tinfo2->simple_type =
false;
1415 mark_parents_nonsimple((PyTypeObject *)
h.ptr());
1420 void *get_buffer_data) {
1421 auto *
type = (PyHeapTypeObject *)
m_ptr;
1424 if (!
type->ht_type.tp_as_buffer) {
1425 pybind11_fail(
"To be able to register buffer protocol support for the type '"
1427 +
"' the associated class<>(..) invocation must "
1428 "include the pybind11::buffer_protocol() annotation!");
1431 tinfo->get_buffer = get_buffer;
1432 tinfo->get_buffer_data = get_buffer_data;
1439 detail::function_record *rec_func) {
1440 const auto is_static = (rec_func !=
nullptr) && !(rec_func->is_method && rec_func->scope);
1441 const auto has_doc = (rec_func !=
nullptr) && (rec_func->doc !=
nullptr)
1442 && pybind11::options::show_user_defined_docstrings();
1444 (PyObject *) (is_static ?
get_internals().static_property_type : &PyProperty_Type));
1453 template <
typename T,
1462 template <
typename T,
typename SFINAE =
void>
1464 template <
typename T>
1466 : std::true_type {};
1467 template <
typename T,
typename SFINAE =
void>
1469 template <
typename T>
1477 T::operator
delete(
p);
1479 template <
typename T,
1483 T::operator
delete(
p,
s);
1489 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1490 if (
a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1491 # ifdef __cpp_sized_deallocation
1492 ::operator
delete(
p,
s, std::align_val_t(
a));
1494 ::operator
delete(
p, std::align_val_t(
a));
1499 #ifdef __cpp_sized_deallocation
1500 ::operator
delete(
p,
s);
1502 ::operator
delete(
p);
1507 cls.attr(cf.
name()) = cf;
1508 if (std::strcmp(name_,
"__eq__") == 0 && !cls.attr(
"__dict__").contains(
"__hash__")) {
1509 cls.attr(
"__hash__") =
none();
1515 template <
typename ,
typename F>
1519 return std::forward<F>(
f);
1522 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1526 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1530 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1531 auto method_adaptor(Return (Class::*pmf)(Args...)
const) -> Return (Derived::*)(Args...)
const {
1534 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1538 template <
typename type_,
typename...
options>
1540 template <
typename T>
1542 template <
typename T>
1544 template <
typename T>
1545 using is_base = detail::is_strict_base_of<T, type_>;
1547 template <
typename T>
1557 "Unknown/invalid class_ template parameters provided");
1560 "Cannot use an alias class with a non-polymorphic type");
1564 template <
typename... Extra>
1574 none_of<std::is_same<multiple_inheritance, Extra>...>::
value),
1575 "Error: multiple inheritance bases must be specified via class_ template options");
1588 set_operator_new<type>(&record);
1602 instances[std::type_index(
typeid(
type_alias))]
1603 = instances[std::type_index(
typeid(
type))];
1611 rec.add_base(
typeid(Base), [](
void *src) ->
void * {
1612 return static_cast<Base *
>(
reinterpret_cast<type *
>(src));
1619 template <
typename Func,
typename... Extra>
1620 class_ &
def(
const char *name_, Func &&
f,
const Extra &...extra) {
1621 cpp_function cf(method_adaptor<type>(std::forward<Func>(
f)),
1630 template <
typename Func,
typename... Extra>
1631 class_ &
def_static(
const char *name_, Func &&
f,
const Extra &...extra) {
1633 "def_static(...) called with a non-static member function pointer");
1639 auto cf_name = cf.
name();
1640 attr(std::move(cf_name)) =
staticmethod(std::move(cf));
1644 template <
typename T,
typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1645 class_ &
def(
const T &op,
const Extra &...extra) {
1646 op.execute(*
this, extra...);
1650 template <
typename T,
typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1652 op.execute_cast(*
this, extra...);
1656 template <
typename... Args,
typename... Extra>
1657 class_ &
def(
const detail::initimpl::constructor<Args...> &
init,
const Extra &...extra) {
1659 init.execute(*
this, extra...);
1663 template <
typename... Args,
typename... Extra>
1664 class_ &
def(
const detail::initimpl::alias_constructor<Args...> &
init,
const Extra &...extra) {
1666 init.execute(*
this, extra...);
1670 template <
typename... Args,
typename... Extra>
1671 class_ &
def(detail::initimpl::factory<Args...> &&
init,
const Extra &...extra) {
1672 std::move(
init).execute(*
this, extra...);
1676 template <
typename... Args,
typename... Extra>
1677 class_ &
def(detail::initimpl::pickle_factory<Args...> &&pf,
const Extra &...extra) {
1678 std::move(pf).execute(*
this, extra...);
1682 template <
typename Func>
1688 install_buffer_funcs(
1690 detail::make_caster<type> caster;
1691 if (!caster.load(obj,
false)) {
1705 template <
typename Return,
typename Class,
typename... Args>
1707 return def_buffer([
func](
type &obj) {
return (obj.*
func)(); });
1710 template <
typename Return,
typename Class,
typename... Args>
1712 return def_buffer([
func](
const type &obj) {
return (obj.*
func)(); });
1715 template <
typename C,
typename D,
typename... Extra>
1718 "def_readwrite() requires a class member (or base class member)");
1725 template <
typename C,
typename D,
typename... Extra>
1728 "def_readonly() requires a class member (or base class member)");
1734 template <
typename D,
typename... Extra>
1742 template <
typename D,
typename... Extra>
1750 template <
typename Getter,
typename... Extra>
1752 return def_property_readonly(
name,
1759 template <
typename... Extra>
1762 return def_property(
name, fget,
nullptr, extra...);
1766 template <
typename Getter,
typename... Extra>
1769 return def_property_readonly_static(
1774 template <
typename... Extra>
1777 const Extra &...extra) {
1778 return def_property_static(
name, fget,
nullptr, extra...);
1782 template <
typename Getter,
typename Setter,
typename... Extra>
1784 def_property(
const char *
name,
const Getter &fget,
const Setter &fset,
const Extra &...extra) {
1785 return def_property(
1788 template <
typename Getter,
typename... Extra>
1792 const Extra &...extra) {
1793 return def_property(
name,
1801 template <
typename... Extra>
1805 const Extra &...extra) {
1806 return def_property_static(
name, fget, fset,
is_method(*
this), extra...);
1810 template <
typename Getter,
typename... Extra>
1814 const Extra &...extra) {
1815 return def_property_static(
1820 template <
typename... Extra>
1824 const Extra &...extra) {
1826 "Argument annotations are not allowed for properties");
1827 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1828 auto *rec_active = rec_fget;
1830 char *doc_prev = rec_fget->doc;
1833 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1834 std::free(doc_prev);
1839 char *doc_prev = rec_fset->doc;
1841 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1842 std::free(doc_prev);
1846 rec_active = rec_fset;
1849 def_property_static_impl(
name, fget, fset, rec_active);
1855 template <
typename T>
1857 detail::value_and_holder &v_h,
1859 const std::enable_shared_from_this<T> * ) {
1861 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1865 v_h.set_holder_constructed();
1868 if (!v_h.holder_constructed() &&
inst->owned) {
1870 v_h.set_holder_constructed();
1891 detail::value_and_holder &v_h,
1895 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1896 v_h.set_holder_constructed();
1899 v_h.set_holder_constructed();
1909 if (!v_h.instance_registered()) {
1911 v_h.set_instance_registered();
1917 static void dealloc(detail::value_and_holder &v_h) {
1925 if (v_h.holder_constructed()) {
1927 v_h.set_holder_constructed(
false);
1930 v_h.value_ptr<
type>(), v_h.type->type_size, v_h.type->type_align);
1932 v_h.value_ptr() =
nullptr;
1941 handle func_self = PyCFunction_GET_SELF(
h.ptr());
1945 if (!isinstance<capsule>(func_self)) {
1948 auto cap = reinterpret_borrow<capsule>(func_self);
1952 return cap.get_pointer<detail::function_record>();
1957 template <
typename... Args>
1958 detail::initimpl::constructor<Args...>
init() {
1963 template <
typename... Args>
1969 template <
typename Func,
typename Ret = detail::initimpl::factory<Func>>
1971 return {std::forward<Func>(
f)};
1977 template <
typename CFunc,
typename AFunc,
typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1979 return {std::forward<CFunc>(
c), std::forward<AFunc>(
a)};
1984 template <
typename GetState,
typename SetState>
1985 detail::initimpl::pickle_factory<GetState, SetState>
pickle(GetState &&
g, SetState &&
s) {
1986 return {std::forward<GetState>(
g), std::forward<SetState>(
s)};
1992 dict entries =
arg.get_type().attr(
"__entries");
1993 for (
auto kv : entries) {
2005 m_base.attr(
"__entries") =
dict();
2006 auto property =
handle((PyObject *) &PyProperty_Type);
2010 [](
const object &
arg) ->
str {
2030 m_base.attr(
"__doc__") = static_property(
2033 std::string docstring;
2034 dict entries =
arg.attr(
"__entries");
2035 if (((PyTypeObject *)
arg.ptr())->tp_doc) {
2036 docstring += std::string(
2037 reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);
2038 docstring +=
"\n\n";
2040 docstring +=
"Members:";
2041 for (
auto kv : entries) {
2043 auto comment = kv.second[
int_(1)];
2044 docstring +=
"\n\n ";
2046 if (!comment.is_none()) {
2059 m_base.attr(
"__members__") = static_property(
cpp_function(
2061 dict entries =
arg.attr(
"__entries"),
2063 for (
auto kv : entries) {
2064 m[kv.first] = kv.second[
int_(0)];
2068 name(
"__members__")),
2073 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
2074 m_base.attr(op) = cpp_function( \
2075 [](const object &a, const object &b) { \
2076 if (!type::handle_of(a).is(type::handle_of(b))) \
2081 is_method(m_base), \
2084 #define PYBIND11_ENUM_OP_CONV(op, expr) \
2085 m_base.attr(op) = cpp_function( \
2086 [](const object &a_, const object &b_) { \
2087 int_ a(a_), b(b_); \
2091 is_method(m_base), \
2094 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
2095 m_base.attr(op) = cpp_function( \
2096 [](const object &a_, const object &b) { \
2101 is_method(m_base), \
2104 if (is_convertible) {
2108 if (is_arithmetic) {
2119 m_base.attr(
"__invert__")
2128 if (is_arithmetic) {
2129 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
2134 #undef PYBIND11_THROW
2138 #undef PYBIND11_ENUM_OP_CONV_LHS
2139 #undef PYBIND11_ENUM_OP_CONV
2140 #undef PYBIND11_ENUM_OP_STRICT
2150 dict entries = m_base.attr(
"__entries");
2153 std::string
type_name = (std::string)
str(m_base.attr(
"__name__"));
2154 throw value_error(std::move(
type_name) +
": element \"" + std::string(name_)
2155 +
"\" already exists!");
2159 m_base.attr(std::move(
name)) = std::move(
value);
2163 dict entries = m_base.attr(
"__entries");
2164 for (
auto kv : entries) {
2165 m_parent.attr(kv.first) = kv.second[
int_(0)];
2173 template <
bool is_
signed,
size_t length>
2208 template <
typename IntLike>
2214 template <
typename Type>
2221 using Base::def_property_readonly;
2222 using Base::def_property_readonly_static;
2225 using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2226 std::is_same<Underlying, bool>>
::value,
2227 detail::equivalent_integer_t<Underlying>,
2230 template <
typename... Extra>
2233 constexpr
bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>
::value;
2235 m_base.init(is_arithmetic, is_convertible);
2242 [](detail::value_and_holder &v_h,
Scalar arg) {
2243 detail::initimpl::setstate<Base>(
2244 v_h,
static_cast<Type>(
arg), Py_TYPE(v_h.inst) != v_h.type->type);
2246 detail::is_new_style_constructor(),
2271 if (!nurse || !patient) {
2275 if (patient.is_none() || nurse.is_none()) {
2280 if (!tinfo.empty()) {
2293 weakref wr(nurse, disable_lifesupport);
2296 (void) wr.release();
2302 auto get_arg = [&](
size_t n) {
2309 if (
n <= call.
args.size()) {
2310 return call.
args[
n - 1];
2323 #ifdef __cpp_lib_unordered_map_try_emplace
2326 .emplace(
type, std::vector<detail::type_info *>());
2338 for (
auto it = cache.begin(),
last = cache.end(); it !=
last;) {
2339 if (it->first == reinterpret_cast<PyObject *>(type)) {
2340 it = cache.erase(it);
2358 template <
typename Access,
2374 template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
2381 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).
first)>
2398 decltype(((*std::declval<Iterator &>()).
first)),
2399 decltype(std::declval<pair_type>().first)>;
2403 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
2411 decltype(((*std::declval<Iterator &>()).second)),
2412 decltype(std::declval<pair_type>().second)>;
2416 template <
typename Access,
2423 using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
2427 class_<state>(
handle(),
"iterator", pybind11::module_local())
2428 .def(
"__iter__", [](
state &
s) ->
state & {
return s; })
2431 [](
state &
s) -> ValueType {
2432 if (!
s.first_or_done) {
2435 s.first_or_done = false;
2437 if (
s.it ==
s.end) {
2438 s.first_or_done = true;
2439 throw stop_iteration();
2441 return Access()(
s.it);
2444 std::forward<Extra>(extra)...,
2448 return cast(
state{std::forward<Iterator>(
first), std::forward<Sentinel>(
last),
true});
2457 typename ValueType =
typename detail::iterator_access<Iterator>::result_type,
2460 return detail::make_iterator_impl<detail::iterator_access<Iterator>,
2465 Extra...>(std::forward<Iterator>(
first),
2466 std::forward<Sentinel>(
last),
2467 std::forward<Extra>(extra)...);
2475 typename KeyType =
typename detail::iterator_key_access<Iterator>::result_type,
2478 return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
2483 Extra...>(std::forward<Iterator>(
first),
2484 std::forward<Sentinel>(
last),
2485 std::forward<Extra>(extra)...);
2493 typename ValueType =
typename detail::iterator_value_access<Iterator>::result_type,
2496 return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
2501 Extra...>(std::forward<Iterator>(
first),
2502 std::forward<Sentinel>(
last),
2503 std::forward<Extra>(extra)...);
2510 typename ValueType =
typename detail::iterator_access<
2511 decltype(std::begin(std::declval<Type &>()))>::result_type,
2514 return make_iterator<Policy>(
2522 typename KeyType =
typename detail::iterator_key_access<
2523 decltype(std::begin(std::declval<Type &>()))>::result_type,
2526 return make_key_iterator<Policy>(
2534 typename ValueType =
typename detail::iterator_value_access<
2535 decltype(std::begin(std::declval<Type &>()))>::result_type,
2538 return make_value_iterator<Policy>(
2542 template <
typename InputType,
typename OutputType>
2546 explicit set_flag(
bool &flag_) : flag(flag_) { flag_ =
true; }
2547 ~set_flag() { flag =
false; }
2549 auto implicit_caster = [](PyObject *obj, PyTypeObject *
type) -> PyObject * {
2550 #ifdef Py_GIL_DISABLED
2551 thread_local
bool currently_used =
false;
2553 static bool currently_used =
false;
2555 if (currently_used) {
2558 set_flag flag_helper(currently_used);
2559 if (!detail::make_caster<InputType>().load(obj,
false)) {
2572 tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
2574 pybind11_fail(
"implicitly_convertible: Unable to find type " + type_id<OutputType>());
2581 std::forward<ExceptionTranslator>(translator));
2595 std::forward<ExceptionTranslator>(translator));
2606 template <
typename type>
2609 exception() =
default;
2611 std::string full_name
2612 =
scope.attr(
"__name__").cast<std::string>() + std::string(
".") +
name;
2613 m_ptr = PyErr_NewException(
const_cast<char *
>(full_name.c_str()),
base.ptr(),
nullptr);
2615 pybind11_fail(
"Error during initialization: multiple incompatible "
2616 "definitions with name \""
2617 + std::string(
name) +
"\"");
2624 "(https://github.com/pybind/pybind11/pull/4772)")
2625 void operator()(const
char *message)
const {
set_error(*
this, message); }
2636 template <
typename CppException>
2637 exception<CppException> &
2641 [&]() {
return exception<CppException>(
scope,
name,
base); });
2646 register_func([](std::exception_ptr
p) {
2651 std::rethrow_exception(
p);
2652 }
catch (
const CppException &
e) {
2653 set_error(exc_storage.get_stored(),
e.what());
2656 return exc_storage.get_stored();
2667 template <
typename CppException>
2668 exception<CppException> &
2670 return detail::register_exception_impl<CppException>(
scope,
name,
base,
false );
2681 template <
typename CppException>
2682 exception<CppException> &
2684 return detail::register_exception_impl<CppException>(
scope,
name,
base,
true );
2694 auto line =
sep.attr(
"join")(std::move(strings));
2712 write(std::move(line));
2716 file.attr(
"flush")();
2723 auto c = detail::collect_arguments<policy>(std::forward<Args>(
args)...);
2737 return m_fetched_error->error_string().c_str();
2755 return cache.find(
key) != cache.end();
2757 if (not_overridden) {
2761 function override =
getattr(
self,
name,
function());
2771 #if !defined(PYPY_VERSION)
2772 # if PY_VERSION_HEX >= 0x03090000
2773 PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
2774 if (frame !=
nullptr) {
2775 PyCodeObject *f_code = PyFrame_GetCode(frame);
2777 if ((std::string)
str(f_code->co_name) ==
name && f_code->co_argcount > 0) {
2778 # if PY_VERSION_HEX >= 0x030d0000
2779 PyObject *locals = PyEval_GetFrameLocals();
2781 PyObject *locals = PyEval_GetLocals();
2784 if (locals !=
nullptr) {
2785 # if PY_VERSION_HEX >= 0x030b0000
2786 PyObject *co_varnames = PyCode_GetVarnames(f_code);
2788 PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code,
"co_varnames");
2790 PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
2791 Py_DECREF(co_varnames);
2792 PyObject *self_caller =
dict_getitem(locals, self_arg);
2794 if (self_caller ==
self.
ptr()) {
2805 PyFrameObject *frame = PyThreadState_Get()->frame;
2806 if (frame !=
nullptr && (std::string)
str(frame->f_code->co_name) ==
name
2807 && frame->f_code->co_argcount > 0) {
2808 PyFrame_FastToLocals(frame);
2809 PyObject *self_caller
2810 =
dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2811 if (self_caller ==
self.
ptr()) {
2825 = PyRun_String(
"import inspect\n"
2826 "frame = inspect.currentframe()\n"
2827 "if frame is not None:\n"
2828 " frame = frame.f_back\n"
2829 " if frame is not None and str(frame.f_code.co_name) == name and "
2830 "frame.f_code.co_argcount > 0:\n"
2831 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2832 " if self_caller == self:\n"
2840 if (
d[
"self"].is_none())
2863 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
2865 pybind11::gil_scoped_acquire gil; \
2866 pybind11::function override \
2867 = pybind11::get_override(static_cast<const cname *>(this), name); \
2869 auto o = override(__VA_ARGS__); \
2870 PYBIND11_WARNING_PUSH \
2871 PYBIND11_WARNING_DISABLE_MSVC(4127) \
2872 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value \
2873 && !pybind11::detail::is_same_ignoring_cvref<ret_type, PyObject *>::value) { \
2874 static pybind11::detail::override_caster_t<ret_type> caster; \
2875 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
2877 PYBIND11_WARNING_POP \
2878 return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2900 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
2902 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2903 return cname::fn(__VA_ARGS__); \
2910 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
2912 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2913 pybind11::pybind11_fail( \
2914 "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
2942 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
2943 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2949 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
2950 PYBIND11_OVERRIDE_PURE_NAME( \
2951 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2966 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
2967 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
2968 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
2969 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
2970 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
2971 PYBIND11_OVERRIDE_PURE_NAME( \
2972 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
2973 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
2974 PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
2975 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2976 PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);