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__)
45#if defined(__GNUC__) && __GNUC__ == 7
46# pragma GCC diagnostic push
47# pragma GCC diagnostic ignored "-Wnoexcept-type"
59 auto last_exception = std::current_exception();
61 for (
auto &translator : translators) {
63 translator(last_exception);
66 last_exception = std::current_exception();
73# define PYBIND11_COMPAT_STRDUP _strdup
75# define PYBIND11_COMPAT_STRDUP strdup
88 template <
typename Return,
typename... Args,
typename... Extra>
91 initialize(f, f, extra...);
95 template <
typename Func,
97 typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
101 std::forward<Func>(f), (detail::function_signature_t<Func> *)
nullptr, extra...);
105 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
109 [f](Class *c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
110 (Return(*)(Class *, Arg...))
nullptr,
117 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
121 [f](Class *c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
122 (Return(*)(Class *, Arg...))
nullptr,
127 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
129 cpp_function(Return (Class::*f)(Arg...)
const,
const Extra &...extra) {
130 initialize([f](
const Class *c,
131 Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
132 (Return(*)(
const Class *, Arg...))
nullptr,
139 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
141 cpp_function(Return (Class::*f)(Arg...)
const &,
const Extra &...extra) {
142 initialize([f](
const Class *c,
143 Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
144 (Return(*)(
const Class *, Arg...))
nullptr,
149 object name()
const {
return attr(
"__name__"); }
155 void operator()(detail::function_record *rec) { destruct(rec,
false); }
158 = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
166 template <
typename Func,
typename Return,
typename... Args,
typename... Extra>
167 void initialize(Func &&f, Return (*)(Args...),
const Extra &...extra) {
168 using namespace detail;
176 auto unique_rec = make_function_record();
177 auto *rec = unique_rec.get();
184#if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER)
185# pragma GCC diagnostic push
186# pragma GCC diagnostic ignored "-Wplacement-new"
188 new ((capture *) &rec->data) capture{std::forward<Func>(f)};
189#if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER)
190# pragma GCC diagnostic pop
192#if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER)
193# pragma GCC diagnostic push
194# pragma GCC diagnostic ignored "-Wstrict-aliasing"
198 if (!std::is_trivially_destructible<capture>::value) {
205#if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER)
206# pragma GCC diagnostic pop
209 rec->data[0] =
new capture{std::forward<Func>(f)};
210 rec->free_data = [](
function_record *r) {
delete ((capture *) r->data[0]); };
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]);
238 auto *cap =
const_cast<capture *
>(
reinterpret_cast<const capture *
>(
data));
249 = cast_out::cast(std::move(args_converter).
template call<Return, Guard>(cap->f),
259 rec->nargs_pos = cast_in::args_pos >= 0
260 ?
static_cast<std::uint16_t
>(cast_in::args_pos)
261 :
sizeof...(Args) - cast_in::has_kwargs;
263 rec->has_args = cast_in::args_pos >= 0;
264 rec->has_kwargs = cast_in::has_kwargs;
273 static_assert(has_arg_annotations || !has_kw_only_args,
274 "py::kw_only requires the use of argument annotations");
275 static_assert(has_arg_annotations || !has_pos_only_args,
276 "py::pos_only requires the use of argument annotations (for docstrings "
277 "and aligning the annotations to the argument)");
280 "py::kw_only may be specified only once");
282 "py::pos_only may be specified only once");
285 static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
286 "py::pos_only must come before py::kw_only");
291 static constexpr auto signature
297 initialize_generic(std::move(unique_rec), signature.text, types.data(),
sizeof...(Args));
300 using FunctionType = Return (*)(Args...);
301 constexpr bool is_function_ptr
302 = std::is_convertible<Func, FunctionType>::value &&
sizeof(capture) ==
sizeof(
void *);
303 if (is_function_ptr) {
304 rec->is_stateless =
true;
306 =
const_cast<void *
>(
reinterpret_cast<const void *
>(&
typeid(FunctionType)));
316 for (
auto *s : strings) {
322 strings.push_back(t);
334 const std::type_info *
const *types,
340 auto *rec = unique_rec.get();
351 rec->name = guarded_strdup(rec->name ? rec->name :
"");
353 rec->doc = guarded_strdup(rec->doc);
355 for (
auto &a : rec->args) {
357 a.name = guarded_strdup(a.name);
360 a.descr = guarded_strdup(a.descr);
361 }
else if (a.value) {
362 a.descr = guarded_strdup(
repr(a.value).
cast<std::string>().c_str());
366 rec->is_constructor = (std::strcmp(rec->name,
"__init__") == 0)
367 || (std::strcmp(rec->name,
"__setstate__") == 0);
369#if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
370 if (rec->is_constructor && !rec->is_new_style_constructor) {
371 const auto class_name
372 = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
373 const auto func_name = std::string(rec->name);
374 PyErr_WarnEx(PyExc_FutureWarning,
375 (
"pybind11-bound class '" + class_name
376 +
"' is using an old-style "
379 +
"' which has been deprecated. See "
380 "the upgrade guide in pybind11's docs. This message is only visible "
381 "when compiled in debug mode.")
388 std::string signature;
389 size_t type_index = 0, arg_index = 0;
390 bool is_starred =
false;
391 for (
const auto *pc = text; *pc !=
'\0'; ++pc) {
396 is_starred = *(pc + 1) ==
'*';
402 if (!rec->has_args && arg_index == rec->nargs_pos) {
405 if (arg_index < rec->
args.
size() && rec->args[arg_index].name) {
406 signature += rec->args[arg_index].name;
407 }
else if (arg_index == 0 && rec->is_method) {
410 signature +=
"arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
413 }
else if (c ==
'}') {
415 if (!is_starred && arg_index < rec->
args.
size() && rec->args[arg_index].descr) {
417 signature += rec->args[arg_index].descr;
421 if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
427 }
else if (c ==
'%') {
428 const std::type_info *t = types[type_index++];
430 pybind11_fail(
"Internal error while parsing type signature (1)");
432 if (
auto *tinfo = detail::get_type_info(*t)) {
433 handle th((PyObject *) tinfo->type);
434 signature += th.attr(
"__module__").
cast<std::string>() +
"." +
436 th.attr(
"__qualname__").
cast<std::string>();
437 }
else if (rec->is_new_style_constructor && arg_index == 0) {
440 signature += rec->scope.attr(
"__module__").cast<std::string>() +
"."
441 + rec->scope.attr(
"__qualname__").cast<std::string>();
443 std::string tname(t->name());
444 detail::clean_type_id(tname);
452 if (arg_index !=
args - rec->has_args - rec->has_kwargs || types[type_index] !=
nullptr) {
453 pybind11_fail(
"Internal error while parsing type signature (2)");
456#if PY_MAJOR_VERSION < 3
457 if (std::strcmp(rec->name,
"__next__") == 0) {
458 std::free(rec->name);
459 rec->name = guarded_strdup(
"next");
460 }
else if (std::strcmp(rec->name,
"__bool__") == 0) {
461 std::free(rec->name);
462 rec->name = guarded_strdup(
"__nonzero__");
465 rec->signature = guarded_strdup(signature.c_str());
466 rec->args.shrink_to_fit();
467 rec->nargs = (std::uint16_t)
args;
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 capsule rec_capsule = isinstance<capsule>(
self) ? reinterpret_borrow<capsule>(
self)
479 chain = (detail::function_record *) rec_capsule;
482 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); });
509 if (
hasattr(rec->scope,
"__module__")) {
510 scope_module = rec->scope.attr(
"__module__");
511 }
else if (
hasattr(rec->scope,
"__name__")) {
512 scope_module = rec->scope.attr(
"__name__");
516 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.
ptr(), scope_module.
ptr());
518 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate function object");
522 m_ptr = rec->sibling.ptr();
524 if (chain->is_method != rec->is_method) {
526 "overloading a method with both static and instance methods is not supported; "
528 "compile in debug mode for more details"
530 "error while attempting to bind "
531 + std::string(rec->is_method ?
"instance" :
"static") +
" method "
532 + std::string(pybind11::str(rec->scope.attr(
"__name__"))) +
"."
533 + std::string(rec->name) + signature
545 = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self);
546 rec_capsule.set_pointer(unique_rec.release());
551 while (chain->next) {
554 chain->next = unique_rec.release();
559 std::string signatures;
565 signatures += rec->name;
566 signatures +=
"(*args, **kwargs)\n";
567 signatures +=
"Overloaded function.\n\n";
570 bool first_user_def =
true;
571 for (
auto *it = chain_start; it !=
nullptr; it = it->next) {
577 signatures += std::to_string(++index) +
". ";
579 signatures += rec->name;
580 signatures += it->signature;
587 if (first_user_def) {
588 first_user_def =
false;
596 signatures += it->doc;
604 auto *func = (PyCFunctionObject *) m_ptr;
605 std::free(
const_cast<char *
>(func->m_ml->ml_doc));
610 if (rec->is_method) {
614 "cpp_function::cpp_function(): Could not allocate instance method object");
621 static void destruct(detail::function_record *rec,
bool free_strings =
true) {
624#if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
625 static bool is_zero = Py_GetVersion()[4] ==
'0';
629 detail::function_record *next = rec->next;
630 if (rec->free_data) {
637 std::free((
char *) rec->name);
638 std::free((
char *) rec->doc);
639 std::free((
char *) rec->signature);
640 for (
auto &
arg : rec->args) {
641 std::free(
const_cast<char *
>(
arg.
name));
642 std::free(
const_cast<char *
>(
arg.descr));
645 for (
auto &
arg : rec->args) {
649 std::free(
const_cast<char *
>(rec->def->ml_doc));
653#if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
667 static PyObject *
dispatcher(PyObject *
self, PyObject *args_in, PyObject *kwargs_in) {
668 using namespace detail;
676 const auto n_args_in = (
size_t) PyTuple_GET_SIZE(args_in);
678 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) :
nullptr,
684 || !PyObject_TypeCheck(parent.
ptr(), (PyTypeObject *) overloads->
scope.
ptr())) {
687 "__init__(self, ...) called with invalid or missing `self` argument");
692 auto *
const pi =
reinterpret_cast<instance *
>(parent.
ptr());
697 if (self_value_and_holder.instance_registered()) {
707 std::vector<function_call> second_pass;
710 const bool overloaded = it !=
nullptr && it->next !=
nullptr;
712 for (; it !=
nullptr; it = it->next) {
734 size_t num_args = func.nargs;
738 if (func.has_kwargs) {
741 size_t pos_args = func.nargs_pos;
743 if (!func.has_args && n_args_in > pos_args) {
747 if (n_args_in < pos_args && func.args.size() < pos_args) {
755 size_t args_to_copy = (std::min)(pos_args, n_args_in);
756 size_t args_copied = 0;
759 if (func.is_new_style_constructor) {
762 if (self_value_and_holder) {
763 self_value_and_holder.type->dealloc(self_value_and_holder);
766 call.
init_self = PyTuple_GET_ITEM(args_in, 0);
767 call.
args.emplace_back(
reinterpret_cast<PyObject *
>(&self_value_and_holder));
773 bool bad_arg =
false;
774 for (; args_copied < args_to_copy; ++args_copied) {
776 = args_copied < func.args.size() ? &func.args[args_copied] :
nullptr;
777 if (kwargs_in && arg_rec && arg_rec->
name
783 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
784 if (arg_rec && !arg_rec->
none &&
arg.is_none()) {
797 size_t positional_args_copied = args_copied;
800 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
803 if (args_copied < func.nargs_pos_only) {
804 for (; args_copied < func.nargs_pos_only; ++args_copied) {
805 const auto &arg_rec = func.args[args_copied];
809 value = arg_rec.value;
812 call.
args.push_back(value);
819 if (args_copied < func.nargs_pos_only) {
825 if (args_copied < num_args) {
826 bool copied_kwargs =
false;
828 for (; args_copied < num_args; ++args_copied) {
829 const auto &arg_rec = func.args[args_copied];
832 if (kwargs_in && arg_rec.name) {
838 if (!copied_kwargs) {
840 copied_kwargs =
true;
842 if (PyDict_DelItemString(
kwargs.
ptr(), arg_rec.name) == -1) {
845 }
else if (arg_rec.value) {
846 value = arg_rec.value;
849 if (!arg_rec.none && value.is_none()) {
856 if (func.has_args && call.
args.size() == func.nargs_pos) {
860 call.
args.push_back(value);
867 if (args_copied < num_args) {
881 if (args_to_copy == 0) {
884 extra_args = reinterpret_borrow<tuple>(args_in);
885 }
else if (positional_args_copied >= n_args_in) {
886 extra_args =
tuple(0);
888 size_t args_size = n_args_in - positional_args_copied;
889 extra_args =
tuple(args_size);
890 for (
size_t i = 0; i < args_size; ++i) {
891 extra_args[i] = PyTuple_GET_ITEM(args_in, positional_args_copied + i);
894 if (call.
args.size() <= func.nargs_pos) {
895 call.
args.push_back(extra_args);
897 call.
args[func.nargs_pos] = extra_args;
900 call.
args_ref = std::move(extra_args);
904 if (func.has_kwargs) {
916 if (call.
args.size() != func.nargs || call.
args_convert.size() != func.nargs) {
917 pybind11_fail(
"Internal error: function call dispatcher inserted wrong number "
922 std::vector<bool> second_pass_convert;
927 second_pass_convert.resize(func.nargs,
false);
934 result = func.impl(call);
935 }
catch (reference_cast_error &) {
947 for (
size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
948 if (second_pass_convert[i]) {
952 second_pass.push_back(std::move(call));
962 for (
auto &call : second_pass) {
965 result = call.func.impl(call);
966 }
catch (reference_cast_error &) {
984 }
catch (abi::__forced_unwind &) {
1004 auto &local_exception_translators
1006 if (detail::apply_exception_translators(local_exception_translators)) {
1010 if (detail::apply_exception_translators(exception_translators)) {
1014 PyErr_SetString(PyExc_SystemError,
1015 "Exception escaped from default exception translator!");
1019 auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
1020 if (msg.find(
"std::") != std::string::npos) {
1022 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1023 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1024 "conversions are optional and require extra headers to be included\n"
1025 "when compiling your pybind11 module.";
1034 std::string msg = std::string(overloads->
name) +
"(): incompatible "
1035 + std::string(overloads->
is_constructor ?
"constructor" :
"function")
1036 +
" arguments. The following argument types are supported:\n";
1040 msg +=
" " + std::to_string(++ctr) +
". ";
1042 bool wrote_sig =
false;
1046 std::string sig = it2->signature;
1047 size_t start = sig.find(
'(') + 7;
1048 if (start < sig.size()) {
1050 size_t end = sig.find(
", "), next = end + 2;
1051 size_t ret = sig.rfind(
" -> ");
1053 if (end >= sig.size()) {
1054 next = end = sig.find(
')');
1056 if (start < end && next < sig.size()) {
1057 msg.append(sig, start, end - start);
1059 msg.append(sig, next, ret - next);
1065 msg += it2->signature;
1070 msg +=
"\nInvoked with: ";
1071 auto args_ = reinterpret_borrow<tuple>(args_in);
1072 bool some_args =
false;
1073 for (
size_t ti = overloads->
is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
1080 msg += pybind11::repr(args_[ti]);
1082 msg +=
"<repr raised Error>";
1086 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
1093 for (
auto kwarg :
kwargs) {
1099 msg += pybind11::str(
"{}=").format(kwarg.first);
1101 msg += pybind11::repr(kwarg.second);
1103 msg +=
"<repr raised Error>";
1109 append_note_if_missing_header_is_suspected(msg);
1110#if PY_VERSION_HEX >= 0x03030000
1112 if (PyErr_Occurred()) {
1118 PyErr_SetString(PyExc_TypeError, msg.c_str());
1122 std::string msg =
"Unable to convert function return value to a "
1123 "Python type! The signature was\n\t";
1124 msg += it->signature;
1125 append_note_if_missing_header_is_suspected(msg);
1126#if PY_VERSION_HEX >= 0x03030000
1128 if (PyErr_Occurred()) {
1133 PyErr_SetString(PyExc_TypeError, msg.c_str());
1136 if (overloads->
is_constructor && !self_value_and_holder.holder_constructed()) {
1137 auto *pi =
reinterpret_cast<instance *
>(parent.
ptr());
1138 self_value_and_holder.type->init_instance(pi,
nullptr);
1140 return result.ptr();
1152#if PY_MAJOR_VERSION >= 3
1164 template <
typename Func,
typename... Extra>
1165 module_ &
def(
const char *name_, Func &&f,
const Extra &...extra) {
1189 std::string full_name
1190 = std::string(PyModule_GetName(
m_ptr)) + std::string(
".") + std::string(
name);
1191 auto result = reinterpret_borrow<module_>(PyImport_AddModule(full_name.c_str()));
1193 result.attr(
"__doc__") = pybind11::str(
doc);
1195 attr(
name) = result;
1201 PyObject *obj = PyImport_ImportModule(
name);
1205 return reinterpret_steal<module_>(obj);
1210 PyObject *obj = PyImport_ReloadModule(
ptr());
1214 *
this = reinterpret_steal<module_>(obj);
1227 "Error during initialization: multiple incompatible definitions with name \""
1228 + std::string(
name) +
"\"");
1234#if PY_MAJOR_VERSION >= 3
1235 using module_def = PyModuleDef;
1247#if PY_MAJOR_VERSION >= 3
1251 PyModuleDef{ PyModuleDef_HEAD_INIT,
1260 auto *m = PyModule_Create(
def);
1264 auto m = Py_InitModule3(
1268 if (PyErr_Occurred()) {
1271 pybind11_fail(
"Internal error in module_::create_extension_module()");
1276 return reinterpret_borrow<module_>(m);
1289 PyObject *p = PyEval_GetGlobals();
1290 return reinterpret_borrow<dict>(p ? p :
module_::import(
"__main__").attr(
"__dict__").ptr());
1293#if PY_VERSION_HEX >= 0x03030000
1296 "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
1297object make_simple_namespace(Args &&...args_) {
1298 return module_::import(
"types").attr(
"SimpleNamespace")(std::forward<Args>(args_)...);
1310 && rec.
scope.attr(
"__dict__").contains(rec.
name)) {
1312 +
"\": an object with that name is already defined");
1318 +
"\" is already registered!");
1324 auto *tinfo =
new detail::type_info();
1325 tinfo->type = (PyTypeObject *) m_ptr;
1326 tinfo->cpptype = rec.
type;
1333 tinfo->simple_type =
true;
1334 tinfo->simple_ancestors =
true;
1339 auto tindex = std::type_index(*rec.
type);
1349 mark_parents_nonsimple(tinfo->type);
1350 tinfo->simple_ancestors =
false;
1353 assert(parent_tinfo !=
nullptr);
1354 bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1355 tinfo->simple_ancestors = parent_simple_ancestors;
1357 parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1369 auto t = reinterpret_borrow<tuple>(value->tp_bases);
1373 tinfo2->simple_type =
false;
1375 mark_parents_nonsimple((PyTypeObject *) h.ptr());
1380 void *get_buffer_data) {
1381 auto *
type = (PyHeapTypeObject *) m_ptr;
1382 auto *tinfo = detail::get_type_info(&
type->ht_type);
1384 if (!
type->ht_type.tp_as_buffer) {
1385 pybind11_fail(
"To be able to register buffer protocol support for the type '"
1387 +
"' the associated class<>(..) invocation must "
1388 "include the pybind11::buffer_protocol() annotation!");
1391 tinfo->get_buffer = get_buffer;
1392 tinfo->get_buffer_data = get_buffer_data;
1399 detail::function_record *rec_func) {
1400 const auto is_static = (rec_func !=
nullptr) && !(rec_func->is_method && rec_func->scope);
1401 const auto has_doc = (rec_func !=
nullptr) && (rec_func->doc !=
nullptr)
1402 && pybind11::options::show_user_defined_docstrings();
1404 (PyObject *) (is_static ?
get_internals().static_property_type : &PyProperty_Type));
1408 pybind11::str(has_doc ? rec_func->doc :
""));
1413template <
typename T,
1422template <
typename T,
typename SFINAE =
void>
1424template <
typename T>
1426 : std::true_type {};
1427template <
typename T,
typename SFINAE =
void>
1429template <
typename T>
1435template <typename T, enable_if_t<has_operator_delete<T>::value,
int> = 0>
1437 T::operator
delete(p);
1443 T::operator
delete(p, s);
1449#if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1450 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1451# ifdef __cpp_sized_deallocation
1452 ::operator
delete(p, s, std::align_val_t(a));
1454 ::operator
delete(p, std::align_val_t(a));
1459#ifdef __cpp_sized_deallocation
1460 ::operator
delete(p, s);
1462 ::operator
delete(p);
1467 cls.attr(cf.
name()) = cf;
1468 if (std::strcmp(name_,
"__eq__") == 0 && !cls.attr(
"__dict__").contains(
"__hash__")) {
1469 cls.attr(
"__hash__") =
none();
1477template <
typename ,
typename F>
1479 return std::forward<F>(f);
1482template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1485 detail::is_accessible_base_of<Class, Derived>::value,
1486 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1490template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1491auto method_adaptor(Return (Class::*pmf)(Args...)
const) -> Return (Derived::*)(Args...)
const {
1493 detail::is_accessible_base_of<Class, Derived>::value,
1494 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1498template <
typename type_,
typename...
options>
1500 template <
typename T>
1502 template <
typename T>
1504 template <
typename T>
1505 using is_base = detail::is_strict_base_of<T, type_>;
1507 template <
typename T>
1513 constexpr static bool has_alias = !std::is_void<type_alias>::value;
1516 static_assert(detail::all_of<is_valid_class_option<options>...>::value,
1517 "Unknown/invalid class_ template parameters provided");
1519 static_assert(!
has_alias || std::is_polymorphic<type>::value,
1520 "Cannot use an alias class with a non-polymorphic type");
1524 template <
typename... Extra>
1526 using namespace detail;
1535 "Error: multiple inheritance bases must be specified via class_ template options");
1546 record.
default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
1548 set_operator_new<type>(&record);
1561 instances[std::type_index(
typeid(
type_alias))]
1562 = instances[std::type_index(
typeid(
type))];
1566 template <typename Base, detail::enable_if_t<is_base<Base>::value,
int> = 0>
1568 rec.add_base(
typeid(
Base), [](
void *src) ->
void * {
1569 return static_cast<Base *
>(
reinterpret_cast<type *
>(src));
1573 template <typename Base, detail::enable_if_t<!is_base<Base>::value,
int> = 0>
1576 template <
typename Func,
typename... Extra>
1577 class_ &
def(
const char *name_, Func &&f,
const Extra &...extra) {
1578 cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
1587 template <
typename Func,
typename... Extra>
1589 static_assert(!std::is_member_function_pointer<Func>::value,
1590 "def_static(...) called with a non-static member function pointer");
1600 template <detail::op_id id, detail::op_type ot,
typename L,
typename R,
typename... Extra>
1601 class_ &
def(
const detail::op_<id, ot, L, R> &op,
const Extra &...extra) {
1602 op.execute(*
this, extra...);
1606 template <detail::op_id id, detail::op_type ot,
typename L,
typename R,
typename... Extra>
1608 op.execute_cast(*
this, extra...);
1612 template <
typename... Args,
typename... Extra>
1613 class_ &
def(
const detail::initimpl::constructor<Args...> &
init,
const Extra &...extra) {
1615 init.execute(*
this, extra...);
1619 template <
typename... Args,
typename... Extra>
1620 class_ &
def(
const detail::initimpl::alias_constructor<Args...> &
init,
const Extra &...extra) {
1622 init.execute(*
this, extra...);
1626 template <
typename... Args,
typename... Extra>
1628 std::move(
init).execute(*
this, extra...);
1632 template <
typename... Args,
typename... Extra>
1633 class_ &
def(detail::initimpl::pickle_factory<Args...> &&pf,
const Extra &...extra) {
1634 std::move(pf).execute(*
this, extra...);
1638 template <
typename Func>
1643 auto *ptr =
new capture{std::forward<Func>(func)};
1644 install_buffer_funcs(
1646 detail::make_caster<type> caster;
1647 if (!caster.load(obj,
false)) {
1650 return new buffer_info(((capture *) ptr)->func(caster));
1661 template <
typename Return,
typename Class,
typename... Args>
1666 template <
typename Return,
typename Class,
typename... Args>
1668 return def_buffer([func](
const type &obj) {
return (obj.*func)(); });
1671 template <
typename C,
typename D,
typename... Extra>
1673 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
1674 "def_readwrite() requires a class member (or base class member)");
1676 fset([pm](
type &c,
const D &value) { c.*pm = value; },
is_method(*
this));
1677 def_property(
name, fget, fset, return_value_policy::reference_internal, extra...);
1681 template <
typename C,
typename D,
typename... Extra>
1683 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
1684 "def_readonly() requires a class member (or base class member)");
1690 template <
typename D,
typename... Extra>
1692 cpp_function fget([pm](
const object &) ->
const D & {
return *pm; },
scope(*
this)),
1693 fset([pm](
const object &,
const D &value) { *pm = value; },
scope(*
this));
1698 template <
typename D,
typename... Extra>
1700 cpp_function fget([pm](
const object &) ->
const D & {
return *pm; },
scope(*
this));
1706 template <
typename Getter,
typename... Extra>
1710 return_value_policy::reference_internal,
1715 template <
typename... Extra>
1722 template <
typename Getter,
typename... Extra>
1730 template <
typename... Extra>
1733 const Extra &...extra) {
1738 template <
typename Getter,
typename Setter,
typename... Extra>
1740 def_property(
const char *
name,
const Getter &fget,
const Setter &fset,
const Extra &...extra) {
1743 template <
typename Getter,
typename... Extra>
1747 const Extra &...extra) {
1751 return_value_policy::reference_internal,
1756 template <
typename... Extra>
1760 const Extra &...extra) {
1765 template <
typename Getter,
typename... Extra>
1769 const Extra &...extra) {
1775 template <
typename... Extra>
1779 const Extra &...extra) {
1780 static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
1781 "Argument annotations are not allowed for properties");
1783 auto *rec_active = rec_fget;
1785 char *doc_prev = rec_fget->doc;
1787 detail::process_attributes<Extra...>::init(extra..., rec_fget);
1788 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1789 std::free(doc_prev);
1794 char *doc_prev = rec_fset->doc;
1795 detail::process_attributes<Extra...>::init(extra..., rec_fset);
1796 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1797 std::free(doc_prev);
1801 rec_active = rec_fset;
1804 def_property_static_impl(
name, fget, fset, rec_active);
1810 template <
typename T>
1812 detail::value_and_holder &v_h,
1814 const std::enable_shared_from_this<T> * ) {
1816 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1817 detail::try_get_shared_from_this(v_h.value_ptr<
type>()));
1820 v_h.set_holder_constructed();
1823 if (!v_h.holder_constructed() && inst->owned) {
1825 v_h.set_holder_constructed();
1846 detail::value_and_holder &v_h,
1851 v_h.set_holder_constructed();
1852 }
else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
1854 v_h.set_holder_constructed();
1863 auto v_h = inst->get_value_and_holder(detail::get_type_info(
typeid(
type)));
1864 if (!v_h.instance_registered()) {
1866 v_h.set_instance_registered();
1872 static void dealloc(detail::value_and_holder &v_h) {
1880 if (v_h.holder_constructed()) {
1882 v_h.set_holder_constructed(
false);
1884 detail::call_operator_delete(
1885 v_h.value_ptr<
type>(), v_h.type->type_size, v_h.type->type_align);
1887 v_h.value_ptr() =
nullptr;
1891 h = detail::get_function(h);
1892 return h ? (detail::function_record *) reinterpret_borrow<capsule>(
1893 PyCFunction_GET_SELF(h.
ptr()))
1899template <
typename... Args>
1900detail::initimpl::constructor<Args...>
init() {
1905template <
typename... Args>
1911template <
typename Func,
typename Ret = detail::initimpl::factory<Func>>
1913 return {std::forward<Func>(f)};
1919template <
typename CFunc,
typename AFunc,
typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1921 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1926template <
typename GetState,
typename SetState>
1927detail::initimpl::pickle_factory<GetState, SetState>
pickle(GetState &&g, SetState &&s) {
1928 return {std::forward<GetState>(g), std::forward<SetState>(s)};
1934 dict entries =
arg.get_type().attr(
"__entries");
1935 for (
auto kv : entries) {
1937 return pybind11::str(kv.first);
1948 auto property =
handle((PyObject *) &PyProperty_Type);
1952 [](
const object &
arg) ->
str {
1954 object type_name =
type.attr(
"__name__");
1965 return pybind11::str(
"{}.{}").format(type_name,
enum_name(
arg));
1970 m_base.attr(
"__doc__") = static_property(
1973 std::string docstring;
1974 dict entries =
arg.attr(
"__entries");
1975 if (((PyTypeObject *)
arg.ptr())->tp_doc) {
1976 docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) +
"\n\n";
1978 docstring +=
"Members:";
1979 for (
auto kv : entries) {
1980 auto key = std::string(pybind11::str(kv.first));
1981 auto comment = kv.second[
int_(1)];
1982 docstring +=
"\n\n " + key;
1983 if (!comment.is_none()) {
1984 docstring +=
" : " + (std::string) pybind11::str(comment);
1996 dict entries =
arg.attr(
"__entries"),
1998 for (
auto kv : entries) {
1999 m[kv.first] = kv.second[
int_(0)];
2003 name(
"__members__")),
2008#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
2009 m_base.attr(op) = cpp_function( \
2010 [](const object &a, const object &b) { \
2011 if (!type::handle_of(a).is(type::handle_of(b))) \
2016 is_method(m_base), \
2019#define PYBIND11_ENUM_OP_CONV(op, expr) \
2020 m_base.attr(op) = cpp_function( \
2021 [](const object &a_, const object &b_) { \
2022 int_ a(a_), b(b_); \
2026 is_method(m_base), \
2029#define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
2030 m_base.attr(op) = cpp_function( \
2031 [](const object &a_, const object &b) { \
2036 is_method(m_base), \
2039 if (is_convertible) {
2043 if (is_arithmetic) {
2054 m_base.attr(
"__invert__")
2063 if (is_arithmetic) {
2064#define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
2069#undef PYBIND11_THROW
2073#undef PYBIND11_ENUM_OP_CONV_LHS
2074#undef PYBIND11_ENUM_OP_CONV
2075#undef PYBIND11_ENUM_OP_STRICT
2088 std::string type_name = (std::string)
str(
m_base.attr(
"__name__"));
2089 throw value_error(type_name +
": element \"" + std::string(name_)
2090 +
"\" already exists!");
2099 for (
auto kv : entries) {
2108template <
bool is_
signed,
size_t length>
2143template <
typename IntLike>
2150template <
typename Type>
2160 using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2161 std::is_same<Underlying, bool>>
::value,
2162 detail::equivalent_integer_t<Underlying>,
2165 template <
typename... Extra>
2168 constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>
::value;
2169 constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
2170 m_base.init(is_arithmetic, is_convertible);
2176#if PY_MAJOR_VERSION < 3
2180 [](detail::value_and_holder &v_h,
Scalar arg) {
2181 detail::initimpl::setstate<Base>(
2182 v_h,
static_cast<Type
>(
arg), Py_TYPE(v_h.inst) != v_h.type->type);
2184 detail::is_new_style_constructor(),
2185 pybind11::name(
"__setstate__"),
2209 if (!nurse || !patient) {
2213 if (patient.is_none() || nurse.is_none()) {
2218 if (!tinfo.empty()) {
2231 weakref wr(nurse, disable_lifesupport);
2234 (void) wr.release();
2240 auto get_arg = [&](
size_t n) {
2247 if (n <= call.
args.size()) {
2248 return call.
args[n - 1];
2260#ifdef __cpp_lib_unordered_map_try_emplace
2263 .emplace(
type, std::vector<detail::type_info *>());
2273 for (
auto it = cache.begin(),
last = cache.end(); it !=
last;) {
2274 if (it->first ==
reinterpret_cast<PyObject *
>(
type)) {
2275 it = cache.erase(it);
2292template <
typename Access,
2308template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
2315template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).
first)>
2332 decltype(((*std::declval<Iterator &>()).
first)),
2333 decltype(std::declval<pair_type>().first)>;
2337template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
2345 decltype(((*std::declval<Iterator &>()).second)),
2346 decltype(std::declval<pair_type>().second)>;
2350template <
typename Access,
2357 using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
2360 if (!detail::get_type_info(
typeid(state),
false)) {
2362 .
def(
"__iter__", [](state &s) -> state & {
return s; })
2365 [](state &s) -> ValueType {
2366 if (!s.first_or_done) {
2369 s.first_or_done = false;
2371 if (s.it == s.end) {
2372 s.first_or_done = true;
2373 throw stop_iteration();
2375 return Access()(s.it);
2378 std::forward<Extra>(extra)...,
2391 typename ValueType =
typename detail::iterator_access<Iterator>::result_type,
2394 return detail::make_iterator_impl<detail::iterator_access<Iterator>,
2399 Extra...>(
first,
last, std::forward<Extra>(extra)...);
2407 typename KeyType =
typename detail::iterator_key_access<Iterator>::result_type,
2410 return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
2415 Extra...>(
first,
last, std::forward<Extra>(extra)...);
2423 typename ValueType =
typename detail::iterator_value_access<Iterator>::result_type,
2426 return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
2431 Extra...>(
first,
last, std::forward<Extra>(extra)...);
2440 return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
2449 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
2458 return make_value_iterator<Policy>(std::begin(value), std::end(value), extra...);
2461template <
typename InputType,
typename OutputType>
2465 explicit set_flag(
bool &flag_) : flag(flag_) { flag_ =
true; }
2466 ~set_flag() { flag =
false; }
2468 auto implicit_caster = [](PyObject *obj, PyTypeObject *
type) -> PyObject * {
2469 static bool currently_used =
false;
2470 if (currently_used) {
2473 set_flag flag_helper(currently_used);
2474 if (!detail::make_caster<InputType>().load(obj,
false)) {
2479 PyObject *result = PyObject_Call((PyObject *)
type,
args.
ptr(),
nullptr);
2480 if (result ==
nullptr) {
2486 if (
auto *tinfo = detail::get_type_info(
typeid(OutputType))) {
2487 tinfo->implicit_conversions.push_back(implicit_caster);
2489 pybind11_fail(
"implicitly_convertible: Unable to find type " + type_id<OutputType>());
2494 detail::get_internals().registered_exception_translators.push_front(
2495 std::forward<ExceptionTranslator>(translator));
2505 detail::get_local_internals().registered_exception_translators.push_front(
2506 std::forward<ExceptionTranslator>(translator));
2516template <
typename type>
2521 std::string full_name
2522 =
scope.attr(
"__name__").cast<std::string>() + std::string(
".") +
name;
2523 m_ptr = PyErr_NewException(
const_cast<char *
>(full_name.c_str()),
base.ptr(), NULL);
2525 pybind11_fail(
"Error during initialization: multiple incompatible "
2526 "definitions with name \""
2527 + std::string(
name) +
"\"");
2540template <
typename CppException>
2547template <
typename CppException>
2550 auto &ex = detail::get_exception_object<CppException>();
2558 register_func([](std::exception_ptr p) {
2563 std::rethrow_exception(p);
2564 }
catch (
const CppException &e) {
2565 detail::get_exception_object<CppException>()(e.what());
2579template <
typename CppException>
2582 return detail::register_exception_impl<CppException>(
scope,
name,
base,
false );
2593template <
typename CppException>
2596 return detail::register_exception_impl<CppException>(
scope,
name,
base,
true );
2602 for (
size_t i = 0; i <
args.
size(); ++i) {
2606 auto line = sep.attr(
"join")(strings);
2623 auto write = file.attr(
"write");
2628 file.attr(
"flush")();
2635 auto c = detail::collect_arguments<policy>(std::forward<Args>(
args)...);
2636 detail::print(c.args(), c.kwargs());
2662 if (cache.find(key) != cache.end()) {
2667 if (
override.is_cpp_function()) {
2674#if !defined(PYPY_VERSION)
2675# if PY_VERSION_HEX >= 0x03090000
2676 PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
2677 if (frame !=
nullptr) {
2678 PyCodeObject *f_code = PyFrame_GetCode(frame);
2680 if ((std::string)
str(f_code->co_name) ==
name && f_code->co_argcount > 0) {
2681 PyObject *locals = PyEval_GetLocals();
2682 if (locals !=
nullptr) {
2683 PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code,
"co_varnames");
2684 PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
2685 Py_DECREF(co_varnames);
2686 PyObject *self_caller =
dict_getitem(locals, self_arg);
2687 if (self_caller ==
self.ptr()) {
2698 PyFrameObject *frame = PyThreadState_Get()->frame;
2699 if (frame !=
nullptr && (std::string)
str(frame->f_code->co_name) ==
name
2700 && frame->f_code->co_argcount > 0) {
2701 PyFrame_FastToLocals(frame);
2702 PyObject *self_caller
2703 =
dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2704 if (self_caller ==
self.ptr()) {
2716 d[
"name"] = pybind11::str(
name);
2718 = PyRun_String(
"import inspect\n"
2719 "frame = inspect.currentframe()\n"
2720 "if frame is not None:\n"
2721 " frame = frame.f_back\n"
2722 " if frame is not None and str(frame.f_code.co_name) == name and "
2723 "frame.f_code.co_argcount > 0:\n"
2724 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2725 " if self_caller == self:\n"
2730 if (result ==
nullptr)
2733 if (d[
"self"].is_none())
2752 auto *tinfo = detail::get_type_info(
typeid(T));
2753 return tinfo ? detail::get_type_override(this_ptr, tinfo,
name) :
function();
2756#define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
2758 pybind11::gil_scoped_acquire gil; \
2759 pybind11::function override \
2760 = pybind11::get_override(static_cast<const cname *>(this), name); \
2762 auto o = override(__VA_ARGS__); \
2763 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
2764 static pybind11::detail::override_caster_t<ret_type> caster; \
2765 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
2767 return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2789#define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
2791 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2792 return cname::fn(__VA_ARGS__); \
2799#define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
2801 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2802 pybind11::pybind11_fail( \
2803 "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
2831#define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
2832 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2838#define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
2839 PYBIND11_OVERRIDE_PURE_NAME( \
2840 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2847 return detail::get_type_override(this_ptr, this_type,
name);
2855#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
2856 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
2857#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
2858 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
2859#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
2860 PYBIND11_OVERRIDE_PURE_NAME( \
2861 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
2862#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
2863 PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
2864#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2865 PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
2869#if defined(__GNUC__) && __GNUC__ == 7
2870# pragma GCC diagnostic pop
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 &)
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)
class_ & def_cast(const detail::op_< id, ot, L, R > &op, 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_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::op_< id, ot, L, R > &op, const Extra &...extra)
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
char * operator()(const char *s)
std::vector< char * > strings
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.
~error_already_set() override
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.
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_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()
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)
#define PYBIND11_SILENCE_MSVC_C4127(...)
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()
#define PYBIND11_COMPAT_STRDUP
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...
#define PYBIND11_STD_LAUNDER
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_ENUM_OP_CONV_LHS(op, expr)
#define PYBIND11_COMPAT_STRDUP
str enum_name(handle arg)
#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.