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);
103 auto last_exception = std::current_exception();
105 for (
auto &translator : translators) {
107 translator(last_exception);
110 last_exception = std::current_exception();
116 #if defined(_MSC_VER)
117 # define PYBIND11_COMPAT_STRDUP _strdup
119 # define PYBIND11_COMPAT_STRDUP strdup
133 template <
typename Return,
typename... Args,
typename... Extra>
140 template <
typename Func,
146 std::forward<Func>(
f), (detail::function_signature_t<Func> *)
nullptr, extra...);
150 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
154 [
f](
Class *
c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
155 (Return(*)(
Class *, Arg...))
nullptr,
162 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
166 [
f](
Class *
c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
167 (Return(*)(
Class *, Arg...))
nullptr,
172 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
176 Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
177 (Return(*)(
const Class *, Arg...))
nullptr,
184 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
188 Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
189 (Return(*)(
const Class *, Arg...))
nullptr,
194 object name()
const {
return attr(
"__name__"); }
203 = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
211 template <
typename Func,
typename Return,
typename... Args,
typename... Extra>
212 void initialize(Func &&
f, Return (*)(Args...),
const Extra &...extra) {
222 auto *rec = unique_rec.get();
225 if (
sizeof(
capture) <=
sizeof(rec->data)) {
229 PYBIND11_WARNING_PUSH
231 #if defined(__GNUG__) && __GNUC__ >= 6
237 #if !PYBIND11_HAS_STD_LAUNDER
252 rec->data[0] =
new capture{std::forward<Func>(
f)};
262 expected_num_args<Extra...>(
263 sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
264 "The number of argument annotations does not match the number of function arguments");
268 cast_in args_converter;
271 if (!args_converter.load_args(call)) {
279 const auto *
data = (
sizeof(
capture) <=
sizeof(call.func.data) ? &call.func.data
280 : call.func.data[0]);
292 if (call.func.is_setter) {
293 (void) std::move(args_converter).template call<Return, Guard>(cap->f);
297 std::move(args_converter).
template call<Return, Guard>(cap->f),
308 rec->nargs_pos = cast_in::args_pos >= 0
310 :
sizeof...(Args) - cast_in::has_kwargs;
312 rec->has_args = cast_in::args_pos >= 0;
313 rec->has_kwargs = cast_in::has_kwargs;
319 constexpr
bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>
::value,
320 has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>
::value,
321 has_arg_annotations = any_of<is_keyword<Extra>...>
::value;
322 static_assert(has_arg_annotations || !has_kw_only_args,
323 "py::kw_only requires the use of argument annotations");
324 static_assert(has_arg_annotations || !has_pos_only_args,
325 "py::pos_only requires the use of argument annotations (for docstrings "
326 "and aligning the annotations to the argument)");
329 "py::kw_only may be specified only once");
331 "py::pos_only may be specified only once");
334 static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
335 "py::pos_only must come before py::kw_only");
340 static constexpr
auto signature
346 initialize_generic(std::move(unique_rec), signature.text, types.data(),
sizeof...(Args));
349 using FunctionType = Return (*)(Args...);
350 constexpr
bool is_function_ptr
352 if (is_function_ptr) {
353 rec->is_stateless =
true;
355 =
const_cast<void *
>(
reinterpret_cast<const void *
>(&
typeid(FunctionType)));
387 const std::type_info *
const *types,
393 auto *rec = unique_rec.get();
404 rec->name = guarded_strdup(rec->name ? rec->name :
"");
406 rec->doc = guarded_strdup(rec->doc);
408 for (
auto &
a : rec->args) {
410 a.name = guarded_strdup(
a.name);
413 a.descr = guarded_strdup(
a.descr);
414 }
else if (
a.value) {
415 a.descr = guarded_strdup(
repr(
a.value).
cast<std::string>().c_str());
419 rec->is_constructor = (std::strcmp(rec->name,
"__init__") == 0)
420 || (std::strcmp(rec->name,
"__setstate__") == 0);
422 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
423 if (rec->is_constructor && !rec->is_new_style_constructor) {
424 const auto class_name
426 const auto func_name = std::string(rec->name);
427 PyErr_WarnEx(PyExc_FutureWarning,
428 (
"pybind11-bound class '" + class_name
429 +
"' is using an old-style "
432 +
"' which has been deprecated. See "
433 "the upgrade guide in pybind11's docs. This message is only visible "
434 "when compiled in debug mode.")
441 std::string signature;
442 size_t type_index = 0, arg_index = 0;
443 bool is_starred =
false;
444 for (
const auto *
pc =
text; *
pc !=
'\0'; ++
pc) {
449 is_starred = *(
pc + 1) ==
'*';
455 if (!rec->has_args && arg_index == rec->nargs_pos) {
458 if (arg_index < rec->
args.
size() && rec->args[arg_index].name) {
459 signature += rec->args[arg_index].name;
460 }
else if (arg_index == 0 && rec->is_method) {
463 signature +=
"arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
466 }
else if (
c ==
'}') {
468 if (!is_starred && arg_index < rec->
args.
size() && rec->args[arg_index].descr) {
474 if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
480 }
else if (
c ==
'%') {
481 const std::type_info *
t = types[type_index++];
483 pybind11_fail(
"Internal error while parsing type signature (1)");
486 handle th((PyObject *) tinfo->type);
487 signature += th.attr(
"__module__").
cast<std::string>() +
"."
488 + th.attr(
"__qualname__").
cast<std::string>();
489 }
else if (rec->is_new_style_constructor && arg_index == 0) {
492 signature += rec->scope.attr(
"__module__").cast<std::string>() +
"."
493 + rec->scope.attr(
"__qualname__").cast<std::string>();
502 if (arg_index !=
args - rec->has_args - rec->has_kwargs || types[type_index] !=
nullptr) {
503 pybind11_fail(
"Internal error while parsing type signature (2)");
506 rec->signature = guarded_strdup(signature.c_str());
507 rec->args.shrink_to_fit();
514 detail::function_record *chain =
nullptr, *chain_start = rec;
516 if (PyCFunction_Check(rec->sibling.ptr())) {
517 auto *
self = PyCFunction_GET_SELF(rec->sibling.ptr());
518 if (!isinstance<capsule>(
self)) {
521 auto rec_capsule = reinterpret_borrow<capsule>(
self);
523 chain = rec_capsule.get_pointer<detail::function_record>();
526 if (!chain->scope.is(rec->scope)) {
536 else if (!rec->sibling.is_none() && rec->name[0] !=
'_') {
537 pybind11_fail(
"Cannot overload existing non-function object \""
538 + std::string(rec->name) +
"\" with a function of the same name");
544 rec->def =
new PyMethodDef();
545 std::memset(rec->def, 0,
sizeof(PyMethodDef));
546 rec->def->ml_name = rec->name;
548 =
reinterpret_cast<PyCFunction
>(
reinterpret_cast<void (*)()
>(
dispatcher));
549 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
551 capsule rec_capsule(unique_rec.release(),
553 [](
void *
ptr) { destruct((detail::function_record *) ptr); });
558 if (
hasattr(rec->scope,
"__module__")) {
559 scope_module = rec->scope.attr(
"__module__");
560 }
else if (
hasattr(rec->scope,
"__name__")) {
561 scope_module = rec->scope.attr(
"__name__");
565 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.
ptr(), scope_module.ptr());
567 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate function object");
571 m_ptr = rec->sibling.ptr();
573 if (chain->is_method != rec->is_method) {
575 "overloading a method with both static and instance methods is not supported; "
577 "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more "
580 "error while attempting to bind "
581 + std::string(rec->is_method ?
"instance" :
"static") +
" method "
582 + std::string(
pybind11::str(rec->scope.attr(
"__name__"))) +
"."
583 + std::string(rec->name) + signature
595 = reinterpret_borrow<capsule>(((PyCFunctionObject *)
m_ptr)->m_self);
596 rec_capsule.set_pointer(unique_rec.release());
601 while (chain->next) {
604 chain->next = unique_rec.release();
609 std::string signatures;
615 signatures += rec->name;
616 signatures +=
"(*args, **kwargs)\n";
617 signatures +=
"Overloaded function.\n\n";
620 bool first_user_def =
true;
621 for (
auto *it = chain_start; it !=
nullptr; it = it->next) {
627 signatures += std::to_string(++index) +
". ";
629 signatures += rec->name;
630 signatures += it->signature;
637 if (first_user_def) {
638 first_user_def =
false;
646 signatures += it->doc;
654 auto *
func = (PyCFunctionObject *)
m_ptr;
655 std::free(
const_cast<char *
>(
func->m_ml->ml_doc));
660 if (rec->is_method) {
664 "cpp_function::cpp_function(): Could not allocate instance method object");
671 static void destruct(detail::function_record *rec,
bool free_strings =
true) {
674 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
675 static bool is_zero = Py_GetVersion()[4] ==
'0';
679 detail::function_record *next = rec->next;
680 if (rec->free_data) {
687 std::free((
char *) rec->name);
688 std::free((
char *) rec->doc);
689 std::free((
char *) rec->signature);
690 for (
auto &
arg : rec->args) {
691 std::free(
const_cast<char *
>(
arg.
name));
692 std::free(
const_cast<char *
>(
arg.descr));
695 for (
auto &
arg : rec->args) {
699 std::free(
const_cast<char *
>(rec->def->ml_doc));
703 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
717 static PyObject *
dispatcher(PyObject *
self, PyObject *args_in, PyObject *kwargs_in) {
719 assert(isinstance<capsule>(
self));
724 *current_overload = overloads;
725 assert(overloads !=
nullptr);
729 const auto n_args_in = (
size_t) PyTuple_GET_SIZE(args_in);
731 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) :
nullptr,
737 || !PyObject_TypeCheck(parent.
ptr(), (PyTypeObject *) overloads->
scope.
ptr())) {
739 "__init__(self, ...) called with invalid or missing `self` argument");
744 auto *
const pi =
reinterpret_cast<instance *
>(parent.
ptr());
749 if (self_value_and_holder.instance_registered()) {
759 std::vector<function_call> second_pass;
762 const bool overloaded
763 = current_overload !=
nullptr && current_overload->next !=
nullptr;
765 for (; current_overload !=
nullptr; current_overload = current_overload->next) {
787 size_t num_args =
func.nargs;
791 if (
func.has_kwargs) {
794 size_t pos_args =
func.nargs_pos;
796 if (!
func.has_args && n_args_in > pos_args) {
800 if (n_args_in < pos_args &&
func.args.size() < pos_args) {
808 size_t args_to_copy = (
std::min)(pos_args, n_args_in);
809 size_t args_copied = 0;
812 if (
func.is_new_style_constructor) {
815 if (self_value_and_holder) {
816 self_value_and_holder.type->dealloc(self_value_and_holder);
819 call.
init_self = PyTuple_GET_ITEM(args_in, 0);
820 call.
args.emplace_back(
reinterpret_cast<PyObject *
>(&self_value_and_holder));
826 bool bad_arg =
false;
827 for (; args_copied < args_to_copy; ++args_copied) {
829 = args_copied <
func.args.size() ? &
func.args[args_copied] :
nullptr;
830 if (kwargs_in && arg_rec && arg_rec->
name
836 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
837 if (arg_rec && !arg_rec->
none &&
arg.is_none()) {
850 size_t positional_args_copied = args_copied;
853 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
856 if (args_copied <
func.nargs_pos_only) {
857 for (; args_copied <
func.nargs_pos_only; ++args_copied) {
858 const auto &arg_rec =
func.args[args_copied];
862 value = arg_rec.value;
872 if (args_copied <
func.nargs_pos_only) {
878 if (args_copied < num_args) {
879 bool copied_kwargs =
false;
881 for (; args_copied < num_args; ++args_copied) {
882 const auto &arg_rec =
func.args[args_copied];
885 if (kwargs_in && arg_rec.name) {
891 if (!copied_kwargs) {
893 copied_kwargs =
true;
895 if (PyDict_DelItemString(
kwargs.
ptr(), arg_rec.name) == -1) {
898 }
else if (arg_rec.value) {
899 value = arg_rec.value;
902 if (!arg_rec.none &&
value.is_none()) {
909 if (
func.has_args && call.
args.size() ==
func.nargs_pos) {
920 if (args_copied < num_args) {
934 if (args_to_copy == 0) {
937 extra_args = reinterpret_borrow<tuple>(args_in);
938 }
else if (positional_args_copied >= n_args_in) {
939 extra_args =
tuple(0);
941 size_t args_size = n_args_in - positional_args_copied;
942 extra_args =
tuple(args_size);
943 for (
size_t i = 0;
i < args_size; ++
i) {
944 extra_args[
i] = PyTuple_GET_ITEM(args_in, positional_args_copied +
i);
947 if (call.
args.size() <=
func.nargs_pos) {
948 call.
args.push_back(extra_args);
950 call.
args[
func.nargs_pos] = extra_args;
953 call.
args_ref = std::move(extra_args);
957 if (
func.has_kwargs) {
968 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
970 pybind11_fail(
"Internal error: function call dispatcher inserted wrong number "
975 std::vector<bool> second_pass_convert;
980 second_pass_convert.resize(
func.nargs,
false);
988 }
catch (reference_cast_error &) {
1000 for (
size_t i =
func.is_method ? 1 : 0;
i < pos_args;
i++) {
1001 if (second_pass_convert[
i]) {
1005 second_pass.push_back(std::move(call));
1015 for (
auto &call : second_pass) {
1018 result = call.func.impl(call);
1019 }
catch (reference_cast_error &) {
1027 current_overload = &call.func;
1037 }
catch (abi::__forced_unwind &) {
1058 auto &local_exception_translators
1074 set_error(PyExc_SystemError,
"Exception escaped from default exception translator!");
1078 auto append_note_if_missing_header_is_suspected = [](std::string &
msg) {
1079 if (
msg.find(
"std::") != std::string::npos) {
1081 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1082 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1083 "conversions are optional and require extra headers to be included\n"
1084 "when compiling your pybind11 module.";
1090 return handle(Py_NotImplemented).inc_ref().ptr();
1093 std::string
msg = std::string(overloads->
name) +
"(): incompatible "
1094 + std::string(overloads->
is_constructor ?
"constructor" :
"function")
1095 +
" arguments. The following argument types are supported:\n";
1099 msg +=
" " + std::to_string(++ctr) +
". ";
1101 bool wrote_sig =
false;
1105 std::string sig = it2->signature;
1106 size_t start = sig.find(
'(') + 7;
1107 if (start < sig.size()) {
1109 size_t end = sig.find(
", "), next =
end + 2;
1110 size_t ret = sig.rfind(
" -> ");
1112 if (
end >= sig.size()) {
1113 next =
end = sig.find(
')');
1115 if (start <
end && next < sig.size()) {
1116 msg.append(sig, start,
end - start);
1118 msg.append(sig, next,
ret - next);
1124 msg += it2->signature;
1129 msg +=
"\nInvoked with: ";
1130 auto args_ = reinterpret_borrow<tuple>(args_in);
1131 bool some_args =
false;
1132 for (
size_t ti = overloads->
is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
1141 msg +=
"<repr raised Error>";
1145 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
1152 for (
const auto &kwarg :
kwargs) {
1162 msg +=
"<repr raised Error>";
1168 append_note_if_missing_header_is_suspected(
msg);
1170 if (PyErr_Occurred()) {
1179 std::string
msg =
"Unable to convert function return value to a "
1180 "Python type! The signature was\n\t";
1181 assert(current_overload !=
nullptr);
1182 msg += current_overload->signature;
1183 append_note_if_missing_header_is_suspected(
msg);
1185 if (PyErr_Occurred()) {
1192 if (overloads->
is_constructor && !self_value_and_holder.holder_constructed()) {
1193 auto *pi =
reinterpret_cast<instance *
>(parent.
ptr());
1194 self_value_and_holder.type->init_instance(pi,
nullptr);
1213 bool flag()
const {
return flag_; }
1227 *
this = create_extension_module(
name,
doc,
new PyModuleDef());
1235 template <
typename Func,
typename... Extra>
1245 add_object(name_,
func,
true );
1260 const char *this_name = PyModule_GetName(
m_ptr);
1261 if (this_name ==
nullptr) {
1264 std::string full_name = std::string(this_name) +
'.' +
name;
1265 handle submodule = PyImport_AddModule(full_name.c_str());
1269 auto result = reinterpret_borrow<module_>(submodule);
1279 PyObject *obj = PyImport_ImportModule(
name);
1283 return reinterpret_steal<module_>(obj);
1288 PyObject *obj = PyImport_ReloadModule(
ptr());
1292 *
this = reinterpret_steal<module_>(obj);
1305 "Error during initialization: multiple incompatible definitions with name \""
1306 + std::string(
name) +
"\"");
1327 PyModuleDef{ PyModuleDef_HEAD_INIT,
1336 auto *
m = PyModule_Create(def);
1338 if (PyErr_Occurred()) {
1341 pybind11_fail(
"Internal error in module_::create_extension_module()");
1343 if (gil_not_used.flag()) {
1344 #ifdef Py_GIL_DISABLED
1345 PyUnstable_Module_SetGIL(
m, Py_MOD_GIL_NOT_USED);
1351 return reinterpret_borrow<module_>(
m);
1373 #if PY_VERSION_HEX >= 0x030d0000
1374 PyObject *
p = PyEval_GetFrameGlobals();
1375 return p ? reinterpret_steal<dict>(
p)
1378 PyObject *
p = PyEval_GetGlobals();
1385 "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
1386 object make_simple_namespace(Args &&...args_) {
1387 return module_::import(
"types").attr(
"SimpleNamespace")(std::forward<Args>(args_)...);
1392 class generic_type : public
object {
1398 && rec.
scope.attr(
"__dict__").contains(rec.
name)) {
1400 +
"\": an object with that name is already defined");
1406 +
"\" is already registered!");
1412 auto *tinfo =
new detail::type_info();
1413 tinfo->type = (PyTypeObject *)
m_ptr;
1414 tinfo->cpptype = rec.
type;
1421 tinfo->simple_type =
true;
1422 tinfo->simple_ancestors =
true;
1427 auto tindex = std::type_index(*rec.
type);
1438 mark_parents_nonsimple(tinfo->type);
1439 tinfo->simple_ancestors =
false;
1440 }
else if (rec.
bases.size() == 1) {
1442 assert(parent_tinfo !=
nullptr);
1443 bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1444 tinfo->simple_ancestors = parent_simple_ancestors;
1446 parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1458 auto t = reinterpret_borrow<tuple>(
value->tp_bases);
1462 tinfo2->simple_type =
false;
1464 mark_parents_nonsimple((PyTypeObject *)
h.ptr());
1469 void *get_buffer_data) {
1470 auto *
type = (PyHeapTypeObject *)
m_ptr;
1473 if (!
type->ht_type.tp_as_buffer) {
1474 pybind11_fail(
"To be able to register buffer protocol support for the type '"
1476 +
"' the associated class<>(..) invocation must "
1477 "include the pybind11::buffer_protocol() annotation!");
1480 tinfo->get_buffer = get_buffer;
1481 tinfo->get_buffer_data = get_buffer_data;
1488 detail::function_record *rec_func) {
1489 const auto is_static = (rec_func !=
nullptr) && !(rec_func->is_method && rec_func->scope);
1490 const auto has_doc = (rec_func !=
nullptr) && (rec_func->doc !=
nullptr)
1491 && pybind11::options::show_user_defined_docstrings();
1493 (PyObject *) (is_static ?
get_internals().static_property_type : &PyProperty_Type));
1502 template <
typename T,
1511 template <
typename T,
typename SFINAE =
void>
1513 template <
typename T>
1515 : std::true_type {};
1516 template <
typename T,
typename SFINAE =
void>
1518 template <
typename T>
1526 T::operator
delete(
p);
1528 template <
typename T,
1532 T::operator
delete(
p,
s);
1538 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1539 if (
a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1540 # ifdef __cpp_sized_deallocation
1541 ::operator
delete(
p,
s, std::align_val_t(
a));
1543 ::operator
delete(
p, std::align_val_t(
a));
1548 #ifdef __cpp_sized_deallocation
1549 ::operator
delete(
p,
s);
1551 ::operator
delete(
p);
1556 cls.attr(cf.
name()) = cf;
1557 if (std::strcmp(name_,
"__eq__") == 0 && !cls.attr(
"__dict__").contains(
"__hash__")) {
1558 cls.attr(
"__hash__") =
none();
1564 template <
typename ,
typename F>
1568 return std::forward<F>(
f);
1571 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1575 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1579 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1580 auto method_adaptor(Return (Class::*pmf)(Args...)
const) -> Return (Derived::*)(Args...)
const {
1583 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1587 template <
typename type_,
typename...
options>
1589 template <
typename T>
1591 template <
typename T>
1593 template <
typename T>
1594 using is_base = detail::is_strict_base_of<T, type_>;
1596 template <
typename T>
1606 "Unknown/invalid class_ template parameters provided");
1609 "Cannot use an alias class with a non-polymorphic type");
1613 template <
typename... Extra>
1623 none_of<std::is_same<multiple_inheritance, Extra>...>::
value),
1624 "Error: multiple inheritance bases must be specified via class_ template options");
1637 set_operator_new<type>(&record);
1651 instances[std::type_index(
typeid(
type_alias))]
1652 = instances[std::type_index(
typeid(
type))];
1659 rec.add_base(
typeid(Base), [](
void *src) ->
void * {
1660 return static_cast<Base *
>(
reinterpret_cast<type *
>(src));
1667 template <
typename Func,
typename... Extra>
1668 class_ &
def(
const char *name_, Func &&
f,
const Extra &...extra) {
1669 cpp_function cf(method_adaptor<type>(std::forward<Func>(
f)),
1678 template <
typename Func,
typename... Extra>
1679 class_ &
def_static(
const char *name_, Func &&
f,
const Extra &...extra) {
1681 "def_static(...) called with a non-static member function pointer");
1687 auto cf_name = cf.
name();
1688 attr(std::move(cf_name)) =
staticmethod(std::move(cf));
1692 template <
typename T,
typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1693 class_ &
def(
const T &op,
const Extra &...extra) {
1694 op.execute(*
this, extra...);
1698 template <
typename T,
typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1700 op.execute_cast(*
this, extra...);
1704 template <
typename... Args,
typename... Extra>
1705 class_ &
def(
const detail::initimpl::constructor<Args...> &
init,
const Extra &...extra) {
1707 init.execute(*
this, extra...);
1711 template <
typename... Args,
typename... Extra>
1712 class_ &
def(
const detail::initimpl::alias_constructor<Args...> &
init,
const Extra &...extra) {
1714 init.execute(*
this, extra...);
1718 template <
typename... Args,
typename... Extra>
1719 class_ &
def(detail::initimpl::factory<Args...> &&
init,
const Extra &...extra) {
1720 std::move(
init).execute(*
this, extra...);
1724 template <
typename... Args,
typename... Extra>
1725 class_ &
def(detail::initimpl::pickle_factory<Args...> &&pf,
const Extra &...extra) {
1726 std::move(pf).execute(*
this, extra...);
1730 template <
typename Func>
1736 install_buffer_funcs(
1738 detail::make_caster<type> caster;
1739 if (!caster.load(obj,
false)) {
1753 template <
typename Return,
typename Class,
typename... Args>
1755 return def_buffer([
func](
type &obj) {
return (obj.*
func)(); });
1758 template <
typename Return,
typename Class,
typename... Args>
1760 return def_buffer([
func](
const type &obj) {
return (obj.*
func)(); });
1763 template <
typename C,
typename D,
typename... Extra>
1766 "def_readwrite() requires a class member (or base class member)");
1773 template <
typename C,
typename D,
typename... Extra>
1776 "def_readonly() requires a class member (or base class member)");
1782 template <
typename D,
typename... Extra>
1790 template <
typename D,
typename... Extra>
1798 template <
typename Getter,
typename... Extra>
1800 return def_property_readonly(
name,
1807 template <
typename... Extra>
1810 return def_property(
name, fget,
nullptr, extra...);
1814 template <
typename Getter,
typename... Extra>
1817 return def_property_readonly_static(
1822 template <
typename... Extra>
1825 const Extra &...extra) {
1826 return def_property_static(
name, fget,
nullptr, extra...);
1830 template <
typename Getter,
typename Setter,
typename... Extra>
1832 def_property(
const char *
name,
const Getter &fget,
const Setter &fset,
const Extra &...extra) {
1833 return def_property(
1836 template <
typename Getter,
typename... Extra>
1840 const Extra &...extra) {
1841 return def_property(
name,
1849 template <
typename... Extra>
1853 const Extra &...extra) {
1854 return def_property_static(
name, fget, fset,
is_method(*
this), extra...);
1858 template <
typename Getter,
typename... Extra>
1862 const Extra &...extra) {
1863 return def_property_static(
1868 template <
typename... Extra>
1872 const Extra &...extra) {
1874 "Argument annotations are not allowed for properties");
1875 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1876 auto *rec_active = rec_fget;
1878 char *doc_prev = rec_fget->doc;
1881 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1882 std::free(doc_prev);
1887 char *doc_prev = rec_fset->doc;
1889 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1890 std::free(doc_prev);
1894 rec_active = rec_fset;
1897 def_property_static_impl(
name, fget, fset, rec_active);
1903 template <
typename T>
1905 detail::value_and_holder &v_h,
1907 const std::enable_shared_from_this<T> * ) {
1909 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1913 v_h.set_holder_constructed();
1916 if (!v_h.holder_constructed() &&
inst->owned) {
1918 v_h.set_holder_constructed();
1939 detail::value_and_holder &v_h,
1943 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1944 v_h.set_holder_constructed();
1947 v_h.set_holder_constructed();
1957 if (!v_h.instance_registered()) {
1959 v_h.set_instance_registered();
1965 static void dealloc(detail::value_and_holder &v_h) {
1973 if (v_h.holder_constructed()) {
1975 v_h.set_holder_constructed(
false);
1978 v_h.value_ptr<
type>(), v_h.type->type_size, v_h.type->type_align);
1980 v_h.value_ptr() =
nullptr;
1989 handle func_self = PyCFunction_GET_SELF(
h.ptr());
1993 if (!isinstance<capsule>(func_self)) {
1996 auto cap = reinterpret_borrow<capsule>(func_self);
2000 return cap.get_pointer<detail::function_record>();
2005 template <
typename... Args>
2006 detail::initimpl::constructor<Args...>
init() {
2011 template <
typename... Args>
2017 template <
typename Func,
typename Ret = detail::initimpl::factory<Func>>
2019 return {std::forward<Func>(
f)};
2025 template <
typename CFunc,
typename AFunc,
typename Ret = detail::initimpl::factory<CFunc, AFunc>>
2027 return {std::forward<CFunc>(
c), std::forward<AFunc>(
a)};
2032 template <
typename GetState,
typename SetState>
2033 detail::initimpl::pickle_factory<GetState, SetState>
pickle(GetState &&
g, SetState &&
s) {
2034 return {std::forward<GetState>(
g), std::forward<SetState>(
s)};
2040 dict entries =
arg.get_type().attr(
"__entries");
2041 for (
auto kv : entries) {
2053 m_base.attr(
"__entries") =
dict();
2054 auto property =
handle((PyObject *) &PyProperty_Type);
2058 [](
const object &
arg) ->
str {
2078 m_base.attr(
"__doc__") = static_property(
2081 std::string docstring;
2082 dict entries =
arg.attr(
"__entries");
2083 if (((PyTypeObject *)
arg.ptr())->tp_doc) {
2084 docstring += std::string(
2085 reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);
2086 docstring +=
"\n\n";
2088 docstring +=
"Members:";
2089 for (
auto kv : entries) {
2091 auto comment = kv.second[
int_(1)];
2092 docstring +=
"\n\n ";
2094 if (!comment.is_none()) {
2107 m_base.attr(
"__members__") = static_property(
cpp_function(
2109 dict entries =
arg.attr(
"__entries"),
2111 for (
auto kv : entries) {
2112 m[kv.first] = kv.second[
int_(0)];
2116 name(
"__members__")),
2121 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
2122 m_base.attr(op) = cpp_function( \
2123 [](const object &a, const object &b) { \
2124 if (!type::handle_of(a).is(type::handle_of(b))) \
2129 is_method(m_base), \
2132 #define PYBIND11_ENUM_OP_CONV(op, expr) \
2133 m_base.attr(op) = cpp_function( \
2134 [](const object &a_, const object &b_) { \
2135 int_ a(a_), b(b_); \
2139 is_method(m_base), \
2142 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
2143 m_base.attr(op) = cpp_function( \
2144 [](const object &a_, const object &b) { \
2149 is_method(m_base), \
2152 if (is_convertible) {
2156 if (is_arithmetic) {
2167 m_base.attr(
"__invert__")
2176 if (is_arithmetic) {
2177 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
2182 #undef PYBIND11_THROW
2186 #undef PYBIND11_ENUM_OP_CONV_LHS
2187 #undef PYBIND11_ENUM_OP_CONV
2188 #undef PYBIND11_ENUM_OP_STRICT
2198 dict entries = m_base.attr(
"__entries");
2201 std::string
type_name = (std::string)
str(m_base.attr(
"__name__"));
2202 throw value_error(std::move(
type_name) +
": element \"" + std::string(name_)
2203 +
"\" already exists!");
2207 m_base.attr(std::move(
name)) = std::move(
value);
2211 dict entries = m_base.attr(
"__entries");
2212 for (
auto kv : entries) {
2213 m_parent.attr(kv.first) = kv.second[
int_(0)];
2221 template <
bool is_
signed,
size_t length>
2256 template <
typename IntLike>
2262 template <
typename Type>
2269 using Base::def_property_readonly;
2270 using Base::def_property_readonly_static;
2273 using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2274 std::is_same<Underlying, bool>>
::value,
2275 detail::equivalent_integer_t<Underlying>,
2278 template <
typename... Extra>
2281 constexpr
bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>
::value;
2283 m_base.init(is_arithmetic, is_convertible);
2290 [](detail::value_and_holder &v_h,
Scalar arg) {
2291 detail::initimpl::setstate<Base>(
2292 v_h,
static_cast<Type>(
arg), Py_TYPE(v_h.inst) != v_h.type->type);
2294 detail::is_new_style_constructor(),
2319 if (!nurse || !patient) {
2323 if (patient.is_none() || nurse.is_none()) {
2328 if (!tinfo.empty()) {
2341 weakref wr(nurse, disable_lifesupport);
2344 (void) wr.release();
2350 auto get_arg = [&](
size_t n) {
2357 if (
n <= call.
args.size()) {
2358 return call.
args[
n - 1];
2371 #ifdef __cpp_lib_unordered_map_try_emplace
2374 .emplace(
type, std::vector<detail::type_info *>());
2386 for (
auto it = cache.begin(),
last = cache.end(); it !=
last;) {
2387 if (it->first == reinterpret_cast<PyObject *>(type)) {
2388 it = cache.erase(it);
2406 template <
typename Access,
2422 template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
2429 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).
first)>
2446 decltype(((*std::declval<Iterator &>()).
first)),
2447 decltype(std::declval<pair_type>().first)>;
2451 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
2459 decltype(((*std::declval<Iterator &>()).second)),
2460 decltype(std::declval<pair_type>().second)>;
2464 template <
typename Access,
2471 using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
2475 class_<state>(
handle(),
"iterator", pybind11::module_local())
2476 .def(
"__iter__", [](
state &
s) ->
state & {
return s; })
2479 [](
state &
s) -> ValueType {
2480 if (!
s.first_or_done) {
2483 s.first_or_done = false;
2485 if (
s.it ==
s.end) {
2486 s.first_or_done = true;
2487 throw stop_iteration();
2489 return Access()(
s.it);
2492 std::forward<Extra>(extra)...,
2496 return cast(
state{std::forward<Iterator>(
first), std::forward<Sentinel>(
last),
true});
2505 typename ValueType =
typename detail::iterator_access<Iterator>::result_type,
2508 return detail::make_iterator_impl<detail::iterator_access<Iterator>,
2513 Extra...>(std::forward<Iterator>(
first),
2514 std::forward<Sentinel>(
last),
2515 std::forward<Extra>(extra)...);
2523 typename KeyType =
typename detail::iterator_key_access<Iterator>::result_type,
2526 return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
2531 Extra...>(std::forward<Iterator>(
first),
2532 std::forward<Sentinel>(
last),
2533 std::forward<Extra>(extra)...);
2541 typename ValueType =
typename detail::iterator_value_access<Iterator>::result_type,
2544 return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
2549 Extra...>(std::forward<Iterator>(
first),
2550 std::forward<Sentinel>(
last),
2551 std::forward<Extra>(extra)...);
2558 typename ValueType =
typename detail::iterator_access<
2559 decltype(std::begin(std::declval<Type &>()))>::result_type,
2562 return make_iterator<Policy>(
2570 typename KeyType =
typename detail::iterator_key_access<
2571 decltype(std::begin(std::declval<Type &>()))>::result_type,
2574 return make_key_iterator<Policy>(
2582 typename ValueType =
typename detail::iterator_value_access<
2583 decltype(std::begin(std::declval<Type &>()))>::result_type,
2586 return make_value_iterator<Policy>(
2590 template <
typename InputType,
typename OutputType>
2594 explicit set_flag(
bool &flag_) : flag(flag_) { flag_ =
true; }
2595 ~set_flag() { flag =
false; }
2597 auto implicit_caster = [](PyObject *obj, PyTypeObject *
type) -> PyObject * {
2598 #ifdef Py_GIL_DISABLED
2599 thread_local
bool currently_used =
false;
2601 static bool currently_used =
false;
2603 if (currently_used) {
2606 set_flag flag_helper(currently_used);
2607 if (!detail::make_caster<InputType>().load(obj,
false)) {
2620 tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
2622 pybind11_fail(
"implicitly_convertible: Unable to find type " + type_id<OutputType>());
2629 std::forward<ExceptionTranslator>(translator));
2643 std::forward<ExceptionTranslator>(translator));
2654 template <
typename type>
2657 exception() =
default;
2659 std::string full_name
2660 =
scope.attr(
"__name__").cast<std::string>() + std::string(
".") +
name;
2661 m_ptr = PyErr_NewException(
const_cast<char *
>(full_name.c_str()),
base.ptr(),
nullptr);
2663 pybind11_fail(
"Error during initialization: multiple incompatible "
2664 "definitions with name \""
2665 + std::string(
name) +
"\"");
2672 "(https://github.com/pybind/pybind11/pull/4772)")
2673 void operator()(const
char *message)
const {
set_error(*
this, message); }
2684 template <
typename CppException>
2685 exception<CppException> &
2689 [&]() {
return exception<CppException>(
scope,
name,
base); });
2694 register_func([](std::exception_ptr
p) {
2699 std::rethrow_exception(
p);
2700 }
catch (
const CppException &
e) {
2701 set_error(exc_storage.get_stored(),
e.what());
2704 return exc_storage.get_stored();
2715 template <
typename CppException>
2716 exception<CppException> &
2718 return detail::register_exception_impl<CppException>(
scope,
name,
base,
false );
2729 template <
typename CppException>
2730 exception<CppException> &
2732 return detail::register_exception_impl<CppException>(
scope,
name,
base,
true );
2742 auto line =
sep.attr(
"join")(std::move(strings));
2760 write(std::move(line));
2764 file.attr(
"flush")();
2771 auto c = detail::collect_arguments<policy>(std::forward<Args>(
args)...);
2785 return m_fetched_error->error_string().c_str();
2803 return cache.find(
key) != cache.end();
2805 if (not_overridden) {
2809 function override =
getattr(
self,
name,
function());
2819 #if !defined(PYPY_VERSION)
2820 # if PY_VERSION_HEX >= 0x03090000
2821 PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
2822 if (frame !=
nullptr) {
2823 PyCodeObject *f_code = PyFrame_GetCode(frame);
2825 if ((std::string)
str(f_code->co_name) ==
name && f_code->co_argcount > 0) {
2826 # if PY_VERSION_HEX >= 0x030d0000
2827 PyObject *locals = PyEval_GetFrameLocals();
2829 PyObject *locals = PyEval_GetLocals();
2832 if (locals !=
nullptr) {
2833 # if PY_VERSION_HEX >= 0x030b0000
2834 PyObject *co_varnames = PyCode_GetVarnames(f_code);
2836 PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code,
"co_varnames");
2838 PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
2839 Py_DECREF(co_varnames);
2840 PyObject *self_caller =
dict_getitem(locals, self_arg);
2842 if (self_caller ==
self.
ptr()) {
2853 PyFrameObject *frame = PyThreadState_Get()->frame;
2854 if (frame !=
nullptr && (std::string)
str(frame->f_code->co_name) ==
name
2855 && frame->f_code->co_argcount > 0) {
2856 PyFrame_FastToLocals(frame);
2857 PyObject *self_caller
2858 =
dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2859 if (self_caller ==
self.
ptr()) {
2873 = PyRun_String(
"import inspect\n"
2874 "frame = inspect.currentframe()\n"
2875 "if frame is not None:\n"
2876 " frame = frame.f_back\n"
2877 " if frame is not None and str(frame.f_code.co_name) == name and "
2878 "frame.f_code.co_argcount > 0:\n"
2879 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2880 " if self_caller == self:\n"
2888 if (
d[
"self"].is_none())
2911 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
2913 pybind11::gil_scoped_acquire gil; \
2914 pybind11::function override \
2915 = pybind11::get_override(static_cast<const cname *>(this), name); \
2917 auto o = override(__VA_ARGS__); \
2918 PYBIND11_WARNING_PUSH \
2919 PYBIND11_WARNING_DISABLE_MSVC(4127) \
2920 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value \
2921 && !pybind11::detail::is_same_ignoring_cvref<ret_type, PyObject *>::value) { \
2922 static pybind11::detail::override_caster_t<ret_type> caster; \
2923 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
2925 PYBIND11_WARNING_POP \
2926 return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2948 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
2950 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2951 return cname::fn(__VA_ARGS__); \
2958 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
2960 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2961 pybind11::pybind11_fail( \
2962 "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
2990 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
2991 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2997 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
2998 PYBIND11_OVERRIDE_PURE_NAME( \
2999 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
3014 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
3015 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
3016 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
3017 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
3018 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
3019 PYBIND11_OVERRIDE_PURE_NAME( \
3020 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
3021 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
3022 PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
3023 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
3024 PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);