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
31 # define PYBIND11_STD_LAUNDER
32 # define PYBIND11_HAS_STD_LAUNDER 0
34 #if defined(__GNUG__) && !defined(__clang__)
47 #if defined(__GNUC__) && __GNUC__ == 7
60 auto last_exception = std::current_exception();
62 for (
auto &translator : translators) {
64 translator(last_exception);
67 last_exception = std::current_exception();
74 # define PYBIND11_COMPAT_STRDUP _strdup
76 # define PYBIND11_COMPAT_STRDUP strdup
90 template <
typename Return,
typename... Args,
typename... Extra>
97 template <
typename Func,
103 std::forward<Func>(
f), (detail::function_signature_t<Func> *)
nullptr, extra...);
107 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
111 [
f](
Class *
c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
112 (Return(*)(
Class *, Arg...))
nullptr,
119 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
123 [
f](
Class *
c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
124 (Return(*)(
Class *, Arg...))
nullptr,
129 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
133 Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
134 (Return(*)(
const Class *, Arg...))
nullptr,
141 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
145 Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
146 (Return(*)(
const Class *, Arg...))
nullptr,
151 object name()
const {
return attr(
"__name__"); }
160 = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
168 template <
typename Func,
typename Return,
typename... Args,
typename... Extra>
169 void initialize(Func &&
f, Return (*)(Args...),
const Extra &...extra) {
179 auto *rec = unique_rec.get();
182 if (
sizeof(
capture) <=
sizeof(rec->data)) {
186 PYBIND11_WARNING_PUSH
188 #if defined(__GNUG__) && __GNUC__ >= 6
194 #if !PYBIND11_HAS_STD_LAUNDER
209 rec->data[0] =
new capture{std::forward<Func>(
f)};
219 expected_num_args<Extra...>(
220 sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
221 "The number of argument annotations does not match the number of function arguments");
225 cast_in args_converter;
228 if (!args_converter.load_args(call)) {
236 const auto *
data = (
sizeof(
capture) <=
sizeof(call.func.data) ? &call.func.data
237 : call.func.data[0]);
249 if (call.func.is_setter) {
250 (void) std::move(args_converter).template call<Return, Guard>(cap->f);
254 std::move(args_converter).
template call<Return, Guard>(cap->f),
265 rec->nargs_pos = cast_in::args_pos >= 0
267 :
sizeof...(Args) - cast_in::has_kwargs;
269 rec->has_args = cast_in::args_pos >= 0;
270 rec->has_kwargs = cast_in::has_kwargs;
276 constexpr
bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>
::value,
277 has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>
::value,
278 has_arg_annotations = any_of<is_keyword<Extra>...>
::value;
279 static_assert(has_arg_annotations || !has_kw_only_args,
280 "py::kw_only requires the use of argument annotations");
281 static_assert(has_arg_annotations || !has_pos_only_args,
282 "py::pos_only requires the use of argument annotations (for docstrings "
283 "and aligning the annotations to the argument)");
286 "py::kw_only may be specified only once");
288 "py::pos_only may be specified only once");
291 static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
292 "py::pos_only must come before py::kw_only");
297 static constexpr
auto signature
303 initialize_generic(std::move(unique_rec), signature.text, types.data(),
sizeof...(Args));
306 using FunctionType = Return (*)(Args...);
307 constexpr
bool is_function_ptr
309 if (is_function_ptr) {
310 rec->is_stateless =
true;
312 =
const_cast<void *
>(
reinterpret_cast<const void *
>(&
typeid(FunctionType)));
344 const std::type_info *
const *types,
350 auto *rec = unique_rec.get();
361 rec->name = guarded_strdup(rec->name ? rec->name :
"");
363 rec->doc = guarded_strdup(rec->doc);
365 for (
auto &
a : rec->args) {
367 a.name = guarded_strdup(
a.name);
370 a.descr = guarded_strdup(
a.descr);
371 }
else if (
a.value) {
372 a.descr = guarded_strdup(
repr(
a.value).
cast<std::string>().c_str());
376 rec->is_constructor = (std::strcmp(rec->name,
"__init__") == 0)
377 || (std::strcmp(rec->name,
"__setstate__") == 0);
379 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
380 if (rec->is_constructor && !rec->is_new_style_constructor) {
381 const auto class_name
383 const auto func_name = std::string(rec->name);
384 PyErr_WarnEx(PyExc_FutureWarning,
385 (
"pybind11-bound class '" + class_name
386 +
"' is using an old-style "
389 +
"' which has been deprecated. See "
390 "the upgrade guide in pybind11's docs. This message is only visible "
391 "when compiled in debug mode.")
398 std::string signature;
399 size_t type_index = 0, arg_index = 0;
400 bool is_starred =
false;
401 for (
const auto *
pc =
text; *
pc !=
'\0'; ++
pc) {
406 is_starred = *(
pc + 1) ==
'*';
412 if (!rec->has_args && arg_index == rec->nargs_pos) {
415 if (arg_index < rec->
args.
size() && rec->args[arg_index].name) {
416 signature += rec->args[arg_index].name;
417 }
else if (arg_index == 0 && rec->is_method) {
420 signature +=
"arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
423 }
else if (
c ==
'}') {
425 if (!is_starred && arg_index < rec->
args.
size() && rec->args[arg_index].descr) {
427 signature += rec->args[arg_index].descr;
431 if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
437 }
else if (
c ==
'%') {
438 const std::type_info *
t = types[type_index++];
440 pybind11_fail(
"Internal error while parsing type signature (1)");
443 handle th((PyObject *) tinfo->type);
444 signature += th.attr(
"__module__").
cast<std::string>() +
"."
445 + th.attr(
"__qualname__").
cast<std::string>();
446 }
else if (rec->is_new_style_constructor && arg_index == 0) {
449 signature += rec->scope.attr(
"__module__").cast<std::string>() +
"."
450 + rec->scope.attr(
"__qualname__").cast<std::string>();
452 std::string tname(
t->name());
461 if (arg_index !=
args - rec->has_args - rec->has_kwargs || types[type_index] !=
nullptr) {
462 pybind11_fail(
"Internal error while parsing type signature (2)");
465 rec->signature = guarded_strdup(signature.c_str());
466 rec->args.shrink_to_fit();
473 detail::function_record *chain =
nullptr, *chain_start = rec;
475 if (PyCFunction_Check(rec->sibling.ptr())) {
476 auto *
self = PyCFunction_GET_SELF(rec->sibling.ptr());
477 if (!isinstance<capsule>(
self)) {
480 auto rec_capsule = reinterpret_borrow<capsule>(
self);
482 chain = rec_capsule.get_pointer<detail::function_record>();
485 if (!chain->scope.is(rec->scope)) {
495 else if (!rec->sibling.is_none() && rec->name[0] !=
'_') {
496 pybind11_fail(
"Cannot overload existing non-function object \""
497 + std::string(rec->name) +
"\" with a function of the same name");
503 rec->def =
new PyMethodDef();
504 std::memset(rec->def, 0,
sizeof(PyMethodDef));
505 rec->def->ml_name = rec->name;
507 =
reinterpret_cast<PyCFunction
>(
reinterpret_cast<void (*)()
>(
dispatcher));
508 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
510 capsule rec_capsule(unique_rec.release(),
512 [](
void *
ptr) { destruct((detail::function_record *) ptr); });
517 if (
hasattr(rec->scope,
"__module__")) {
518 scope_module = rec->scope.attr(
"__module__");
519 }
else if (
hasattr(rec->scope,
"__name__")) {
520 scope_module = rec->scope.attr(
"__name__");
524 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.
ptr(), scope_module.ptr());
526 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate function object");
530 m_ptr = rec->sibling.ptr();
532 if (chain->is_method != rec->is_method) {
534 "overloading a method with both static and instance methods is not supported; "
536 "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more "
539 "error while attempting to bind "
540 + std::string(rec->is_method ?
"instance" :
"static") +
" method "
541 + std::string(
pybind11::str(rec->scope.attr(
"__name__"))) +
"."
542 + std::string(rec->name) + signature
554 = reinterpret_borrow<capsule>(((PyCFunctionObject *)
m_ptr)->m_self);
555 rec_capsule.set_pointer(unique_rec.release());
560 while (chain->next) {
563 chain->next = unique_rec.release();
568 std::string signatures;
574 signatures += rec->name;
575 signatures +=
"(*args, **kwargs)\n";
576 signatures +=
"Overloaded function.\n\n";
579 bool first_user_def =
true;
580 for (
auto *it = chain_start; it !=
nullptr; it = it->next) {
586 signatures += std::to_string(++index) +
". ";
588 signatures += rec->name;
589 signatures += it->signature;
596 if (first_user_def) {
597 first_user_def =
false;
605 signatures += it->doc;
613 auto *
func = (PyCFunctionObject *)
m_ptr;
614 std::free(
const_cast<char *
>(
func->m_ml->ml_doc));
619 if (rec->is_method) {
623 "cpp_function::cpp_function(): Could not allocate instance method object");
630 static void destruct(detail::function_record *rec,
bool free_strings =
true) {
633 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
634 static bool is_zero = Py_GetVersion()[4] ==
'0';
638 detail::function_record *next = rec->next;
639 if (rec->free_data) {
646 std::free((
char *) rec->name);
647 std::free((
char *) rec->doc);
648 std::free((
char *) rec->signature);
649 for (
auto &
arg : rec->args) {
650 std::free(
const_cast<char *
>(
arg.
name));
651 std::free(
const_cast<char *
>(
arg.descr));
654 for (
auto &
arg : rec->args) {
658 std::free(
const_cast<char *
>(rec->def->ml_doc));
662 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
676 static PyObject *
dispatcher(PyObject *
self, PyObject *args_in, PyObject *kwargs_in) {
678 assert(isinstance<capsule>(
self));
684 assert(overloads !=
nullptr);
688 const auto n_args_in = (
size_t) PyTuple_GET_SIZE(args_in);
690 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) :
nullptr,
696 || !PyObject_TypeCheck(parent.
ptr(), (PyTypeObject *) overloads->
scope.
ptr())) {
699 "__init__(self, ...) called with invalid or missing `self` argument");
704 auto *
const pi =
reinterpret_cast<instance *
>(parent.
ptr());
709 if (self_value_and_holder.instance_registered()) {
719 std::vector<function_call> second_pass;
722 const bool overloaded = it !=
nullptr && it->next !=
nullptr;
724 for (; it !=
nullptr; it = it->next) {
746 size_t num_args =
func.nargs;
750 if (
func.has_kwargs) {
753 size_t pos_args =
func.nargs_pos;
755 if (!
func.has_args && n_args_in > pos_args) {
759 if (n_args_in < pos_args &&
func.args.size() < pos_args) {
767 size_t args_to_copy = (
std::min)(pos_args, n_args_in);
768 size_t args_copied = 0;
771 if (
func.is_new_style_constructor) {
774 if (self_value_and_holder) {
775 self_value_and_holder.type->dealloc(self_value_and_holder);
778 call.
init_self = PyTuple_GET_ITEM(args_in, 0);
779 call.
args.emplace_back(
reinterpret_cast<PyObject *
>(&self_value_and_holder));
785 bool bad_arg =
false;
786 for (; args_copied < args_to_copy; ++args_copied) {
788 = args_copied <
func.args.size() ? &
func.args[args_copied] :
nullptr;
789 if (kwargs_in && arg_rec && arg_rec->
name
795 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
796 if (arg_rec && !arg_rec->
none &&
arg.is_none()) {
809 size_t positional_args_copied = args_copied;
812 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
815 if (args_copied <
func.nargs_pos_only) {
816 for (; args_copied <
func.nargs_pos_only; ++args_copied) {
817 const auto &arg_rec =
func.args[args_copied];
821 value = arg_rec.value;
831 if (args_copied <
func.nargs_pos_only) {
837 if (args_copied < num_args) {
838 bool copied_kwargs =
false;
840 for (; args_copied < num_args; ++args_copied) {
841 const auto &arg_rec =
func.args[args_copied];
844 if (kwargs_in && arg_rec.name) {
850 if (!copied_kwargs) {
852 copied_kwargs =
true;
854 if (PyDict_DelItemString(
kwargs.
ptr(), arg_rec.name) == -1) {
857 }
else if (arg_rec.value) {
858 value = arg_rec.value;
861 if (!arg_rec.none &&
value.is_none()) {
868 if (
func.has_args && call.
args.size() ==
func.nargs_pos) {
879 if (args_copied < num_args) {
893 if (args_to_copy == 0) {
896 extra_args = reinterpret_borrow<tuple>(args_in);
897 }
else if (positional_args_copied >= n_args_in) {
898 extra_args =
tuple(0);
900 size_t args_size = n_args_in - positional_args_copied;
901 extra_args =
tuple(args_size);
902 for (
size_t i = 0;
i < args_size; ++
i) {
903 extra_args[
i] = PyTuple_GET_ITEM(args_in, positional_args_copied +
i);
906 if (call.
args.size() <=
func.nargs_pos) {
907 call.
args.push_back(extra_args);
909 call.
args[
func.nargs_pos] = extra_args;
912 call.
args_ref = std::move(extra_args);
916 if (
func.has_kwargs) {
927 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
929 pybind11_fail(
"Internal error: function call dispatcher inserted wrong number "
934 std::vector<bool> second_pass_convert;
939 second_pass_convert.resize(
func.nargs,
false);
947 }
catch (reference_cast_error &) {
959 for (
size_t i =
func.is_method ? 1 : 0;
i < pos_args;
i++) {
960 if (second_pass_convert[
i]) {
964 second_pass.push_back(std::move(call));
974 for (
auto &call : second_pass) {
977 result = call.func.impl(call);
978 }
catch (reference_cast_error &) {
996 }
catch (abi::__forced_unwind &) {
1016 auto &local_exception_translators
1026 PyErr_SetString(PyExc_SystemError,
1027 "Exception escaped from default exception translator!");
1031 auto append_note_if_missing_header_is_suspected = [](std::string &
msg) {
1032 if (
msg.find(
"std::") != std::string::npos) {
1034 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1035 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1036 "conversions are optional and require extra headers to be included\n"
1037 "when compiling your pybind11 module.";
1043 return handle(Py_NotImplemented).inc_ref().ptr();
1046 std::string
msg = std::string(overloads->
name) +
"(): incompatible "
1047 + std::string(overloads->
is_constructor ?
"constructor" :
"function")
1048 +
" arguments. The following argument types are supported:\n";
1052 msg +=
" " + std::to_string(++ctr) +
". ";
1054 bool wrote_sig =
false;
1058 std::string sig = it2->signature;
1059 size_t start = sig.find(
'(') + 7;
1060 if (start < sig.size()) {
1062 size_t end = sig.find(
", "), next =
end + 2;
1063 size_t ret = sig.rfind(
" -> ");
1065 if (
end >= sig.size()) {
1066 next =
end = sig.find(
')');
1068 if (start <
end && next < sig.size()) {
1069 msg.append(sig, start,
end - start);
1071 msg.append(sig, next,
ret - next);
1077 msg += it2->signature;
1082 msg +=
"\nInvoked with: ";
1083 auto args_ = reinterpret_borrow<tuple>(args_in);
1084 bool some_args =
false;
1085 for (
size_t ti = overloads->
is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
1094 msg +=
"<repr raised Error>";
1098 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
1105 for (
auto kwarg :
kwargs) {
1115 msg +=
"<repr raised Error>";
1121 append_note_if_missing_header_is_suspected(
msg);
1123 if (PyErr_Occurred()) {
1128 PyErr_SetString(PyExc_TypeError,
msg.c_str());
1132 std::string
msg =
"Unable to convert function return value to a "
1133 "Python type! The signature was\n\t";
1134 msg += it->signature;
1135 append_note_if_missing_header_is_suspected(
msg);
1137 if (PyErr_Occurred()) {
1141 PyErr_SetString(PyExc_TypeError,
msg.c_str());
1144 if (overloads->
is_constructor && !self_value_and_holder.holder_constructed()) {
1145 auto *pi =
reinterpret_cast<instance *
>(parent.
ptr());
1146 self_value_and_holder.type->init_instance(pi,
nullptr);
1160 *
this = create_extension_module(
name,
doc,
new PyModuleDef());
1168 template <
typename Func,
typename... Extra>
1178 add_object(name_,
func,
true );
1193 const char *this_name = PyModule_GetName(
m_ptr);
1194 if (this_name ==
nullptr) {
1197 std::string full_name = std::string(this_name) +
'.' +
name;
1198 handle submodule = PyImport_AddModule(full_name.c_str());
1202 auto result = reinterpret_borrow<module_>(submodule);
1212 PyObject *obj = PyImport_ImportModule(
name);
1216 return reinterpret_steal<module_>(obj);
1221 PyObject *obj = PyImport_ReloadModule(
ptr());
1225 *
this = reinterpret_steal<module_>(obj);
1238 "Error during initialization: multiple incompatible definitions with name \""
1239 + std::string(
name) +
"\"");
1256 PyModuleDef{ PyModuleDef_HEAD_INIT,
1265 auto *
m = PyModule_Create(def);
1267 if (PyErr_Occurred()) {
1270 pybind11_fail(
"Internal error in module_::create_extension_module()");
1275 return reinterpret_borrow<module_>(
m);
1288 PyObject *
p = PyEval_GetGlobals();
1294 "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
1295 object make_simple_namespace(Args &&...args_) {
1296 return module_::import(
"types").attr(
"SimpleNamespace")(std::forward<Args>(args_)...);
1301 class generic_type : public
object {
1307 && rec.
scope.attr(
"__dict__").contains(rec.
name)) {
1309 +
"\": an object with that name is already defined");
1315 +
"\" is already registered!");
1321 auto *tinfo =
new detail::type_info();
1322 tinfo->type = (PyTypeObject *)
m_ptr;
1323 tinfo->cpptype = rec.
type;
1330 tinfo->simple_type =
true;
1331 tinfo->simple_ancestors =
true;
1336 auto tindex = std::type_index(*rec.
type);
1346 mark_parents_nonsimple(tinfo->type);
1347 tinfo->simple_ancestors =
false;
1348 }
else if (rec.
bases.size() == 1) {
1350 assert(parent_tinfo !=
nullptr);
1351 bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1352 tinfo->simple_ancestors = parent_simple_ancestors;
1354 parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1366 auto t = reinterpret_borrow<tuple>(
value->tp_bases);
1370 tinfo2->simple_type =
false;
1372 mark_parents_nonsimple((PyTypeObject *)
h.ptr());
1377 void *get_buffer_data) {
1378 auto *
type = (PyHeapTypeObject *)
m_ptr;
1381 if (!
type->ht_type.tp_as_buffer) {
1382 pybind11_fail(
"To be able to register buffer protocol support for the type '"
1384 +
"' the associated class<>(..) invocation must "
1385 "include the pybind11::buffer_protocol() annotation!");
1388 tinfo->get_buffer = get_buffer;
1389 tinfo->get_buffer_data = get_buffer_data;
1396 detail::function_record *rec_func) {
1397 const auto is_static = (rec_func !=
nullptr) && !(rec_func->is_method && rec_func->scope);
1398 const auto has_doc = (rec_func !=
nullptr) && (rec_func->doc !=
nullptr)
1399 && pybind11::options::show_user_defined_docstrings();
1401 (PyObject *) (is_static ?
get_internals().static_property_type : &PyProperty_Type));
1410 template <
typename T,
1419 template <
typename T,
typename SFINAE =
void>
1421 template <
typename T>
1423 : std::true_type {};
1424 template <
typename T,
typename SFINAE =
void>
1426 template <
typename T>
1434 T::operator
delete(
p);
1436 template <
typename T,
1440 T::operator
delete(
p,
s);
1446 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1447 if (
a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1448 # ifdef __cpp_sized_deallocation
1449 ::operator
delete(
p,
s, std::align_val_t(
a));
1451 ::operator
delete(
p, std::align_val_t(
a));
1456 #ifdef __cpp_sized_deallocation
1457 ::operator
delete(
p,
s);
1459 ::operator
delete(
p);
1464 cls.attr(cf.
name()) = cf;
1465 if (std::strcmp(name_,
"__eq__") == 0 && !cls.attr(
"__dict__").contains(
"__hash__")) {
1466 cls.attr(
"__hash__") =
none();
1472 template <
typename ,
typename F>
1476 return std::forward<F>(
f);
1479 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1483 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1487 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1488 auto method_adaptor(Return (Class::*pmf)(Args...)
const) -> Return (Derived::*)(Args...)
const {
1491 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1495 template <
typename type_,
typename...
options>
1497 template <
typename T>
1499 template <
typename T>
1501 template <
typename T>
1502 using is_base = detail::is_strict_base_of<T, type_>;
1504 template <
typename T>
1514 "Unknown/invalid class_ template parameters provided");
1517 "Cannot use an alias class with a non-polymorphic type");
1521 template <
typename... Extra>
1531 none_of<std::is_same<multiple_inheritance, Extra>...>::
value),
1532 "Error: multiple inheritance bases must be specified via class_ template options");
1545 set_operator_new<type>(&record);
1558 instances[std::type_index(
typeid(
type_alias))]
1559 = instances[std::type_index(
typeid(
type))];
1565 rec.add_base(
typeid(Base), [](
void *src) ->
void * {
1566 return static_cast<Base *
>(
reinterpret_cast<type *
>(src));
1573 template <
typename Func,
typename... Extra>
1574 class_ &
def(
const char *name_, Func &&
f,
const Extra &...extra) {
1575 cpp_function cf(method_adaptor<type>(std::forward<Func>(
f)),
1584 template <
typename Func,
typename... Extra>
1585 class_ &
def_static(
const char *name_, Func &&
f,
const Extra &...extra) {
1587 "def_static(...) called with a non-static member function pointer");
1593 auto cf_name = cf.
name();
1594 attr(std::move(cf_name)) =
staticmethod(std::move(cf));
1598 template <
typename T,
typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1599 class_ &
def(
const T &op,
const Extra &...extra) {
1600 op.execute(*
this, extra...);
1604 template <
typename T,
typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1606 op.execute_cast(*
this, extra...);
1610 template <
typename... Args,
typename... Extra>
1611 class_ &
def(
const detail::initimpl::constructor<Args...> &
init,
const Extra &...extra) {
1613 init.execute(*
this, extra...);
1617 template <
typename... Args,
typename... Extra>
1618 class_ &
def(
const detail::initimpl::alias_constructor<Args...> &
init,
const Extra &...extra) {
1620 init.execute(*
this, extra...);
1624 template <
typename... Args,
typename... Extra>
1625 class_ &
def(detail::initimpl::factory<Args...> &&
init,
const Extra &...extra) {
1626 std::move(
init).execute(*
this, extra...);
1630 template <
typename... Args,
typename... Extra>
1631 class_ &
def(detail::initimpl::pickle_factory<Args...> &&pf,
const Extra &...extra) {
1632 std::move(pf).execute(*
this, extra...);
1636 template <
typename Func>
1642 install_buffer_funcs(
1644 detail::make_caster<type> caster;
1645 if (!caster.load(obj,
false)) {
1659 template <
typename Return,
typename Class,
typename... Args>
1661 return def_buffer([
func](
type &obj) {
return (obj.*
func)(); });
1664 template <
typename Return,
typename Class,
typename... Args>
1666 return def_buffer([
func](
const type &obj) {
return (obj.*
func)(); });
1669 template <
typename C,
typename D,
typename... Extra>
1672 "def_readwrite() requires a class member (or base class member)");
1679 template <
typename C,
typename D,
typename... Extra>
1682 "def_readonly() requires a class member (or base class member)");
1688 template <
typename D,
typename... Extra>
1696 template <
typename D,
typename... Extra>
1704 template <
typename Getter,
typename... Extra>
1706 return def_property_readonly(
name,
1713 template <
typename... Extra>
1716 return def_property(
name, fget,
nullptr, extra...);
1720 template <
typename Getter,
typename... Extra>
1723 return def_property_readonly_static(
1728 template <
typename... Extra>
1731 const Extra &...extra) {
1732 return def_property_static(
name, fget,
nullptr, extra...);
1736 template <
typename Getter,
typename Setter,
typename... Extra>
1738 def_property(
const char *
name,
const Getter &fget,
const Setter &fset,
const Extra &...extra) {
1739 return def_property(
1742 template <
typename Getter,
typename... Extra>
1746 const Extra &...extra) {
1747 return def_property(
name,
1755 template <
typename... Extra>
1759 const Extra &...extra) {
1760 return def_property_static(
name, fget, fset,
is_method(*
this), extra...);
1764 template <
typename Getter,
typename... Extra>
1768 const Extra &...extra) {
1769 return def_property_static(
1774 template <
typename... Extra>
1778 const Extra &...extra) {
1780 "Argument annotations are not allowed for properties");
1781 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1782 auto *rec_active = rec_fget;
1784 char *doc_prev = rec_fget->doc;
1787 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1788 std::free(doc_prev);
1793 char *doc_prev = rec_fset->doc;
1795 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1796 std::free(doc_prev);
1800 rec_active = rec_fset;
1803 def_property_static_impl(
name, fget, fset, rec_active);
1809 template <
typename T>
1811 detail::value_and_holder &v_h,
1813 const std::enable_shared_from_this<T> * ) {
1815 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1819 v_h.set_holder_constructed();
1822 if (!v_h.holder_constructed() &&
inst->owned) {
1824 v_h.set_holder_constructed();
1845 detail::value_and_holder &v_h,
1849 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1850 v_h.set_holder_constructed();
1853 v_h.set_holder_constructed();
1863 if (!v_h.instance_registered()) {
1865 v_h.set_instance_registered();
1871 static void dealloc(detail::value_and_holder &v_h) {
1879 if (v_h.holder_constructed()) {
1881 v_h.set_holder_constructed(
false);
1884 v_h.value_ptr<
type>(), v_h.type->type_size, v_h.type->type_align);
1886 v_h.value_ptr() =
nullptr;
1895 handle func_self = PyCFunction_GET_SELF(
h.ptr());
1899 if (!isinstance<capsule>(func_self)) {
1902 auto cap = reinterpret_borrow<capsule>(func_self);
1906 return cap.get_pointer<detail::function_record>();
1911 template <
typename... Args>
1912 detail::initimpl::constructor<Args...>
init() {
1917 template <
typename... Args>
1923 template <
typename Func,
typename Ret = detail::initimpl::factory<Func>>
1925 return {std::forward<Func>(
f)};
1931 template <
typename CFunc,
typename AFunc,
typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1933 return {std::forward<CFunc>(
c), std::forward<AFunc>(
a)};
1938 template <
typename GetState,
typename SetState>
1939 detail::initimpl::pickle_factory<GetState, SetState>
pickle(GetState &&
g, SetState &&
s) {
1940 return {std::forward<GetState>(
g), std::forward<SetState>(
s)};
1946 dict entries =
arg.get_type().attr(
"__entries");
1947 for (
auto kv : entries) {
1959 m_base.attr(
"__entries") =
dict();
1960 auto property =
handle((PyObject *) &PyProperty_Type);
1964 [](
const object &
arg) ->
str {
1984 m_base.attr(
"__doc__") = static_property(
1987 std::string docstring;
1988 dict entries =
arg.attr(
"__entries");
1989 if (((PyTypeObject *)
arg.ptr())->tp_doc) {
1990 docstring += std::string(
1991 reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);
1992 docstring +=
"\n\n";
1994 docstring +=
"Members:";
1995 for (
auto kv : entries) {
1997 auto comment = kv.second[
int_(1)];
1998 docstring +=
"\n\n ";
2000 if (!comment.is_none()) {
2013 m_base.attr(
"__members__") = static_property(
cpp_function(
2015 dict entries =
arg.attr(
"__entries"),
2017 for (
auto kv : entries) {
2018 m[kv.first] = kv.second[
int_(0)];
2022 name(
"__members__")),
2027 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
2028 m_base.attr(op) = cpp_function( \
2029 [](const object &a, const object &b) { \
2030 if (!type::handle_of(a).is(type::handle_of(b))) \
2035 is_method(m_base), \
2038 #define PYBIND11_ENUM_OP_CONV(op, expr) \
2039 m_base.attr(op) = cpp_function( \
2040 [](const object &a_, const object &b_) { \
2041 int_ a(a_), b(b_); \
2045 is_method(m_base), \
2048 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
2049 m_base.attr(op) = cpp_function( \
2050 [](const object &a_, const object &b) { \
2055 is_method(m_base), \
2058 if (is_convertible) {
2062 if (is_arithmetic) {
2073 m_base.attr(
"__invert__")
2082 if (is_arithmetic) {
2083 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
2088 #undef PYBIND11_THROW
2092 #undef PYBIND11_ENUM_OP_CONV_LHS
2093 #undef PYBIND11_ENUM_OP_CONV
2094 #undef PYBIND11_ENUM_OP_STRICT
2104 dict entries = m_base.attr(
"__entries");
2107 std::string
type_name = (std::string)
str(m_base.attr(
"__name__"));
2108 throw value_error(std::move(
type_name) +
": element \"" + std::string(name_)
2109 +
"\" already exists!");
2113 m_base.attr(std::move(
name)) = std::move(
value);
2117 dict entries = m_base.attr(
"__entries");
2118 for (
auto kv : entries) {
2119 m_parent.attr(kv.first) = kv.second[
int_(0)];
2127 template <
bool is_
signed,
size_t length>
2162 template <
typename IntLike>
2168 template <
typename Type>
2175 using Base::def_property_readonly;
2176 using Base::def_property_readonly_static;
2179 using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2180 std::is_same<Underlying, bool>>
::value,
2181 detail::equivalent_integer_t<Underlying>,
2184 template <
typename... Extra>
2187 constexpr
bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>
::value;
2189 m_base.init(is_arithmetic, is_convertible);
2196 [](detail::value_and_holder &v_h,
Scalar arg) {
2197 detail::initimpl::setstate<Base>(
2198 v_h,
static_cast<Type>(
arg), Py_TYPE(v_h.inst) != v_h.type->type);
2200 detail::is_new_style_constructor(),
2225 if (!nurse || !patient) {
2229 if (patient.is_none() || nurse.is_none()) {
2234 if (!tinfo.empty()) {
2247 weakref wr(nurse, disable_lifesupport);
2250 (void) wr.release();
2256 auto get_arg = [&](
size_t n) {
2263 if (
n <= call.
args.size()) {
2264 return call.
args[
n - 1];
2276 #ifdef __cpp_lib_unordered_map_try_emplace
2279 .emplace(
type, std::vector<detail::type_info *>());
2289 for (
auto it = cache.begin(),
last = cache.end(); it !=
last;) {
2290 if (it->first ==
reinterpret_cast<PyObject *
>(
type)) {
2291 it = cache.erase(it);
2308 template <
typename Access,
2324 template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
2331 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).
first)>
2348 decltype(((*std::declval<Iterator &>()).
first)),
2349 decltype(std::declval<pair_type>().first)>;
2353 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
2361 decltype(((*std::declval<Iterator &>()).second)),
2362 decltype(std::declval<pair_type>().second)>;
2366 template <
typename Access,
2373 using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
2377 class_<state>(
handle(),
"iterator", pybind11::module_local())
2378 .def(
"__iter__", [](
state &
s) ->
state & {
return s; })
2381 [](
state &
s) -> ValueType {
2382 if (!
s.first_or_done) {
2385 s.first_or_done = false;
2387 if (
s.it ==
s.end) {
2388 s.first_or_done = true;
2389 throw stop_iteration();
2391 return Access()(
s.it);
2394 std::forward<Extra>(extra)...,
2407 typename ValueType =
typename detail::iterator_access<Iterator>::result_type,
2410 return detail::make_iterator_impl<detail::iterator_access<Iterator>,
2415 Extra...>(
first,
last, std::forward<Extra>(extra)...);
2423 typename KeyType =
typename detail::iterator_key_access<Iterator>::result_type,
2426 return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
2431 Extra...>(
first,
last, std::forward<Extra>(extra)...);
2439 typename ValueType =
typename detail::iterator_value_access<Iterator>::result_type,
2442 return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
2447 Extra...>(
first,
last, std::forward<Extra>(extra)...);
2456 return make_iterator<Policy>(
2466 return make_key_iterator<Policy>(
2476 return make_value_iterator<Policy>(
2480 template <
typename InputType,
typename OutputType>
2484 explicit set_flag(
bool &flag_) : flag(flag_) { flag_ =
true; }
2485 ~set_flag() { flag =
false; }
2487 auto implicit_caster = [](PyObject *obj, PyTypeObject *
type) -> PyObject * {
2488 static bool currently_used =
false;
2489 if (currently_used) {
2492 set_flag flag_helper(currently_used);
2493 if (!detail::make_caster<InputType>().load(obj,
false)) {
2506 tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
2508 pybind11_fail(
"implicitly_convertible: Unable to find type " + type_id<OutputType>());
2514 std::forward<ExceptionTranslator>(translator));
2525 std::forward<ExceptionTranslator>(translator));
2535 template <
typename type>
2538 exception() =
default;
2540 std::string full_name
2541 =
scope.attr(
"__name__").cast<std::string>() + std::string(
".") +
name;
2542 m_ptr = PyErr_NewException(
const_cast<char *
>(full_name.c_str()),
base.ptr(),
nullptr);
2544 pybind11_fail(
"Error during initialization: multiple incompatible "
2545 "definitions with name \""
2546 + std::string(
name) +
"\"");
2559 template <
typename CppException>
2561 static exception<CppException> ex;
2566 template <
typename CppException>
2567 exception<CppException> &
2569 auto &ex = detail::get_exception_object<CppException>();
2577 register_func([](std::exception_ptr
p) {
2582 std::rethrow_exception(
p);
2583 }
catch (
const CppException &
e) {
2584 detail::get_exception_object<CppException>()(
e.what());
2598 template <
typename CppException>
2599 exception<CppException> &
2601 return detail::register_exception_impl<CppException>(
scope,
name,
base,
false );
2612 template <
typename CppException>
2613 exception<CppException> &
2615 return detail::register_exception_impl<CppException>(
scope,
name,
base,
true );
2625 auto line =
sep.attr(
"join")(std::move(strings));
2643 write(std::move(line));
2647 file.attr(
"flush")();
2654 auto c = detail::collect_arguments<policy>(std::forward<Args>(
args)...);
2668 return m_fetched_error->error_string().c_str();
2685 if (cache.find(
key) != cache.end()) {
2689 function override =
getattr(
self,
name,
function());
2691 cache.insert(std::move(
key));
2697 #if !defined(PYPY_VERSION)
2698 # if PY_VERSION_HEX >= 0x03090000
2699 PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
2700 if (frame !=
nullptr) {
2701 PyCodeObject *f_code = PyFrame_GetCode(frame);
2703 if ((std::string)
str(f_code->co_name) ==
name && f_code->co_argcount > 0) {
2704 PyObject *locals = PyEval_GetLocals();
2705 if (locals !=
nullptr) {
2706 PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code,
"co_varnames");
2707 PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
2708 Py_DECREF(co_varnames);
2709 PyObject *self_caller =
dict_getitem(locals, self_arg);
2710 if (self_caller ==
self.
ptr()) {
2721 PyFrameObject *frame = PyThreadState_Get()->frame;
2722 if (frame !=
nullptr && (std::string)
str(frame->f_code->co_name) ==
name
2723 && frame->f_code->co_argcount > 0) {
2724 PyFrame_FastToLocals(frame);
2725 PyObject *self_caller
2726 =
dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2727 if (self_caller ==
self.
ptr()) {
2741 = PyRun_String(
"import inspect\n"
2742 "frame = inspect.currentframe()\n"
2743 "if frame is not None:\n"
2744 " frame = frame.f_back\n"
2745 " if frame is not None and str(frame.f_code.co_name) == name and "
2746 "frame.f_code.co_argcount > 0:\n"
2747 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2748 " if self_caller == self:\n"
2756 if (
d[
"self"].is_none())
2779 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
2781 pybind11::gil_scoped_acquire gil; \
2782 pybind11::function override \
2783 = pybind11::get_override(static_cast<const cname *>(this), name); \
2785 auto o = override(__VA_ARGS__); \
2786 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
2787 static pybind11::detail::override_caster_t<ret_type> caster; \
2788 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
2790 return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2812 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
2814 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2815 return cname::fn(__VA_ARGS__); \
2822 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
2824 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2825 pybind11::pybind11_fail( \
2826 "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
2854 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
2855 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2861 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
2862 PYBIND11_OVERRIDE_PURE_NAME( \
2863 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2878 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
2879 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
2880 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
2881 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
2882 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
2883 PYBIND11_OVERRIDE_PURE_NAME( \
2884 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
2885 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
2886 PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
2887 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2888 PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);