13#include "detail/class.h"
14#include "detail/init.h"
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
89 template <
typename Return,
typename... Args,
typename... Extra>
96 template <
typename Func,
98 typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
102 std::forward<Func>(f), (detail::function_signature_t<Func> *)
nullptr, extra...);
106 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
110 [f](Class *c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
111 (Return(*)(Class *, Arg...))
nullptr,
118 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
122 [f](Class *c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
123 (Return(*)(Class *, Arg...))
nullptr,
128 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
130 cpp_function(Return (Class::*f)(Arg...)
const,
const Extra &...extra) {
132 Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
133 (Return(*)(
const Class *, Arg...))
nullptr,
140 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
142 cpp_function(Return (Class::*f)(Arg...)
const &,
const Extra &...extra) {
144 Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
145 (Return(*)(
const Class *, Arg...))
nullptr,
150 object name()
const {
return attr(
"__name__"); }
153 struct InitializingFunctionRecordDeleter {
159 = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
167 template <
typename Func,
typename Return,
typename... Args,
typename... Extra>
168 void initialize(Func &&f, Return (*)(Args...),
const Extra &...extra) {
169 using namespace detail;
178 auto *rec = unique_rec.get();
181 if (
sizeof(capture) <=
sizeof(rec->data)) {
185 PYBIND11_WARNING_PUSH
187#if defined(__GNUG__) && __GNUC__ >= 6
191 new ((capture *) &rec->data) capture{std::forward<Func>(f)};
193#if !PYBIND11_HAS_STD_LAUNDER
199 if (!std::is_trivially_destructible<capture>::value) {
208 rec->data[0] =
new capture{std::forward<Func>(f)};
209 rec->free_data = [](
function_record *r) {
delete ((capture *) r->data[0]); };
219 sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
220 "The number of argument annotations does not match the number of function arguments");
224 cast_in args_converter;
227 if (!args_converter.load_args(call)) {
235 const auto *
data = (
sizeof(capture) <=
sizeof(call.func.data) ? &call.func.data
236 : call.func.data[0]);
237 auto *cap =
const_cast<capture *
>(
reinterpret_cast<const capture *
>(
data));
248 = cast_out::cast(std::move(args_converter).
template call<Return, Guard>(cap->f),
258 rec->nargs_pos = cast_in::args_pos >= 0
259 ?
static_cast<std::uint16_t
>(cast_in::args_pos)
260 :
sizeof...(Args) - cast_in::has_kwargs;
262 rec->has_args = cast_in::args_pos >= 0;
263 rec->has_kwargs = cast_in::has_kwargs;
272 static_assert(has_arg_annotations || !has_kw_only_args,
273 "py::kw_only requires the use of argument annotations");
274 static_assert(has_arg_annotations || !has_pos_only_args,
275 "py::pos_only requires the use of argument annotations (for docstrings "
276 "and aligning the annotations to the argument)");
279 "py::kw_only may be specified only once");
281 "py::pos_only may be specified only once");
284 static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
285 "py::pos_only must come before py::kw_only");
290 static constexpr auto signature
296 initialize_generic(std::move(unique_rec), signature.text, types.data(),
sizeof...(Args));
299 using FunctionType = Return (*)(Args...);
300 constexpr bool is_function_ptr
301 = std::is_convertible<Func, FunctionType>::value &&
sizeof(capture) ==
sizeof(
void *);
302 if (is_function_ptr) {
303 rec->is_stateless =
true;
305 =
const_cast<void *
>(
reinterpret_cast<const void *
>(&
typeid(FunctionType)));
337 const std::type_info *
const *types,
343 auto *rec = unique_rec.get();
354 rec->name = guarded_strdup(rec->name ? rec->name :
"");
356 rec->doc = guarded_strdup(rec->doc);
358 for (
auto &a : rec->args) {
360 a.name = guarded_strdup(a.name);
363 a.descr = guarded_strdup(a.descr);
364 }
else if (a.value) {
365 a.descr = guarded_strdup(
repr(a.value).
cast<std::string>().c_str());
369 rec->is_constructor = (std::strcmp(rec->name,
"__init__") == 0)
370 || (std::strcmp(rec->name,
"__setstate__") == 0);
372#if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
373 if (rec->is_constructor && !rec->is_new_style_constructor) {
374 const auto class_name
375 = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
376 const auto func_name = std::string(rec->name);
377 PyErr_WarnEx(PyExc_FutureWarning,
378 (
"pybind11-bound class '" + class_name
379 +
"' is using an old-style "
382 +
"' which has been deprecated. See "
383 "the upgrade guide in pybind11's docs. This message is only visible "
384 "when compiled in debug mode.")
391 std::string signature;
392 size_t type_index = 0, arg_index = 0;
393 bool is_starred =
false;
394 for (
const auto *pc = text; *pc !=
'\0'; ++pc) {
399 is_starred = *(pc + 1) ==
'*';
405 if (!rec->has_args && arg_index == rec->nargs_pos) {
408 if (arg_index < rec->
args.
size() && rec->args[arg_index].name) {
409 signature += rec->args[arg_index].name;
410 }
else if (arg_index == 0 && rec->is_method) {
413 signature +=
"arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
416 }
else if (c ==
'}') {
418 if (!is_starred && arg_index < rec->
args.
size() && rec->args[arg_index].descr) {
420 signature += rec->args[arg_index].descr;
424 if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
430 }
else if (c ==
'%') {
431 const std::type_info *t = types[type_index++];
433 pybind11_fail(
"Internal error while parsing type signature (1)");
435 if (
auto *tinfo = detail::get_type_info(*t)) {
436 handle th((PyObject *) tinfo->type);
437 signature += th.attr(
"__module__").
cast<std::string>() +
"."
438 + th.attr(
"__qualname__").
cast<std::string>();
439 }
else if (rec->is_new_style_constructor && arg_index == 0) {
442 signature += rec->scope.attr(
"__module__").cast<std::string>() +
"."
443 + rec->scope.attr(
"__qualname__").cast<std::string>();
445 std::string tname(t->name());
446 detail::clean_type_id(tname);
454 if (arg_index !=
args - rec->has_args - rec->has_kwargs || types[type_index] !=
nullptr) {
455 pybind11_fail(
"Internal error while parsing type signature (2)");
458 rec->signature = guarded_strdup(signature.c_str());
459 rec->args.shrink_to_fit();
460 rec->nargs = (std::uint16_t)
args;
466 detail::function_record *chain =
nullptr, *chain_start = rec;
468 if (PyCFunction_Check(rec->sibling.ptr())) {
469 auto *
self = PyCFunction_GET_SELF(rec->sibling.ptr());
470 if (!isinstance<capsule>(
self)) {
473 auto rec_capsule = reinterpret_borrow<capsule>(
self);
474 if (detail::is_function_record_capsule(rec_capsule)) {
475 chain = rec_capsule.get_pointer<detail::function_record>();
478 if (!chain->scope.is(rec->scope)) {
488 else if (!rec->sibling.is_none() && rec->name[0] !=
'_') {
489 pybind11_fail(
"Cannot overload existing non-function object \""
490 + std::string(rec->name) +
"\" with a function of the same name");
496 rec->def =
new PyMethodDef();
497 std::memset(rec->def, 0,
sizeof(PyMethodDef));
498 rec->def->ml_name = rec->name;
500 =
reinterpret_cast<PyCFunction
>(
reinterpret_cast<void (*)()
>(
dispatcher));
501 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
503 capsule rec_capsule(unique_rec.release(),
504 [](
void *
ptr) { destruct((detail::function_record *) ptr); });
505 rec_capsule.set_name(detail::get_function_record_capsule_name());
506 guarded_strdup.release();
510 if (
hasattr(rec->scope,
"__module__")) {
511 scope_module = rec->scope.attr(
"__module__");
512 }
else if (
hasattr(rec->scope,
"__name__")) {
513 scope_module = rec->scope.attr(
"__name__");
517 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.
ptr(), scope_module.
ptr());
519 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate function object");
523 m_ptr = rec->sibling.ptr();
525 if (chain->is_method != rec->is_method) {
527 "overloading a method with both static and instance methods is not supported; "
529 "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more "
532 "error while attempting to bind "
533 + std::string(rec->is_method ?
"instance" :
"static") +
" method "
534 + std::string(pybind11::str(rec->scope.attr(
"__name__"))) +
"."
535 + std::string(rec->name) + signature
547 = reinterpret_borrow<capsule>(((PyCFunctionObject *)
m_ptr)->m_self);
548 rec_capsule.set_pointer(unique_rec.release());
549 guarded_strdup.release();
553 while (chain->next) {
556 chain->next = unique_rec.release();
557 guarded_strdup.release();
561 std::string signatures;
567 signatures += rec->name;
568 signatures +=
"(*args, **kwargs)\n";
569 signatures +=
"Overloaded function.\n\n";
572 bool first_user_def =
true;
573 for (
auto *it = chain_start; it !=
nullptr; it = it->next) {
579 signatures += std::to_string(++index) +
". ";
581 signatures += rec->name;
582 signatures += it->signature;
589 if (first_user_def) {
590 first_user_def =
false;
598 signatures += it->doc;
606 auto *func = (PyCFunctionObject *)
m_ptr;
607 std::free(
const_cast<char *
>(func->m_ml->ml_doc));
612 if (rec->is_method) {
616 "cpp_function::cpp_function(): Could not allocate instance method object");
623 static void destruct(detail::function_record *rec,
bool free_strings =
true) {
626#if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
627 static bool is_zero = Py_GetVersion()[4] ==
'0';
631 detail::function_record *next = rec->next;
632 if (rec->free_data) {
639 std::free((
char *) rec->name);
640 std::free((
char *) rec->doc);
641 std::free((
char *) rec->signature);
642 for (
auto &
arg : rec->args) {
643 std::free(
const_cast<char *
>(
arg.
name));
644 std::free(
const_cast<char *
>(
arg.descr));
647 for (
auto &
arg : rec->args) {
651 std::free(
const_cast<char *
>(rec->def->ml_doc));
655#if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
669 static PyObject *
dispatcher(PyObject *
self, PyObject *args_in, PyObject *kwargs_in) {
670 using namespace detail;
671 assert(isinstance<capsule>(
self));
677 assert(overloads !=
nullptr);
681 const auto n_args_in = (
size_t) PyTuple_GET_SIZE(args_in);
683 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) :
nullptr,
689 || !PyObject_TypeCheck(parent.
ptr(), (PyTypeObject *) overloads->
scope.
ptr())) {
692 "__init__(self, ...) called with invalid or missing `self` argument");
697 auto *
const pi =
reinterpret_cast<instance *
>(parent.
ptr());
702 if (self_value_and_holder.instance_registered()) {
712 std::vector<function_call> second_pass;
715 const bool overloaded = it !=
nullptr && it->next !=
nullptr;
717 for (; it !=
nullptr; it = it->next) {
739 size_t num_args = func.nargs;
743 if (func.has_kwargs) {
746 size_t pos_args = func.nargs_pos;
748 if (!func.has_args && n_args_in > pos_args) {
752 if (n_args_in < pos_args && func.args.size() < pos_args) {
760 size_t args_to_copy = (std::min)(pos_args, n_args_in);
761 size_t args_copied = 0;
764 if (func.is_new_style_constructor) {
767 if (self_value_and_holder) {
768 self_value_and_holder.type->dealloc(self_value_and_holder);
771 call.
init_self = PyTuple_GET_ITEM(args_in, 0);
772 call.
args.emplace_back(
reinterpret_cast<PyObject *
>(&self_value_and_holder));
778 bool bad_arg =
false;
779 for (; args_copied < args_to_copy; ++args_copied) {
781 = args_copied < func.args.size() ? &func.args[args_copied] :
nullptr;
782 if (kwargs_in && arg_rec && arg_rec->
name
788 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
789 if (arg_rec && !arg_rec->
none &&
arg.is_none()) {
802 size_t positional_args_copied = args_copied;
805 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
808 if (args_copied < func.nargs_pos_only) {
809 for (; args_copied < func.nargs_pos_only; ++args_copied) {
810 const auto &arg_rec = func.args[args_copied];
814 value = arg_rec.value;
817 call.
args.push_back(value);
824 if (args_copied < func.nargs_pos_only) {
830 if (args_copied < num_args) {
831 bool copied_kwargs =
false;
833 for (; args_copied < num_args; ++args_copied) {
834 const auto &arg_rec = func.args[args_copied];
837 if (kwargs_in && arg_rec.name) {
843 if (!copied_kwargs) {
845 copied_kwargs =
true;
847 if (PyDict_DelItemString(
kwargs.
ptr(), arg_rec.name) == -1) {
850 }
else if (arg_rec.value) {
851 value = arg_rec.value;
854 if (!arg_rec.none && value.is_none()) {
861 if (func.has_args && call.
args.size() == func.nargs_pos) {
865 call.
args.push_back(value);
872 if (args_copied < num_args) {
886 if (args_to_copy == 0) {
889 extra_args = reinterpret_borrow<tuple>(args_in);
890 }
else if (positional_args_copied >= n_args_in) {
891 extra_args =
tuple(0);
893 size_t args_size = n_args_in - positional_args_copied;
894 extra_args =
tuple(args_size);
895 for (
size_t i = 0; i < args_size; ++i) {
896 extra_args[i] = PyTuple_GET_ITEM(args_in, positional_args_copied + i);
899 if (call.
args.size() <= func.nargs_pos) {
900 call.
args.push_back(extra_args);
902 call.
args[func.nargs_pos] = extra_args;
905 call.
args_ref = std::move(extra_args);
909 if (func.has_kwargs) {
920#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
921 if (call.
args.size() != func.nargs || call.
args_convert.size() != func.nargs) {
922 pybind11_fail(
"Internal error: function call dispatcher inserted wrong number "
927 std::vector<bool> second_pass_convert;
932 second_pass_convert.resize(func.nargs,
false);
939 result = func.impl(call);
940 }
catch (reference_cast_error &) {
952 for (
size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
953 if (second_pass_convert[i]) {
957 second_pass.push_back(std::move(call));
967 for (
auto &call : second_pass) {
970 result = call.func.impl(call);
971 }
catch (reference_cast_error &) {
989 }
catch (abi::__forced_unwind &) {
1009 auto &local_exception_translators
1011 if (detail::apply_exception_translators(local_exception_translators)) {
1015 if (detail::apply_exception_translators(exception_translators)) {
1019 PyErr_SetString(PyExc_SystemError,
1020 "Exception escaped from default exception translator!");
1024 auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
1025 if (msg.find(
"std::") != std::string::npos) {
1027 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1028 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1029 "conversions are optional and require extra headers to be included\n"
1030 "when compiling your pybind11 module.";
1036 return handle(Py_NotImplemented).inc_ref().ptr();
1039 std::string msg = std::string(overloads->
name) +
"(): incompatible "
1040 + std::string(overloads->
is_constructor ?
"constructor" :
"function")
1041 +
" arguments. The following argument types are supported:\n";
1045 msg +=
" " + std::to_string(++ctr) +
". ";
1047 bool wrote_sig =
false;
1051 std::string sig = it2->signature;
1052 size_t start = sig.find(
'(') + 7;
1053 if (start < sig.size()) {
1055 size_t end = sig.find(
", "), next = end + 2;
1056 size_t ret = sig.rfind(
" -> ");
1058 if (end >= sig.size()) {
1059 next = end = sig.find(
')');
1061 if (start < end && next < sig.size()) {
1062 msg.append(sig, start, end - start);
1064 msg.append(sig, next, ret - next);
1070 msg += it2->signature;
1075 msg +=
"\nInvoked with: ";
1076 auto args_ = reinterpret_borrow<tuple>(args_in);
1077 bool some_args =
false;
1078 for (
size_t ti = overloads->
is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
1085 msg += pybind11::repr(args_[ti]);
1087 msg +=
"<repr raised Error>";
1091 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
1098 for (
auto kwarg :
kwargs) {
1104 msg += pybind11::str(
"{}=").format(kwarg.first);
1106 msg += pybind11::repr(kwarg.second);
1108 msg +=
"<repr raised Error>";
1114 append_note_if_missing_header_is_suspected(msg);
1116 if (PyErr_Occurred()) {
1121 PyErr_SetString(PyExc_TypeError, msg.c_str());
1125 std::string msg =
"Unable to convert function return value to a "
1126 "Python type! The signature was\n\t";
1127 msg += it->signature;
1128 append_note_if_missing_header_is_suspected(msg);
1130 if (PyErr_Occurred()) {
1134 PyErr_SetString(PyExc_TypeError, msg.c_str());
1137 if (overloads->
is_constructor && !self_value_and_holder.holder_constructed()) {
1138 auto *pi =
reinterpret_cast<instance *
>(parent.
ptr());
1139 self_value_and_holder.type->init_instance(pi,
nullptr);
1141 return result.ptr();
1161 template <
typename Func,
typename... Extra>
1162 module_ &
def(
const char *name_, Func &&f,
const Extra &...extra) {
1186 const char *this_name = PyModule_GetName(
m_ptr);
1187 if (this_name ==
nullptr) {
1190 std::string full_name = std::string(this_name) +
'.' +
name;
1191 handle submodule = PyImport_AddModule(full_name.c_str());
1195 auto result = reinterpret_borrow<module_>(submodule);
1197 result.attr(
"__doc__") = pybind11::str(
doc);
1199 attr(
name) = result;
1205 PyObject *obj = PyImport_ImportModule(
name);
1209 return reinterpret_steal<module_>(obj);
1214 PyObject *obj = PyImport_ReloadModule(
ptr());
1218 *
this = reinterpret_steal<module_>(obj);
1231 "Error during initialization: multiple incompatible definitions with name \""
1232 + std::string(
name) +
"\"");
1249 PyModuleDef{ PyModuleDef_HEAD_INIT,
1258 auto *m = PyModule_Create(
def);
1260 if (PyErr_Occurred()) {
1263 pybind11_fail(
"Internal error in module_::create_extension_module()");
1268 return reinterpret_borrow<module_>(m);
1281 PyObject *p = PyEval_GetGlobals();
1282 return reinterpret_borrow<dict>(p ? p :
module_::import(
"__main__").attr(
"__dict__").ptr());
1287 "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
1288object make_simple_namespace(Args &&...args_) {
1289 return module_::import(
"types").attr(
"SimpleNamespace")(std::forward<Args>(args_)...);
1300 && rec.
scope.attr(
"__dict__").contains(rec.
name)) {
1302 +
"\": an object with that name is already defined");
1308 +
"\" is already registered!");
1314 auto *tinfo =
new detail::type_info();
1315 tinfo->type = (PyTypeObject *) m_ptr;
1316 tinfo->cpptype = rec.
type;
1323 tinfo->simple_type =
true;
1324 tinfo->simple_ancestors =
true;
1329 auto tindex = std::type_index(*rec.
type);
1339 mark_parents_nonsimple(tinfo->type);
1340 tinfo->simple_ancestors =
false;
1343 assert(parent_tinfo !=
nullptr);
1344 bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1345 tinfo->simple_ancestors = parent_simple_ancestors;
1347 parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1359 auto t = reinterpret_borrow<tuple>(value->tp_bases);
1363 tinfo2->simple_type =
false;
1365 mark_parents_nonsimple((PyTypeObject *) h.ptr());
1370 void *get_buffer_data) {
1371 auto *
type = (PyHeapTypeObject *) m_ptr;
1372 auto *tinfo = detail::get_type_info(&
type->ht_type);
1374 if (!
type->ht_type.tp_as_buffer) {
1375 pybind11_fail(
"To be able to register buffer protocol support for the type '"
1377 +
"' the associated class<>(..) invocation must "
1378 "include the pybind11::buffer_protocol() annotation!");
1381 tinfo->get_buffer = get_buffer;
1382 tinfo->get_buffer_data = get_buffer_data;
1389 detail::function_record *rec_func) {
1390 const auto is_static = (rec_func !=
nullptr) && !(rec_func->is_method && rec_func->scope);
1391 const auto has_doc = (rec_func !=
nullptr) && (rec_func->doc !=
nullptr)
1392 && pybind11::options::show_user_defined_docstrings();
1394 (PyObject *) (is_static ?
get_internals().static_property_type : &PyProperty_Type));
1398 pybind11::str(has_doc ? rec_func->doc :
""));
1403template <
typename T,
1412template <
typename T,
typename SFINAE =
void>
1414template <
typename T>
1416 : std::true_type {};
1417template <
typename T,
typename SFINAE =
void>
1419template <
typename T>
1425template <typename T, enable_if_t<has_operator_delete<T>::value,
int> = 0>
1427 T::operator
delete(p);
1429template <
typename T,
1433 T::operator
delete(p, s);
1439#if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1440 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1441# ifdef __cpp_sized_deallocation
1442 ::operator
delete(p, s, std::align_val_t(a));
1444 ::operator
delete(p, std::align_val_t(a));
1449#ifdef __cpp_sized_deallocation
1450 ::operator
delete(p, s);
1452 ::operator
delete(p);
1457 cls.attr(cf.
name()) = cf;
1458 if (std::strcmp(name_,
"__eq__") == 0 && !cls.attr(
"__dict__").contains(
"__hash__")) {
1459 cls.attr(
"__hash__") =
none();
1467template <
typename ,
typename F>
1469 return std::forward<F>(f);
1472template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1475 detail::is_accessible_base_of<Class, Derived>::value,
1476 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1480template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1481auto method_adaptor(Return (Class::*pmf)(Args...)
const) -> Return (Derived::*)(Args...)
const {
1483 detail::is_accessible_base_of<Class, Derived>::value,
1484 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1488template <
typename type_,
typename...
options>
1489class class_ :
public detail::generic_type {
1490 template <
typename T>
1492 template <
typename T>
1494 template <
typename T>
1495 using is_base = detail::is_strict_base_of<T, type_>;
1497 template <
typename T>
1503 constexpr static bool has_alias = !std::is_void<type_alias>::value;
1506 static_assert(detail::all_of<is_valid_class_option<options>...>::value,
1507 "Unknown/invalid class_ template parameters provided");
1509 static_assert(!
has_alias || std::is_polymorphic<type>::value,
1510 "Cannot use an alias class with a non-polymorphic type");
1514 template <
typename... Extra>
1516 using namespace detail;
1525 "Error: multiple inheritance bases must be specified via class_ template options");
1536 record.
default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
1538 set_operator_new<type>(&record);
1551 instances[std::type_index(
typeid(
type_alias))]
1552 = instances[std::type_index(
typeid(
type))];
1556 template <typename Base, detail::enable_if_t<is_base<Base>::value,
int> = 0>
1558 rec.add_base(
typeid(
Base), [](
void *src) ->
void * {
1559 return static_cast<Base *
>(
reinterpret_cast<type *
>(src));
1563 template <typename Base, detail::enable_if_t<!is_base<Base>::value,
int> = 0>
1566 template <
typename Func,
typename... Extra>
1567 class_ &
def(
const char *name_, Func &&f,
const Extra &...extra) {
1568 cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
1577 template <
typename Func,
typename... Extra>
1579 static_assert(!std::is_member_function_pointer<Func>::value,
1580 "def_static(...) called with a non-static member function pointer");
1586 auto cf_name = cf.
name();
1587 attr(std::move(cf_name)) =
staticmethod(std::move(cf));
1591 template <
typename T,
typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1593 op.execute(*
this, extra...);
1597 template <
typename T,
typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1599 op.execute_cast(*
this, extra...);
1603 template <
typename... Args,
typename... Extra>
1604 class_ &
def(
const detail::initimpl::constructor<Args...> &
init,
const Extra &...extra) {
1606 init.execute(*
this, extra...);
1610 template <
typename... Args,
typename... Extra>
1611 class_ &
def(
const detail::initimpl::alias_constructor<Args...> &
init,
const Extra &...extra) {
1613 init.execute(*
this, extra...);
1617 template <
typename... Args,
typename... Extra>
1619 std::move(
init).execute(*
this, extra...);
1623 template <
typename... Args,
typename... Extra>
1624 class_ &
def(detail::initimpl::pickle_factory<Args...> &&pf,
const Extra &...extra) {
1625 std::move(pf).execute(*
this, extra...);
1629 template <
typename Func>
1634 auto *ptr =
new capture{std::forward<Func>(func)};
1635 install_buffer_funcs(
1637 detail::make_caster<type> caster;
1638 if (!caster.load(obj,
false)) {
1641 return new buffer_info(((capture *) ptr)->func(std::move(caster)));
1652 template <
typename Return,
typename Class,
typename... Args>
1657 template <
typename Return,
typename Class,
typename... Args>
1659 return def_buffer([func](
const type &obj) {
return (obj.*func)(); });
1662 template <
typename C,
typename D,
typename... Extra>
1664 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
1665 "def_readwrite() requires a class member (or base class member)");
1667 fset([pm](
type &c,
const D &value) { c.*pm = value; },
is_method(*
this));
1668 def_property(
name, fget, fset, return_value_policy::reference_internal, extra...);
1672 template <
typename C,
typename D,
typename... Extra>
1674 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
1675 "def_readonly() requires a class member (or base class member)");
1681 template <
typename D,
typename... Extra>
1683 cpp_function fget([pm](
const object &) ->
const D & {
return *pm; },
scope(*
this)),
1684 fset([pm](
const object &,
const D &value) { *pm = value; },
scope(*
this));
1689 template <
typename D,
typename... Extra>
1691 cpp_function fget([pm](
const object &) ->
const D & {
return *pm; },
scope(*
this));
1697 template <
typename Getter,
typename... Extra>
1701 return_value_policy::reference_internal,
1706 template <
typename... Extra>
1713 template <
typename Getter,
typename... Extra>
1721 template <
typename... Extra>
1724 const Extra &...extra) {
1729 template <
typename Getter,
typename Setter,
typename... Extra>
1731 def_property(
const char *
name,
const Getter &fget,
const Setter &fset,
const Extra &...extra) {
1734 template <
typename Getter,
typename... Extra>
1738 const Extra &...extra) {
1742 return_value_policy::reference_internal,
1747 template <
typename... Extra>
1751 const Extra &...extra) {
1756 template <
typename Getter,
typename... Extra>
1760 const Extra &...extra) {
1766 template <
typename... Extra>
1770 const Extra &...extra) {
1771 static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
1772 "Argument annotations are not allowed for properties");
1774 auto *rec_active = rec_fget;
1776 char *doc_prev = rec_fget->doc;
1778 detail::process_attributes<Extra...>::init(extra..., rec_fget);
1779 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1780 std::free(doc_prev);
1785 char *doc_prev = rec_fset->doc;
1786 detail::process_attributes<Extra...>::init(extra..., rec_fset);
1787 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1788 std::free(doc_prev);
1792 rec_active = rec_fset;
1795 def_property_static_impl(
name, fget, fset, rec_active);
1801 template <
typename T>
1803 detail::value_and_holder &v_h,
1805 const std::enable_shared_from_this<T> * ) {
1807 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1808 detail::try_get_shared_from_this(v_h.value_ptr<
type>()));
1811 v_h.set_holder_constructed();
1814 if (!v_h.holder_constructed() && inst->owned) {
1816 v_h.set_holder_constructed();
1837 detail::value_and_holder &v_h,
1842 v_h.set_holder_constructed();
1843 }
else if (detail::always_construct_holder<holder_type>::value || inst->owned) {
1845 v_h.set_holder_constructed();
1854 auto v_h = inst->get_value_and_holder(detail::get_type_info(
typeid(
type)));
1855 if (!v_h.instance_registered()) {
1857 v_h.set_instance_registered();
1863 static void dealloc(detail::value_and_holder &v_h) {
1871 if (v_h.holder_constructed()) {
1873 v_h.set_holder_constructed(
false);
1875 detail::call_operator_delete(
1876 v_h.value_ptr<
type>(), v_h.type->type_size, v_h.type->type_align);
1878 v_h.value_ptr() =
nullptr;
1882 h = detail::get_function(h);
1887 handle func_self = PyCFunction_GET_SELF(h.
ptr());
1891 if (!isinstance<capsule>(func_self)) {
1894 auto cap = reinterpret_borrow<capsule>(func_self);
1895 if (!detail::is_function_record_capsule(cap)) {
1898 return cap.get_pointer<detail::function_record>();
1903template <
typename... Args>
1904detail::initimpl::constructor<Args...>
init() {
1909template <
typename... Args>
1915template <
typename Func,
typename Ret = detail::initimpl::factory<Func>>
1917 return {std::forward<Func>(f)};
1923template <
typename CFunc,
typename AFunc,
typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1925 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1930template <
typename GetState,
typename SetState>
1931detail::initimpl::pickle_factory<GetState, SetState>
pickle(GetState &&g, SetState &&s) {
1932 return {std::forward<GetState>(g), std::forward<SetState>(s)};
1938 dict entries =
arg.get_type().attr(
"__entries");
1939 for (
auto kv : entries) {
1941 return pybind11::str(kv.first);
1952 auto property =
handle((PyObject *) &PyProperty_Type);
1956 [](
const object &
arg) ->
str {
1958 object type_name =
type.attr(
"__name__");
1959 return pybind11::str(
"<{}.{}: {}>")
1970 return pybind11::str(
"{}.{}").format(std::move(type_name),
enum_name(
arg));
1976 m_base.attr(
"__doc__") = static_property(
1979 std::string docstring;
1980 dict entries =
arg.attr(
"__entries");
1981 if (((PyTypeObject *)
arg.ptr())->tp_doc) {
1982 docstring += std::string(
1983 reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);
1984 docstring +=
"\n\n";
1986 docstring +=
"Members:";
1987 for (
auto kv : entries) {
1988 auto key = std::string(pybind11::str(kv.first));
1989 auto comment = kv.second[
int_(1)];
1990 docstring +=
"\n\n ";
1992 if (!comment.is_none()) {
1994 docstring += pybind11::str(comment).cast<std::string>();
2007 dict entries =
arg.attr(
"__entries"),
2009 for (
auto kv : entries) {
2010 m[kv.first] = kv.second[
int_(0)];
2014 name(
"__members__")),
2019#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
2020 m_base.attr(op) = cpp_function( \
2021 [](const object &a, const object &b) { \
2022 if (!type::handle_of(a).is(type::handle_of(b))) \
2027 is_method(m_base), \
2030#define PYBIND11_ENUM_OP_CONV(op, expr) \
2031 m_base.attr(op) = cpp_function( \
2032 [](const object &a_, const object &b_) { \
2033 int_ a(a_), b(b_); \
2037 is_method(m_base), \
2040#define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
2041 m_base.attr(op) = cpp_function( \
2042 [](const object &a_, const object &b) { \
2047 is_method(m_base), \
2050 if (is_convertible) {
2054 if (is_arithmetic) {
2065 m_base.attr(
"__invert__")
2074 if (is_arithmetic) {
2075#define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
2080#undef PYBIND11_THROW
2084#undef PYBIND11_ENUM_OP_CONV_LHS
2085#undef PYBIND11_ENUM_OP_CONV
2086#undef PYBIND11_ENUM_OP_STRICT
2099 std::string type_name = (std::string)
str(
m_base.attr(
"__name__"));
2100 throw value_error(std::move(type_name) +
": element \"" + std::string(name_)
2101 +
"\" already exists!");
2110 for (
auto kv : entries) {
2119template <
bool is_
signed,
size_t length>
2154template <
typename IntLike>
2161template <
typename Type>
2171 using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2172 std::is_same<Underlying, bool>>
::value,
2173 detail::equivalent_integer_t<Underlying>,
2176 template <
typename... Extra>
2179 constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>
::value;
2180 constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
2181 m_base.init(is_arithmetic, is_convertible);
2188 [](detail::value_and_holder &v_h,
Scalar arg) {
2189 detail::initimpl::setstate<Base>(
2190 v_h,
static_cast<Type
>(
arg), Py_TYPE(v_h.inst) != v_h.type->type);
2192 detail::is_new_style_constructor(),
2193 pybind11::name(
"__setstate__"),
2211 detail::enum_base
m_base;
2217 if (!nurse || !patient) {
2221 if (patient.is_none() || nurse.is_none()) {
2226 if (!tinfo.empty()) {
2239 weakref wr(nurse, disable_lifesupport);
2242 (void) wr.release();
2248 auto get_arg = [&](
size_t n) {
2255 if (n <= call.
args.size()) {
2256 return call.
args[n - 1];
2268#ifdef __cpp_lib_unordered_map_try_emplace
2271 .emplace(
type, std::vector<detail::type_info *>());
2281 for (
auto it = cache.begin(),
last = cache.end(); it !=
last;) {
2282 if (it->first ==
reinterpret_cast<PyObject *
>(
type)) {
2283 it = cache.erase(it);
2300template <
typename Access,
2316template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
2323template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).
first)>
2340 decltype(((*std::declval<Iterator &>()).
first)),
2341 decltype(std::declval<pair_type>().first)>;
2345template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
2353 decltype(((*std::declval<Iterator &>()).second)),
2354 decltype(std::declval<pair_type>().second)>;
2358template <
typename Access,
2365 using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
2368 if (!detail::get_type_info(
typeid(state),
false)) {
2370 .
def(
"__iter__", [](state &s) -> state & {
return s; })
2373 [](state &s) -> ValueType {
2374 if (!s.first_or_done) {
2377 s.first_or_done = false;
2379 if (s.it == s.end) {
2380 s.first_or_done = true;
2381 throw stop_iteration();
2383 return Access()(s.it);
2386 std::forward<Extra>(extra)...,
2399 typename ValueType =
typename detail::iterator_access<Iterator>::result_type,
2402 return detail::make_iterator_impl<detail::iterator_access<Iterator>,
2407 Extra...>(
first,
last, std::forward<Extra>(extra)...);
2415 typename KeyType =
typename detail::iterator_key_access<Iterator>::result_type,
2418 return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
2423 Extra...>(
first,
last, std::forward<Extra>(extra)...);
2431 typename ValueType =
typename detail::iterator_value_access<Iterator>::result_type,
2434 return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
2439 Extra...>(
first,
last, std::forward<Extra>(extra)...);
2448 return make_iterator<Policy>(
2449 std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2458 return make_key_iterator<Policy>(
2459 std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2468 return make_value_iterator<Policy>(
2469 std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2472template <
typename InputType,
typename OutputType>
2476 explicit set_flag(
bool &flag_) : flag(flag_) { flag_ =
true; }
2477 ~set_flag() { flag =
false; }
2479 auto implicit_caster = [](PyObject *obj, PyTypeObject *
type) -> PyObject * {
2480 static bool currently_used =
false;
2481 if (currently_used) {
2484 set_flag flag_helper(currently_used);
2485 if (!detail::make_caster<InputType>().load(obj,
false)) {
2490 PyObject *result = PyObject_Call((PyObject *)
type,
args.
ptr(),
nullptr);
2491 if (result ==
nullptr) {
2497 if (
auto *tinfo = detail::get_type_info(
typeid(OutputType))) {
2498 tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
2500 pybind11_fail(
"implicitly_convertible: Unable to find type " + type_id<OutputType>());
2505 detail::get_internals().registered_exception_translators.push_front(
2506 std::forward<ExceptionTranslator>(translator));
2516 detail::get_local_internals().registered_exception_translators.push_front(
2517 std::forward<ExceptionTranslator>(translator));
2527template <
typename type>
2532 std::string full_name
2533 =
scope.attr(
"__name__").cast<std::string>() + std::string(
".") +
name;
2534 m_ptr = PyErr_NewException(
const_cast<char *
>(full_name.c_str()),
base.ptr(),
nullptr);
2536 pybind11_fail(
"Error during initialization: multiple incompatible "
2537 "definitions with name \""
2538 + std::string(
name) +
"\"");
2551template <
typename CppException>
2558template <
typename CppException>
2561 auto &ex = detail::get_exception_object<CppException>();
2569 register_func([](std::exception_ptr p) {
2574 std::rethrow_exception(p);
2575 }
catch (
const CppException &e) {
2576 detail::get_exception_object<CppException>()(e.what());
2590template <
typename CppException>
2593 return detail::register_exception_impl<CppException>(
scope,
name,
base,
false );
2604template <
typename CppException>
2607 return detail::register_exception_impl<CppException>(
scope,
name,
base,
true );
2613 for (
size_t i = 0; i <
args.
size(); ++i) {
2617 auto line = sep.attr(
"join")(std::move(strings));
2634 auto write = file.attr(
"write");
2635 write(std::move(line));
2639 file.attr(
"flush")();
2646 auto c = detail::collect_arguments<policy>(std::forward<Args>(
args)...);
2647 detail::print(c.args(), c.kwargs());
2677 if (cache.find(key) != cache.end()) {
2682 if (
override.is_cpp_function()) {
2683 cache.insert(std::move(key));
2689#if !defined(PYPY_VERSION)
2690# if PY_VERSION_HEX >= 0x03090000
2691 PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
2692 if (frame !=
nullptr) {
2693 PyCodeObject *f_code = PyFrame_GetCode(frame);
2695 if ((std::string)
str(f_code->co_name) ==
name && f_code->co_argcount > 0) {
2696 PyObject *locals = PyEval_GetLocals();
2697 if (locals !=
nullptr) {
2698 PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code,
"co_varnames");
2699 PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
2700 Py_DECREF(co_varnames);
2701 PyObject *self_caller =
dict_getitem(locals, self_arg);
2702 if (self_caller ==
self.ptr()) {
2713 PyFrameObject *frame = PyThreadState_Get()->frame;
2714 if (frame !=
nullptr && (std::string)
str(frame->f_code->co_name) ==
name
2715 && frame->f_code->co_argcount > 0) {
2716 PyFrame_FastToLocals(frame);
2717 PyObject *self_caller
2718 =
dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2719 if (self_caller ==
self.ptr()) {
2731 d[
"name"] = pybind11::str(
name);
2733 = PyRun_String(
"import inspect\n"
2734 "frame = inspect.currentframe()\n"
2735 "if frame is not None:\n"
2736 " frame = frame.f_back\n"
2737 " if frame is not None and str(frame.f_code.co_name) == name and "
2738 "frame.f_code.co_argcount > 0:\n"
2739 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2740 " if self_caller == self:\n"
2745 if (result ==
nullptr)
2748 if (d[
"self"].is_none())
2767 auto *tinfo = detail::get_type_info(
typeid(T));
2768 return tinfo ? detail::get_type_override(this_ptr, tinfo,
name) :
function();
2771#define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
2773 pybind11::gil_scoped_acquire gil; \
2774 pybind11::function override \
2775 = pybind11::get_override(static_cast<const cname *>(this), name); \
2777 auto o = override(__VA_ARGS__); \
2778 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
2779 static pybind11::detail::override_caster_t<ret_type> caster; \
2780 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
2782 return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2804#define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
2806 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2807 return cname::fn(__VA_ARGS__); \
2814#define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
2816 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2817 pybind11::pybind11_fail( \
2818 "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
2846#define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
2847 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2853#define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
2854 PYBIND11_OVERRIDE_PURE_NAME( \
2855 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2862 return detail::get_type_override(this_ptr, this_type,
name);
2870#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
2871 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
2872#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
2873 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
2874#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
2875 PYBIND11_OVERRIDE_PURE_NAME( \
2876 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
2877#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
2878 PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
2879#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2880 PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
Helper class which loads arguments for C++ functions called from Python.
class_ & def(detail::initimpl::pickle_factory< Args... > &&pf, const Extra &...extra)
class_ & def_property_readonly_static(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
static void init_holder(detail::instance *inst, detail::value_and_holder &v_h, const holder_type *, const std::enable_shared_from_this< T > *)
Initialize holder object, variant 1: object derives from enable_shared_from_this.
static void add_base(detail::type_record &rec)
class_ & def_static(const char *name_, Func &&f, const Extra &...extra)
detail::exactly_one_t< is_subtype, void, options... > type_alias
class_ & def_readonly_static(const char *name, const D *pm, const Extra &...extra)
detail::is_strict_base_of< T, type_ > is_base
static void init_instance(detail::instance *inst, const void *holder_ptr)
Performs instance initialization including constructing a holder and registering the known instance.
class_ & def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
detail::is_holder_type< type_, T > is_holder
static detail::function_record * get_function_record(handle h)
class_ & def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
Uses return_value_policy::reference by default.
class_ & def(detail::initimpl::factory< Args... > &&init, const Extra &...extra)
class_ & def(const char *name_, Func &&f, const Extra &...extra)
static void add_base(detail::type_record &)
class_ & def(const T &op, const Extra &...extra)
static constexpr bool has_alias
class_ & def_readwrite(const char *name, D C::*pm, const Extra &...extra)
class_ & def_buffer(Return(Class::*func)(Args...))
class_ & def_readonly(const char *name, const D C::*pm, const Extra &...extra)
class_ & def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
class_ & def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
static void dealloc(detail::value_and_holder &v_h)
Deallocates an instance; via holder, if constructed; otherwise via operator delete.
class_ & def_buffer(Return(Class::*func)(Args...) const)
class_ & def_readwrite_static(const char *name, D *pm, const Extra &...extra)
class_ & def_cast(const T &op, const Extra &...extra)
class_ & def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
class_(handle scope, const char *name, const Extra &...extra)
class_ & def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
class_ & def_property_readonly(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
class_ & def(const detail::initimpl::constructor< Args... > &init, const Extra &...extra)
class_ & def_buffer(Func &&func)
static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::true_type)
class_ & def(const detail::initimpl::alias_constructor< Args... > &init, const Extra &...extra)
detail::exactly_one_t< is_holder, std::unique_ptr< type >, options... > holder_type
class_ & def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference by default.
static void init_holder(detail::instance *inst, detail::value_and_holder &v_h, const holder_type *holder_ptr, const void *)
Initialize holder object, variant 2: try to construct from existing holder object,...
static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::false_type)
detail::is_strict_base_of< type_, T > is_subtype
strdup_guard(const strdup_guard &)=delete
char * operator()(const char *s)
std::vector< char * > strings
strdup_guard & operator=(const strdup_guard &)=delete
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
std::unique_ptr< detail::function_record, InitializingFunctionRecordDeleter > unique_function_record
static PyObject * dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in)
Main dispatch logic for calls to functions bound using pybind11.
cpp_function(Return(Class::*f)(Arg...) const, const Extra &...extra)
Construct a cpp_function from a class method (const, no ref-qualifier)
void initialize(Func &&f, Return(*)(Args...), const Extra &...extra)
Special internal constructor for functors, lambda functions, etc.
cpp_function(Return(Class::*f)(Arg...) const &, const Extra &...extra)
Construct a cpp_function from a class method (const, lvalue ref-qualifier) A copy of the overload for...
object name() const
Return the function name.
cpp_function(std::nullptr_t)
cpp_function(Return(Class::*f)(Arg...) &, const Extra &...extra)
Construct a cpp_function from a class method (non-const, lvalue ref-qualifier) A copy of the overload...
void initialize_generic(unique_function_record &&unique_rec, const char *text, const std::type_info *const *types, size_t args)
Register a function call with Python (generic non-templated code goes here)
PYBIND11_NOINLINE unique_function_record make_function_record()
Space optimization: don't inline this frequently instantiated fragment.
cpp_function(Func &&f, const Extra &...extra)
Construct a cpp_function from a lambda function (possibly with internal state)
cpp_function(Return(Class::*f)(Arg...), const Extra &...extra)
Construct a cpp_function from a class method (non-const, no ref-qualifier)
static void destruct(detail::function_record *rec, bool free_strings=true)
When a cpp_function is GCed, release any memory allocated by pybind11.
cpp_function(Return(*f)(Args...), const Extra &...extra)
Construct a cpp_function from a vanilla function pointer.
bool contains(T &&key) const
Binds C++ enumerations and enumeration classes to Python.
enum_ & value(char const *name, Type value, const char *doc=nullptr)
Add an enumeration entry.
detail::conditional_t< detail::any_of< detail::is_std_char_type< Underlying >, std::is_same< Underlying, bool > >::value, detail::equivalent_integer_t< Underlying >, Underlying > Scalar
typename std::underlying_type< Type >::type Underlying
enum_ & export_values()
Export enumeration entries into the parent scope.
enum_(const handle &scope, const char *name, const Extra &...extra)
Fetch and hold an error which was already set in Python.
void restore()
Give the currently-held error back to Python, if any.
static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr)
WARNING: This custom deleter needs to acquire the Python GIL.
std::shared_ptr< detail::error_fetch_and_normalize > m_fetched_error
const char * what() const noexcept override
The what() result is built lazily on demand.
Wrapper to generate a new Python exception type.
exception(handle scope, const char *name, handle base=PyExc_Exception)
void operator()(const char *message)
Generic support for creating new Python heap types.
void initialize(const type_record &rec)
void mark_parents_nonsimple(PyTypeObject *value)
Helper function which tags all parents of a type using mult. inheritance.
void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *), void *get_buffer_data)
void def_property_static_impl(const char *name, handle fget, handle fset, detail::function_record *rec_func)
\rst Holds a reference to a Python object (no reference counting)
const handle & inc_ref() const &
\rst Manually increase the reference count of the Python object.
const handle & dec_ref() const &
\rst Manually decrease the reference count of the Python object.
handle()=default
The default constructor creates a handle with a nullptr-valued pointer.
T cast() const
\rst Attempt to cast the Python object into the given C++ type.
PyObject * ptr() const
Return the underlying PyObject * pointer.
result_type operator()(Iterator &it) const
decltype(*std::declval< Iterator & >()) pair_type
conditional_t< std::is_reference< decltype(*std::declval< Iterator & >())>::value, decltype(((*std::declval< Iterator & >()).first)), decltype(std::declval< pair_type >().first)> result_type
result_type operator()(Iterator &it) const
decltype(*std::declval< Iterator & >()) pair_type
conditional_t< std::is_reference< decltype(*std::declval< Iterator & >())>::value, decltype(((*std::declval< Iterator & >()).second)), decltype(std::declval< pair_type >().second)> result_type
\rst Wraps a Python iterator so that it can also be used as a C++ input iterator
A life support system for temporary objects created by type_caster::load().
Wrapper for Python extension modules.
module_ def_submodule(const char *name, const char *doc=nullptr)
\rst Create and return a new Python submodule with the given name and docstring.
static module_ create_extension_module(const char *name, const char *doc, module_def *def)
\rst Create a new top-level module that can be used as the main module of a C extension.
static module_ import(const char *name)
Import and return a module or throws error_already_set.
PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite=false)
\rst Adds an object to the module using the given name.
void reload()
Reload the module or throws error_already_set.
module_ & def(const char *name_, Func &&f, const Extra &...extra)
\rst Create Python binding for a new function within the module scope.
\rst Holds a reference to a Python object (with reference counting)
handle release()
\rst Resets the internal pointer to nullptr without decreasing the object's reference count.
static bool show_enum_members_docstring()
static bool show_function_signatures()
static bool show_user_defined_docstrings()
static PYBIND11_NOINLINE void * local_load(PyObject *src, const type_info *ti)
static handle handle_of()
Convert C++ type to handle if previously registered.
dict globals()
Return a dictionary representing the global variables in the current execution frame,...
object getattr(handle obj, handle name)
void setattr(handle obj, handle name, handle value)
bool hasattr(handle obj, handle name)
constexpr bool args_are_all_keyword_or_ds()
PYBIND11_WARNING_PUSH PYBIND11_WARNING_POP
typename exactly_one_t< is_call_guard, call_guard<>, Extra... >::type extract_guard_t
Extract the type from the first call_guard in Extras... (or void_type if none found)
constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs)
Check the number of named arguments at compile time.
std::is_same< intrinsic_t< T >, pos_only > is_pos_only
T cast(const handle &handle)
std::is_same< intrinsic_t< T >, kw_only > is_kw_only
std::string get_fully_qualified_tp_name(PyTypeObject *type)
void register_instance(instance *self, void *valptr, const type_info *tinfo)
PyObject * make_new_python_type(const type_record &rec)
Create a brand new Python type according to the type_record specification.
void add_patient(PyObject *nurse, PyObject *patient)
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_)
Include Python header, disable linking to pythonX_d.lib on Windows in debug mode.
constexpr int last(int, int result)
static constexpr size_t size_in_ptrs(size_t s)
PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Thrown when pybind11::cast or.
#define PYBIND11_NOINLINE
typename std::remove_reference< T >::type remove_reference_t
constexpr int constexpr_first()
Return the index of the first type in Ts which satisfies Predicate<T>.
#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)
constexpr int first(int i)
Implementation details for constexpr functions.
constexpr size_t constexpr_sum()
Compile-time integer sum.
#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION
#define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
#define PYBIND11_NAMESPACE_END(name)
#define PYBIND11_TRY_NEXT_OVERLOAD
#define PYBIND11_NAMESPACE_BEGIN(name)
#define PYBIND11_INSTANCE_METHOD_CHECK
typename void_t_impl< Ts... >::type void_t
typename std::conditional< B, T, F >::type conditional_t
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
@ automatic_reference
As above, but use policy return_value_policy::reference when the return value is a pointer.
@ reference_internal
This policy only applies to methods and properties.
#define PYBIND11_DEPRECATED(reason)
constexpr descr< N - 1 > const_name(char const (&text)[N])
#define PYBIND11_DESCR_CONSTEXPR
#define PYBIND11_MODULE_LOCAL_ID
void(*)(std::exception_ptr) ExceptionTranslator
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
const char * c_str(Args &&...args)
Constructs a std::string with the given arguments, stores it in internals, and returns its c_str().
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
PYBIND11_NOINLINE detail::type_info * get_type_info(PyTypeObject *type)
Gets a single pybind11 type info for a python type.
const std::vector< detail::type_info * > & all_type_info(PyTypeObject *type)
Extracts vector of type_info pointers of pybind-registered roots of the given Python type.
detail::type_info * get_global_type_info(const std::type_index &tp)
PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type)
detail::type_info * get_local_type_info(const std::type_index &tp)
iterator make_value_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator over the values (.second) of a iterator over pairs from a first and past-the-...
typename equivalent_integer< std::is_signed< IntLike >::value, sizeof(IntLike)>::type equivalent_integer_t
auto method_adaptor(F &&f) -> decltype(std::forward< F >(f))
Given a pointer to a member function, cast it to its Derived version.
void implicitly_convertible()
exception< CppException > & get_exception_object()
bool apply_exception_translators(std::forward_list< ExceptionTranslator > &translators)
void register_local_exception_translator(ExceptionTranslator &&translator)
Add a new module-local exception translator.
detail::initimpl::alias_constructor< Args... > init_alias()
Like init<Args...>(), but the instance is always constructed through the alias class (even when not i...
iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra)
str enum_name(handle arg)
exception< CppException > & register_local_exception(handle scope, const char *name, handle base=PyExc_Exception)
Registers a Python exception in m of the given name and installs a translator to translate the C++ ex...
void call_operator_delete(T *p, size_t, size_t)
Call class-specific delete if it exists or global otherwise. Can also be an overload set.
PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient)
function get_overload(const T *this_ptr, const char *name)
exception< CppException > & register_exception_impl(handle scope, const char *name, handle base, bool isLocal)
function get_override(const T *this_ptr, const char *name)
\rst Try to retrieve a python method by the provided name from the instance pointed to by the this_pt...
exception< CppException > & register_exception(handle scope, const char *name, handle base=PyExc_Exception)
Registers a Python exception in m of the given name and installs a translator to translate the C++ ex...
function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name)
function get_type_override(const void *this_ptr, const type_info *this_type, const char *name)
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
detail::initimpl::pickle_factory< GetState, SetState > pickle(GetState &&g, SetState &&s)
Binds pickling functions __getstate__ and __setstate__ and ensures that the type returned by __getsta...
iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator over the keys (.first) of a iterator over pairs from a first and past-the-end...
void register_exception_translator(ExceptionTranslator &&translator)
void set_operator_new(type_record *r)
Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
iterator make_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator from a first and past-the-end C++ InputIterator.
std::pair< decltype(internals::registered_types_py)::iterator, bool > all_type_info_get_cache(PyTypeObject *type)
void add_class_method(object &cls, const char *name_, const cpp_function &cf)
PyObject * dict_getitemstring(PyObject *v, const char *key)
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
PyObject * dict_getitem(PyObject *v, PyObject *key)
#define PYBIND11_OBJECT(Name, Parent, CheckFun)
arr data(const arr &a, Ix... index)
#define PYBIND11_WARNING_DISABLE_GCC(name)
#define PYBIND11_DETAILED_ERROR_MESSAGES
#define PYBIND11_WARNING_DISABLE_MSVC(name)
const char * get_function_record_capsule_name()
#define PYBIND11_ENUM_OP_CONV_LHS(op, expr)
#define PYBIND11_COMPAT_STRDUP
str enum_name(handle arg)
#define PYBIND11_STD_LAUNDER
#define PYBIND11_ENUM_OP_CONV(op, expr)
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)
void add_class_method(object &cls, const char *name_, const cpp_function &cf)
void raise_from(PyObject *type, const char *message)
Replaces the current Python error indicator with the chosen error, performing a 'raise from' to indic...
Annotation for arguments.
const char * name
If non-null, this is a named kwargs argument.
Internal data structure which holds metadata about a keyword argument.
const char * name
Argument name.
bool none
True if None is allowed when loading.
bool convert
True if the argument is allowed to convert when loading.
Annotation indicating that a class derives from another given type.
Information record describing a Python buffer object.
void operator()(detail::function_record *rec)
Annotation for documentation.
PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible)
enum_base(const handle &base, const handle &parent)
PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc=nullptr)
PYBIND11_NOINLINE void export_values()
RAII wrapper that temporarily clears any Python error state.
Internal data associated with a single function call.
object args_ref
Extra references for the optional py::args and/or py::kwargs arguments (which, if present,...
std::vector< bool > args_convert
The convert value the arguments should be loaded with.
handle init_self
If this is a call to an initializer, this argument contains self
std::vector< handle > args
Arguments passed to the function:
Internal data structure which holds metadata about a bound function (signature, overloads,...
function_record * next
Pointer to next overload.
bool is_constructor
True if name == 'init'.
bool is_operator
True if this is an operator (add), etc.
char * name
Function name.
handle scope
Python handle to the parent scope (a class or a module)
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
value_and_holder get_value_and_holder(const type_info *find_type=nullptr, bool throw_if_missing=true)
Returns the value_and_holder wrapper for the given type (or the first, if find_type omitted).
Internal data structure used to track registered instances and types.
type_map< type_info * > registered_types_cpp
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
std::forward_list< ExceptionTranslator > registered_exception_translators
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
result_type operator()(Iterator &it) const
decltype(*std::declval< Iterator & >()) result_type
type_map< type_info * > registered_types_cpp
std::forward_list< ExceptionTranslator > registered_exception_translators
Annotation for function names.
static void precall(function_call &call)
static void init(const Args &...args, function_record *r)
static void postcall(function_call &call, handle fn_ret)
static return_value_policy policy(return_value_policy p)
Annotation for parent scope.
Annotation indicating that a function is an overload associated with a given "sibling".
Additional type information which does not fit into the PyTypeObject.
Special data structure which (temporarily) holds metadata about a bound class.
bool multiple_inheritance
Multiple inheritance marker.
bool default_holder
Is the default (unique_ptr) holder type used?
const char * name
Name of the class.
size_t holder_size
How large is the type's holder?
const std::type_info * type
bool module_local
Is the class definition local to the module shared object?
void(* init_instance)(instance *, const void *)
Function pointer to class_<..>::init_instance.
size_t type_size
How large is the underlying C++ type?
handle scope
Handle to the parent scope.
size_t type_align
What is the alignment of the underlying C++ type?
list bases
List of base classes of the newly created type.
void *(* operator_new)(size_t)
The global operator new can be overridden with a class-specific variant.
void(* dealloc)(detail::value_and_holder &)
Function pointer to class_<..>::dealloc.
Helper type to replace 'void' in some expressions.