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>
95 template <
typename Func,
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) {
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) {
143 Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
144 (Return(*)(
const Class *, Arg...))
nullptr,
149 object name()
const {
return attr(
"__name__"); }
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) {
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" 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" 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)};
219 expected_num_args<Extra...>(
220 sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
221 "The number of argument annotations does not match the number of function arguments");
225 cast_in args_converter;
228 if (!args_converter.load_args(call)) {
236 const auto *
data = (
sizeof(
capture) <=
sizeof(call.func.data) ? &call.func.data
237 : call.func.data[0]);
249 =
cast_out::cast(std::move(args_converter).
template call<Return, Guard>(cap->f),
259 rec->nargs_pos = cast_in::args_pos >= 0
261 :
sizeof...(Args) - cast_in::has_kwargs;
263 rec->has_args = cast_in::args_pos >= 0;
264 rec->has_kwargs = cast_in::has_kwargs;
270 constexpr
bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>
::value,
271 has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>
::value,
272 has_arg_annotations = any_of<is_keyword<Extra>...>
::value;
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
303 if (is_function_ptr) {
304 rec->is_stateless =
true;
306 =
const_cast<void *
>(
reinterpret_cast<const void *
>(&
typeid(FunctionType)));
320 for (
auto *
s : strings) {
326 strings.push_back(
t);
338 const std::type_info *
const *types,
344 auto *rec = unique_rec.get();
355 rec->name = guarded_strdup(rec->name ? rec->name :
"");
357 rec->doc = guarded_strdup(rec->doc);
359 for (
auto &
a : rec->args) {
361 a.name = guarded_strdup(
a.name);
364 a.descr = guarded_strdup(
a.descr);
365 }
else if (
a.value) {
366 a.descr = guarded_strdup(
repr(
a.value).
cast<std::string>().c_str());
370 rec->is_constructor = (std::strcmp(rec->name,
"__init__") == 0)
371 || (std::strcmp(rec->name,
"__setstate__") == 0);
373 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING) 374 if (rec->is_constructor && !rec->is_new_style_constructor) {
375 const auto class_name
377 const auto func_name = std::string(rec->name);
378 PyErr_WarnEx(PyExc_FutureWarning,
379 (
"pybind11-bound class '" + class_name
380 +
"' is using an old-style " 383 +
"' which has been deprecated. See " 384 "the upgrade guide in pybind11's docs. This message is only visible " 385 "when compiled in debug mode.")
392 std::string signature;
393 size_t type_index = 0, arg_index = 0;
394 bool is_starred =
false;
395 for (
const auto *
pc = text; *
pc !=
'\0'; ++
pc) {
400 is_starred = *(
pc + 1) ==
'*';
406 if (!rec->has_args && arg_index == rec->nargs_pos) {
409 if (arg_index < rec->args.size() && rec->args[arg_index].name) {
410 signature += rec->args[arg_index].name;
411 }
else if (arg_index == 0 && rec->is_method) {
414 signature +=
"arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
417 }
else if (
c ==
'}') {
419 if (!is_starred && arg_index < rec->args.size() && rec->args[arg_index].descr) {
421 signature += rec->args[arg_index].descr;
425 if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
431 }
else if (
c ==
'%') {
432 const std::type_info *
t = types[type_index++];
434 pybind11_fail(
"Internal error while parsing type signature (1)");
437 handle th((PyObject *) tinfo->type);
438 signature += th.attr(
"__module__").
cast<std::string>() +
"." 439 + th.attr(
"__qualname__").
cast<std::string>();
440 }
else if (rec->is_new_style_constructor && arg_index == 0) {
443 signature += rec->scope.attr(
"__module__").cast<std::string>() +
"." 444 + rec->scope.attr(
"__qualname__").cast<std::string>();
446 std::string tname(t->name());
455 if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] !=
nullptr) {
456 pybind11_fail(
"Internal error while parsing type signature (2)");
459 rec->signature = guarded_strdup(signature.c_str());
460 rec->args.shrink_to_fit();
467 detail::function_record *chain =
nullptr, *chain_start = rec;
469 if (PyCFunction_Check(rec->sibling.ptr())) {
470 auto *
self = PyCFunction_GET_SELF(rec->sibling.ptr());
471 capsule rec_capsule = isinstance<capsule>(
self) ? reinterpret_borrow<capsule>(
self)
473 chain = (detail::function_record *) rec_capsule;
476 if (!chain->scope.is(rec->scope)) {
482 else if (!rec->sibling.is_none() && rec->name[0] !=
'_') {
483 pybind11_fail(
"Cannot overload existing non-function object \"" 484 + std::string(rec->name) +
"\" with a function of the same name");
490 rec->def =
new PyMethodDef();
491 std::memset(rec->def, 0,
sizeof(PyMethodDef));
492 rec->def->ml_name = rec->name;
494 =
reinterpret_cast<PyCFunction
>(
reinterpret_cast<void (*)()
>(
dispatcher));
495 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
497 capsule rec_capsule(unique_rec.release(),
503 if (
hasattr(rec->scope,
"__module__")) {
504 scope_module = rec->scope.attr(
"__module__");
505 }
else if (
hasattr(rec->scope,
"__name__")) {
506 scope_module = rec->scope.attr(
"__name__");
510 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
512 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate function object");
516 m_ptr = rec->sibling.ptr();
518 if (chain->is_method != rec->is_method) {
520 "overloading a method with both static and instance methods is not supported; " 522 "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more " 525 "error while attempting to bind " 526 + std::string(rec->is_method ?
"instance" :
"static") +
" method " 527 + std::string(
pybind11::str(rec->scope.attr(
"__name__"))) +
"." 528 + std::string(rec->name) + signature
540 = reinterpret_borrow<capsule>(((PyCFunctionObject *)
m_ptr)->m_self);
541 rec_capsule.set_pointer(unique_rec.release());
546 while (chain->next) {
549 chain->next = unique_rec.release();
554 std::string signatures;
560 signatures += rec->name;
561 signatures +=
"(*args, **kwargs)\n";
562 signatures +=
"Overloaded function.\n\n";
565 bool first_user_def =
true;
566 for (
auto *it = chain_start; it !=
nullptr; it = it->next) {
572 signatures += std::to_string(++index) +
". ";
574 signatures += rec->name;
575 signatures += it->signature;
582 if (first_user_def) {
583 first_user_def =
false;
591 signatures += it->doc;
599 auto *
func = (PyCFunctionObject *)
m_ptr;
600 std::free(const_cast<char *>(
func->m_ml->ml_doc));
605 if (rec->is_method) {
609 "cpp_function::cpp_function(): Could not allocate instance method object");
616 static void destruct(detail::function_record *rec,
bool free_strings =
true) {
619 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9 620 static bool is_zero = Py_GetVersion()[4] ==
'0';
624 detail::function_record *next = rec->next;
625 if (rec->free_data) {
632 std::free((
char *) rec->name);
633 std::free((
char *) rec->doc);
634 std::free((
char *) rec->signature);
635 for (
auto &
arg : rec->args) {
636 std::free(const_cast<char *>(
arg.
name));
637 std::free(const_cast<char *>(
arg.descr));
640 for (
auto &
arg : rec->args) {
644 std::free(const_cast<char *>(rec->def->ml_doc));
648 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9 662 static PyObject *
dispatcher(PyObject *
self, PyObject *args_in, PyObject *kwargs_in) {
671 const auto n_args_in = (
size_t) PyTuple_GET_SIZE(args_in);
673 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) :
nullptr,
679 || !PyObject_TypeCheck(parent.
ptr(), (PyTypeObject *) overloads->
scope.
ptr())) {
682 "__init__(self, ...) called with invalid or missing `self` argument");
687 auto *
const pi =
reinterpret_cast<instance *
>(parent.
ptr());
692 if (self_value_and_holder.instance_registered()) {
702 std::vector<function_call> second_pass;
705 const bool overloaded = it !=
nullptr && it->next !=
nullptr;
707 for (; it !=
nullptr; it = it->next) {
729 size_t num_args = func.
nargs;
738 if (!func.
has_args && n_args_in > pos_args) {
742 if (n_args_in < pos_args && func.
args.size() < pos_args) {
750 size_t args_to_copy = (
std::min)(pos_args, n_args_in);
751 size_t args_copied = 0;
757 if (self_value_and_holder) {
758 self_value_and_holder.type->dealloc(self_value_and_holder);
761 call.
init_self = PyTuple_GET_ITEM(args_in, 0);
762 call.
args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
768 bool bad_arg =
false;
769 for (; args_copied < args_to_copy; ++args_copied) {
771 = args_copied < func.
args.size() ? &func.
args[args_copied] :
nullptr;
772 if (kwargs_in && arg_rec && arg_rec->
name 778 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
779 if (arg_rec && !arg_rec->
none && arg.is_none()) {
783 call.
args.push_back(arg);
792 size_t positional_args_copied = args_copied;
795 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
800 const auto &arg_rec = func.
args[args_copied];
804 value = arg_rec.value;
807 call.
args.push_back(value);
820 if (args_copied < num_args) {
821 bool copied_kwargs =
false;
823 for (; args_copied < num_args; ++args_copied) {
824 const auto &arg_rec = func.
args[args_copied];
827 if (kwargs_in && arg_rec.name) {
833 if (!copied_kwargs) {
834 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.
ptr()));
835 copied_kwargs =
true;
837 if (PyDict_DelItemString(kwargs.
ptr(), arg_rec.name) == -1) {
840 }
else if (arg_rec.value) {
841 value = arg_rec.value;
844 if (!arg_rec.none && value.is_none()) {
855 call.
args.push_back(value);
862 if (args_copied < num_args) {
876 if (args_to_copy == 0) {
879 extra_args = reinterpret_borrow<tuple>(args_in);
880 }
else if (positional_args_copied >= n_args_in) {
881 extra_args =
tuple(0);
883 size_t args_size = n_args_in - positional_args_copied;
884 extra_args =
tuple(args_size);
885 for (
size_t i = 0;
i < args_size; ++
i) {
886 extra_args[
i] = PyTuple_GET_ITEM(args_in, positional_args_copied +
i);
890 call.
args.push_back(extra_args);
895 call.
args_ref = std::move(extra_args);
903 call.
args.push_back(kwargs);
910 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) 912 pybind11_fail(
"Internal error: function call dispatcher inserted wrong number " 917 std::vector<bool> second_pass_convert;
922 second_pass_convert.resize(func.
nargs,
false);
930 }
catch (reference_cast_error &) {
942 for (
size_t i = func.
is_method ? 1 : 0;
i < pos_args;
i++) {
943 if (second_pass_convert[
i]) {
947 second_pass.push_back(std::move(call));
957 for (
auto &call : second_pass) {
960 result = call.func.impl(call);
961 }
catch (reference_cast_error &) {
979 }
catch (abi::__forced_unwind &) {
999 auto &local_exception_translators
1009 PyErr_SetString(PyExc_SystemError,
1010 "Exception escaped from default exception translator!");
1014 auto append_note_if_missing_header_is_suspected = [](std::string &
msg) {
1015 if (
msg.find(
"std::") != std::string::npos) {
1017 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n" 1018 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n" 1019 "conversions are optional and require extra headers to be included\n" 1020 "when compiling your pybind11 module.";
1026 return handle(Py_NotImplemented).inc_ref().ptr();
1029 std::string
msg = std::string(overloads->
name) +
"(): incompatible " 1030 + std::string(overloads->
is_constructor ?
"constructor" :
"function")
1031 +
" arguments. The following argument types are supported:\n";
1035 msg +=
" " + std::to_string(++ctr) +
". ";
1037 bool wrote_sig =
false;
1041 std::string sig = it2->signature;
1042 size_t start = sig.find(
'(') + 7;
1043 if (start < sig.size()) {
1045 size_t end = sig.find(
", "), next = end + 2;
1046 size_t ret = sig.rfind(
" -> ");
1048 if (end >= sig.size()) {
1049 next = end = sig.find(
')');
1051 if (start < end && next < sig.size()) {
1052 msg.append(sig, start, end - start);
1054 msg.append(sig, next, ret - next);
1060 msg += it2->signature;
1065 msg +=
"\nInvoked with: ";
1066 auto args_ = reinterpret_borrow<tuple>(args_in);
1067 bool some_args =
false;
1068 for (
size_t ti = overloads->
is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
1077 msg +=
"<repr raised Error>";
1081 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
1088 for (
auto kwarg :
kwargs) {
1098 msg +=
"<repr raised Error>";
1104 append_note_if_missing_header_is_suspected(msg);
1106 if (PyErr_Occurred()) {
1111 PyErr_SetString(PyExc_TypeError, msg.c_str());
1115 std::string
msg =
"Unable to convert function return value to a " 1116 "Python type! The signature was\n\t";
1117 msg += it->signature;
1118 append_note_if_missing_header_is_suspected(msg);
1120 if (PyErr_Occurred()) {
1124 PyErr_SetString(PyExc_TypeError, msg.c_str());
1127 if (overloads->
is_constructor && !self_value_and_holder.holder_constructed()) {
1128 auto *pi =
reinterpret_cast<instance *
>(parent.
ptr());
1129 self_value_and_holder.type->init_instance(pi,
nullptr);
1143 *
this = create_extension_module(name,
doc,
new PyModuleDef());
1151 template <
typename Func,
typename... Extra>
1152 module_ &
def(
const char *name_, Func &&f,
const Extra &...extra) {
1161 add_object(name_, func,
true );
1176 const char *this_name = PyModule_GetName(
m_ptr);
1177 if (this_name ==
nullptr) {
1180 std::string full_name = std::string(this_name) +
'.' +
name;
1181 handle submodule = PyImport_AddModule(full_name.c_str());
1185 auto result = reinterpret_borrow<module_>(submodule);
1195 PyObject *obj = PyImport_ImportModule(
name);
1199 return reinterpret_steal<module_>(obj);
1204 PyObject *obj = PyImport_ReloadModule(
ptr());
1208 *
this = reinterpret_steal<module_>(obj);
1219 if (!overwrite &&
hasattr(*
this, name)) {
1221 "Error during initialization: multiple incompatible definitions with name \"" 1222 + std::string(name) +
"\"");
1239 PyModuleDef{ PyModuleDef_HEAD_INIT,
1248 auto *
m = PyModule_Create(def);
1250 if (PyErr_Occurred()) {
1253 pybind11_fail(
"Internal error in module_::create_extension_module()");
1258 return reinterpret_borrow<module_>(
m);
1271 PyObject *
p = PyEval_GetGlobals();
1272 return reinterpret_borrow<dict>(p ?
p :
module_::import(
"__main__").attr(
"__dict__").
ptr());
1277 "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
1278 object make_simple_namespace(Args &&...args_) {
1279 return module_::import(
"types").attr(
"SimpleNamespace")(std::forward<Args>(args_)...);
1284 class generic_type : public
object {
1290 && rec.
scope.attr(
"__dict__").contains(rec.
name)) {
1292 +
"\": an object with that name is already defined");
1298 +
"\" is already registered!");
1304 auto *tinfo =
new detail::type_info();
1305 tinfo->type = (PyTypeObject *)
m_ptr;
1306 tinfo->cpptype = rec.
type;
1313 tinfo->simple_type =
true;
1314 tinfo->simple_ancestors =
true;
1319 auto tindex = std::type_index(*rec.
type);
1329 mark_parents_nonsimple(tinfo->type);
1330 tinfo->simple_ancestors =
false;
1331 }
else if (rec.
bases.size() == 1) {
1333 assert(parent_tinfo !=
nullptr);
1334 bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1335 tinfo->simple_ancestors = parent_simple_ancestors;
1337 parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1349 auto t = reinterpret_borrow<tuple>(value->tp_bases);
1353 tinfo2->simple_type =
false;
1355 mark_parents_nonsimple((PyTypeObject *)
h.ptr());
1360 void *get_buffer_data) {
1361 auto *
type = (PyHeapTypeObject *)
m_ptr;
1364 if (!
type->ht_type.tp_as_buffer) {
1365 pybind11_fail(
"To be able to register buffer protocol support for the type '" 1367 +
"' the associated class<>(..) invocation must " 1368 "include the pybind11::buffer_protocol() annotation!");
1371 tinfo->get_buffer = get_buffer;
1372 tinfo->get_buffer_data = get_buffer_data;
1379 detail::function_record *rec_func) {
1380 const auto is_static = (rec_func !=
nullptr) && !(rec_func->is_method && rec_func->scope);
1381 const auto has_doc = (rec_func !=
nullptr) && (rec_func->doc !=
nullptr)
1382 && pybind11::options::show_user_defined_docstrings();
1384 (PyObject *) (is_static ?
get_internals().static_property_type : &PyProperty_Type));
1385 attr(name) = property(fget.
ptr() ? fget :
none(),
1393 template <
typename T,
1402 template <
typename T,
typename SFINAE =
void>
1404 template <
typename T>
1406 : std::true_type {};
1407 template <
typename T,
typename SFINAE =
void>
1409 template <
typename T>
1412 void_t<decltype(static_cast<void (*)(
void *,
size_t)>(T::operator
delete))>> : std::true_type {
1417 T::operator
delete(
p);
1423 T::operator
delete(
p,
s);
1429 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912) 1430 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1431 # ifdef __cpp_sized_deallocation 1432 ::operator
delete(
p,
s, std::align_val_t(a));
1434 ::operator
delete(
p, std::align_val_t(a));
1439 #ifdef __cpp_sized_deallocation 1440 ::operator
delete(
p,
s);
1442 ::operator
delete(
p);
1447 cls.attr(cf.
name()) = cf;
1448 if (std::strcmp(name_,
"__eq__") == 0 && !cls.attr(
"__dict__").contains(
"__hash__")) {
1449 cls.attr(
"__hash__") =
none();
1455 template <
typename ,
typename F>
1459 return std::forward<F>(
f);
1462 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1466 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1470 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1471 auto method_adaptor(Return (Class::*pmf)(Args...)
const) -> Return (Derived::*)(Args...)
const {
1474 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1478 template <
typename type_,
typename...
options>
1480 template <
typename T>
1482 template <
typename T>
1484 template <
typename T>
1485 using is_base = detail::is_strict_base_of<T, type_>;
1487 template <
typename T>
1497 "Unknown/invalid class_ template parameters provided");
1500 "Cannot use an alias class with a non-polymorphic type");
1504 template <
typename... Extra>
1514 none_of<std::is_same<multiple_inheritance, Extra>...>::
value),
1515 "Error: multiple inheritance bases must be specified via class_ template options");
1528 set_operator_new<type>(&record);
1541 instances[std::type_index(
typeid(
type_alias))]
1542 = instances[std::type_index(
typeid(
type))];
1548 rec.add_base(
typeid(Base), [](
void *src) ->
void * {
1549 return static_cast<Base *
>(
reinterpret_cast<type *
>(src));
1556 template <
typename Func,
typename... Extra>
1557 class_ &
def(
const char *name_, Func &&f,
const Extra &...extra) {
1558 cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
1567 template <
typename Func,
typename... Extra>
1568 class_ &
def_static(
const char *name_, Func &&f,
const Extra &...extra) {
1570 "def_static(...) called with a non-static member function pointer");
1576 auto cf_name = cf.
name();
1577 attr(std::move(cf_name)) =
staticmethod(std::move(cf));
1582 class_ &
def(
const detail::op_<id, ot, L, R> &op,
const Extra &...extra) {
1583 op.execute(*
this, extra...);
1588 class_ &
def_cast(
const detail::op_<id, ot, L, R> &op,
const Extra &...extra) {
1589 op.execute_cast(*
this, extra...);
1593 template <
typename... Args,
typename... Extra>
1594 class_ &
def(
const detail::initimpl::constructor<Args...> &
init,
const Extra &...extra) {
1596 init.execute(*
this, extra...);
1600 template <
typename... Args,
typename... Extra>
1601 class_ &
def(
const detail::initimpl::alias_constructor<Args...> &
init,
const Extra &...extra) {
1603 init.execute(*
this, extra...);
1607 template <
typename... Args,
typename... Extra>
1608 class_ &
def(detail::initimpl::factory<Args...> &&
init,
const Extra &...extra) {
1609 std::move(
init).execute(*
this, extra...);
1613 template <
typename... Args,
typename... Extra>
1614 class_ &
def(detail::initimpl::pickle_factory<Args...> &&pf,
const Extra &...extra) {
1615 std::move(pf).execute(*
this, extra...);
1619 template <
typename Func>
1625 install_buffer_funcs(
1627 detail::make_caster<type> caster;
1628 if (!caster.load(obj,
false)) {
1642 template <
typename Return,
typename Class,
typename... Args>
1644 return def_buffer([func](
type &obj) {
return (obj.*func)(); });
1647 template <
typename Return,
typename Class,
typename... Args>
1649 return def_buffer([func](
const type &obj) {
return (obj.*func)(); });
1652 template <
typename C,
typename D,
typename... Extra>
1655 "def_readwrite() requires a class member (or base class member)");
1662 template <
typename C,
typename D,
typename... Extra>
1665 "def_readonly() requires a class member (or base class member)");
1671 template <
typename D,
typename... Extra>
1674 fset([pm](
const object &,
const D &
value) { *pm =
value; },
scope(*
this));
1679 template <
typename D,
typename... Extra>
1687 template <
typename Getter,
typename... Extra>
1689 return def_property_readonly(name,
1696 template <
typename... Extra>
1699 return def_property(name, fget,
nullptr, extra...);
1703 template <
typename Getter,
typename... Extra>
1706 return def_property_readonly_static(
1711 template <
typename... Extra>
1714 const Extra &...extra) {
1715 return def_property_static(name, fget,
nullptr, extra...);
1719 template <
typename Getter,
typename Setter,
typename... Extra>
1721 def_property(
const char *
name,
const Getter &fget,
const Setter &fset,
const Extra &...extra) {
1722 return def_property(name, fget,
cpp_function(method_adaptor<type>(fset)), extra...);
1724 template <
typename Getter,
typename... Extra>
1728 const Extra &...extra) {
1729 return def_property(name,
1737 template <
typename... Extra>
1741 const Extra &...extra) {
1742 return def_property_static(name, fget, fset,
is_method(*
this), extra...);
1746 template <
typename Getter,
typename... Extra>
1750 const Extra &...extra) {
1751 return def_property_static(
1756 template <
typename... Extra>
1760 const Extra &...extra) {
1762 "Argument annotations are not allowed for properties");
1763 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1764 auto *rec_active = rec_fget;
1766 char *doc_prev = rec_fget->doc;
1769 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1770 std::free(doc_prev);
1775 char *doc_prev = rec_fset->doc;
1777 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1778 std::free(doc_prev);
1782 rec_active = rec_fset;
1785 def_property_static_impl(name, fget, fset, rec_active);
1791 template <
typename T>
1793 detail::value_and_holder &v_h,
1795 const std::enable_shared_from_this<T> * ) {
1797 auto sh = std::dynamic_pointer_cast<
typename holder_type::element_type>(
1801 v_h.set_holder_constructed();
1804 if (!v_h.holder_constructed() && inst->owned) {
1806 v_h.set_holder_constructed();
1814 holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1821 holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1827 detail::value_and_holder &v_h,
1831 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1832 v_h.set_holder_constructed();
1836 v_h.set_holder_constructed();
1846 if (!v_h.instance_registered()) {
1848 v_h.set_instance_registered();
1850 init_holder(inst, v_h, (
const holder_type *) holder_ptr, v_h.value_ptr<
type>());
1854 static void dealloc(detail::value_and_holder &v_h) {
1862 if (v_h.holder_constructed()) {
1864 v_h.set_holder_constructed(
false);
1867 v_h.value_ptr<
type>(), v_h.type->type_size, v_h.type->type_align);
1869 v_h.value_ptr() =
nullptr;
1874 return h ? (detail::function_record *) reinterpret_borrow<capsule>(
1875 PyCFunction_GET_SELF(h.
ptr()))
1881 template <
typename... Args>
1882 detail::initimpl::constructor<Args...>
init() {
1887 template <
typename... Args>
1893 template <
typename Func,
typename Ret = detail::initimpl::factory<Func>>
1895 return {std::forward<Func>(
f)};
1901 template <
typename CFunc,
typename AFunc,
typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1903 return {std::forward<CFunc>(
c), std::forward<AFunc>(
a)};
1908 template <
typename GetState,
typename SetState>
1909 detail::initimpl::pickle_factory<GetState, SetState>
pickle(GetState &&
g, SetState &&s) {
1910 return {std::forward<GetState>(
g), std::forward<SetState>(s)};
1916 dict entries = arg.get_type().attr(
"__entries");
1917 for (
auto kv : entries) {
1929 m_base.attr(
"__entries") =
dict();
1930 auto property =
handle((PyObject *) &PyProperty_Type);
1934 [](
const object &
arg) ->
str {
1936 object type_name = type.attr(
"__name__");
1953 m_base.attr(
"__doc__") = static_property(
1955 [](
handle arg) -> std::string {
1956 std::string docstring;
1957 dict entries = arg.attr(
"__entries");
1958 if (((PyTypeObject *) arg.
ptr())->tp_doc) {
1959 docstring += std::string(((PyTypeObject *) arg.
ptr())->tp_doc) +
"\n\n";
1961 docstring +=
"Members:";
1962 for (
auto kv : entries) {
1964 auto comment = kv.second[
int_(1)];
1965 docstring +=
"\n\n " +
key;
1966 if (!comment.is_none()) {
1977 m_base.attr(
"__members__") = static_property(
cpp_function(
1979 dict entries = arg.attr(
"__entries"),
1981 for (
auto kv : entries) {
1982 m[kv.first] = kv.second[
int_(0)];
1986 name(
"__members__")),
1991 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \ 1992 m_base.attr(op) = cpp_function( \ 1993 [](const object &a, const object &b) { \ 1994 if (!type::handle_of(a).is(type::handle_of(b))) \ 1999 is_method(m_base), \ 2002 #define PYBIND11_ENUM_OP_CONV(op, expr) \ 2003 m_base.attr(op) = cpp_function( \ 2004 [](const object &a_, const object &b_) { \ 2005 int_ a(a_), b(b_); \ 2009 is_method(m_base), \ 2012 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \ 2013 m_base.attr(op) = cpp_function( \ 2014 [](const object &a_, const object &b) { \ 2019 is_method(m_base), \ 2022 if (is_convertible) {
2026 if (is_arithmetic) {
2037 m_base.attr(
"__invert__")
2046 if (is_arithmetic) {
2047 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!"); 2052 #undef PYBIND11_THROW 2056 #undef PYBIND11_ENUM_OP_CONV_LHS 2057 #undef PYBIND11_ENUM_OP_CONV 2058 #undef PYBIND11_ENUM_OP_STRICT 2061 [](
const object &arg) {
return int_(arg); },
name(
"__getstate__"),
is_method(m_base));
2064 [](
const object &arg) {
return int_(arg); },
name(
"__hash__"),
is_method(m_base));
2068 dict entries = m_base.attr(
"__entries");
2071 std::string
type_name = (std::string)
str(m_base.attr(
"__name__"));
2072 throw value_error(std::move(type_name) +
": element \"" + std::string(name_)
2073 +
"\" already exists!");
2076 entries[
name] = std::make_pair(value,
doc);
2077 m_base.attr(std::move(name)) = std::move(value);
2081 dict entries = m_base.attr(
"__entries");
2082 for (
auto kv : entries) {
2083 m_parent.attr(kv.first) = kv.second[
int_(0)];
2091 template <
bool is_
signed,
size_t length>
2126 template <
typename IntLike>
2132 template <
typename Type>
2139 using Base::def_property_readonly;
2140 using Base::def_property_readonly_static;
2143 using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2144 std::is_same<Underlying, bool>>
::value,
2145 detail::equivalent_integer_t<Underlying>,
2148 template <
typename... Extra>
2150 : class_<
Type>(scope, name, extra...), m_base(*
this, scope) {
2151 constexpr
bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>
::value;
2153 m_base.init(is_arithmetic, is_convertible);
2156 def_property_readonly(
"value", [](
Type value) {
return (
Scalar) value; });
2157 def(
"__int__", [](
Type value) {
return (
Scalar) value; });
2158 def(
"__index__", [](
Type value) {
return (
Scalar) value; });
2160 [](detail::value_and_holder &v_h,
Scalar arg) {
2161 detail::initimpl::setstate<Base>(
2162 v_h,
static_cast<Type>(
arg), Py_TYPE(v_h.inst) != v_h.type->type);
2164 detail::is_new_style_constructor(),
2189 if (!nurse || !patient) {
2193 if (patient.is_none() || nurse.is_none()) {
2198 if (!tinfo.empty()) {
2211 weakref wr(nurse, disable_lifesupport);
2214 (void) wr.release();
2220 auto get_arg = [&](
size_t n) {
2227 if (
n <= call.
args.size()) {
2228 return call.
args[
n - 1];
2236 inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
2240 #ifdef __cpp_lib_unordered_map_try_emplace 2243 .emplace(type, std::vector<detail::type_info *>());
2253 for (
auto it = cache.begin(),
last = cache.end(); it !=
last;) {
2254 if (it->first == reinterpret_cast<PyObject *>(type)) {
2255 it = cache.erase(it);
2272 template <
typename Access,
2288 template <
typename Iterator,
typename SFINAE = decltype(*std::declval<Iterator &>())>
2295 template <
typename Iterator,
typename SFINAE = decltype((*std::declval<Iterator &>()).first)>
2312 decltype(((*std::declval<Iterator &>()).
first)),
2313 decltype(std::declval<pair_type>().
first)>;
2317 template <
typename Iterator,
typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
2325 decltype(((*std::declval<Iterator &>()).second)),
2326 decltype(std::declval<pair_type>().second)>;
2330 template <
typename Access,
2337 using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
2341 class_<state>(
handle(),
"iterator", pybind11::module_local())
2342 .def(
"__iter__", [](
state &s) ->
state & {
return s; })
2345 [](
state &s) -> ValueType {
2346 if (!s.first_or_done) {
2349 s.first_or_done =
false;
2351 if (s.it == s.end) {
2352 s.first_or_done =
true;
2353 throw stop_iteration();
2355 return Access()(s.it);
2358 std::forward<Extra>(extra)...,
2362 return cast(
state{std::forward<Iterator>(
first), std::forward<Sentinel>(
last),
true});
2371 typename ValueType =
typename detail::iterator_access<Iterator>::result_type,
2374 return detail::make_iterator_impl<detail::iterator_access<Iterator>,
2379 Extra...>(std::forward<Iterator>(
first),
2380 std::forward<Sentinel>(
last),
2381 std::forward<Extra>(extra)...);
2389 typename KeyType =
typename detail::iterator_key_access<Iterator>::result_type,
2392 return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
2397 Extra...>(std::forward<Iterator>(
first),
2398 std::forward<Sentinel>(
last),
2399 std::forward<Extra>(extra)...);
2407 typename ValueType =
typename detail::iterator_value_access<Iterator>::result_type,
2410 return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
2415 Extra...>(std::forward<Iterator>(
first),
2416 std::forward<Sentinel>(
last),
2417 std::forward<Extra>(extra)...);
2426 return make_iterator<Policy>(
2427 std::begin(value),
std::end(value), std::forward<Extra>(extra)...);
2436 return make_key_iterator<Policy>(
2437 std::begin(value),
std::end(value), std::forward<Extra>(extra)...);
2446 return make_value_iterator<Policy>(
2447 std::begin(value),
std::end(value), std::forward<Extra>(extra)...);
2450 template <
typename InputType,
typename OutputType>
2454 explicit set_flag(
bool &flag_) : flag(flag_) { flag_ =
true; }
2455 ~set_flag() { flag =
false; }
2457 auto implicit_caster = [](PyObject *obj, PyTypeObject *
type) -> PyObject * {
2458 static bool currently_used =
false;
2459 if (currently_used) {
2462 set_flag flag_helper(currently_used);
2463 if (!detail::make_caster<InputType>().load(obj,
false)) {
2468 PyObject *
result = PyObject_Call((PyObject *)
type, args.
ptr(),
nullptr);
2469 if (result ==
nullptr) {
2476 tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
2478 pybind11_fail(
"implicitly_convertible: Unable to find type " + type_id<OutputType>());
2484 std::forward<ExceptionTranslator>(translator));
2495 std::forward<ExceptionTranslator>(translator));
2505 template <
typename type>
2508 exception() =
default;
2510 std::string full_name
2511 = scope.attr(
"__name__").
cast<std::string>() + std::string(
".") +
name;
2512 m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()),
base.ptr(),
nullptr);
2513 if (
hasattr(scope,
"__dict__") && scope.attr(
"__dict__").contains(name)) {
2514 pybind11_fail(
"Error during initialization: multiple incompatible " 2515 "definitions with name \"" 2516 + std::string(name) +
"\"");
2518 scope.attr(name) = *
this;
2529 template <
typename CppException>
2531 static exception<CppException> ex;
2536 template <
typename CppException>
2537 exception<CppException> &
2539 auto &ex = detail::get_exception_object<CppException>();
2541 ex = exception<CppException>(
scope,
name, base);
2547 register_func([](std::exception_ptr p) {
2552 std::rethrow_exception(p);
2553 }
catch (
const CppException &
e) {
2554 detail::get_exception_object<CppException>()(e.what());
2568 template <
typename CppException>
2569 exception<CppException> &
2571 return detail::register_exception_impl<CppException>(
scope,
name,
base,
false );
2582 template <
typename CppException>
2583 exception<CppException> &
2585 return detail::register_exception_impl<CppException>(
scope,
name,
base,
true );
2590 auto strings =
tuple(args.size());
2591 for (
size_t i = 0;
i < args.size(); ++
i) {
2592 strings[
i] =
str(args[
i]);
2594 auto sep = kwargs.contains(
"sep") ? kwargs[
"sep"] :
str(
" ");
2595 auto line =
sep.attr(
"join")(std::move(strings));
2598 if (kwargs.contains(
"file")) {
2599 file = kwargs[
"file"].cast<
object>();
2612 auto write = file.attr(
"write");
2613 write(std::move(line));
2614 write(kwargs.contains(
"end") ? kwargs[
"end"] :
str(
"\n"));
2616 if (kwargs.contains(
"flush") && kwargs[
"flush"].cast<
bool>()) {
2617 file.attr(
"flush")();
2624 auto c = detail::collect_arguments<policy>(std::forward<Args>(
args)...);
2638 return m_fetched_error->error_string().c_str();
2655 if (cache.find(
key) != cache.end()) {
2659 function override =
getattr(
self, name,
function());
2661 cache.insert(std::move(
key));
2667 #if !defined(PYPY_VERSION) 2668 # if PY_VERSION_HEX >= 0x03090000 2669 PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
2670 if (frame !=
nullptr) {
2671 PyCodeObject *f_code = PyFrame_GetCode(frame);
2673 if ((std::string)
str(f_code->co_name) == name && f_code->co_argcount > 0) {
2674 PyObject *locals = PyEval_GetLocals();
2675 if (locals !=
nullptr) {
2676 PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code,
"co_varnames");
2677 PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
2678 Py_DECREF(co_varnames);
2679 PyObject *self_caller =
dict_getitem(locals, self_arg);
2680 if (self_caller ==
self.
ptr()) {
2691 PyFrameObject *frame = PyThreadState_Get()->frame;
2692 if (frame !=
nullptr && (std::string)
str(frame->f_code->co_name) == name
2693 && frame->f_code->co_argcount > 0) {
2694 PyFrame_FastToLocals(frame);
2695 PyObject *self_caller
2696 =
dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2697 if (self_caller ==
self.
ptr()) {
2711 = PyRun_String(
"import inspect\n" 2712 "frame = inspect.currentframe()\n" 2713 "if frame is not None:\n" 2714 " frame = frame.f_back\n" 2715 " if frame is not None and str(frame.f_code.co_name) == name and " 2716 "frame.f_code.co_argcount > 0:\n" 2717 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n" 2718 " if self_caller == self:\n" 2723 if (result ==
nullptr)
2726 if (d[
"self"].is_none())
2749 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \ 2751 pybind11::gil_scoped_acquire gil; \ 2752 pybind11::function override \ 2753 = pybind11::get_override(static_cast<const cname *>(this), name); \ 2755 auto o = override(__VA_ARGS__); \ 2756 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \ 2757 static pybind11::detail::override_caster_t<ret_type> caster; \ 2758 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \ 2760 return pybind11::detail::cast_safe<ret_type>(std::move(o)); \ 2782 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \ 2784 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \ 2785 return cname::fn(__VA_ARGS__); \ 2792 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \ 2794 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \ 2795 pybind11::pybind11_fail( \ 2796 "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \ 2824 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \ 2825 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__) 2831 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \ 2832 PYBIND11_OVERRIDE_PURE_NAME( \ 2833 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__) 2848 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \ 2849 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) 2850 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \ 2851 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__) 2852 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \ 2853 PYBIND11_OVERRIDE_PURE_NAME( \ 2854 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__); 2855 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \ 2856 PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__) 2857 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \ 2858 PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__); 2862 #if defined(__GNUC__) && __GNUC__ == 7 2863 # pragma GCC diagnostic pop // -Wnoexcept-type class_ & def_buffer(Func &&func)
handle scope
Python handle to the parent scope (a class or a module)
typename std::conditional< B, T, F >::type conditional_t
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 detail::type_info * get_type_info(PyTypeObject *type)
const gtsam::Symbol key('X', 0)
detail::exactly_one_t< is_holder, std::unique_ptr< type >, options... > holder_type
detail::exactly_one_t< is_subtype, void, options... > type_alias
#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)
class_ & def_buffer(Return(Class::*func)(Args...))
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.
void(* init_instance)(instance *, const void *)
Function pointer to class_<..>::init_instance.
size_t type_align
What is the alignment of the underlying C++ type?
PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()") object(handle h
Annotation for parent scope.
#define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
void(*)(std::exception_ptr) ExceptionTranslator
#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION
std::uint16_t nargs
Number of arguments (including py::args and/or py::kwargs, if present)
class_ & def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::true_type)
exception< CppException > & get_exception_object()
static handle handle_of()
bool hasattr(handle obj, handle name)
PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient)
iterator make_iterator_impl(Iterator &&first, Sentinel &&last, Extra &&...extra)
auto method_adaptor(F &&f) -> decltype(std::forward< F >(f))
void initialize(const type_record &rec)
PyObject * dict_getitemstring(PyObject *v, const char *key)
#define PYBIND11_COMPAT_STRDUP
std::forward_list< ExceptionTranslator > registered_exception_translators
module_ def_submodule(const char *name, const char *doc=nullptr)
PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type)
std::vector< handle > args
Arguments passed to the function:
#define PYBIND11_DETAILED_ERROR_MESSAGES
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 *, const std::enable_shared_from_this< T > *)
Initialize holder object, variant 1: object derives from enable_shared_from_this. ...
int RealScalar int RealScalar int RealScalar * pc
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)
PYBIND11_NOINLINE unique_function_record make_function_record()
Space optimization: don't inline this frequently instantiated fragment.
Annotation for documentation.
#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)
cpp_function(Return(Class::*f)(Arg...), const Extra &...extra)
Construct a cpp_function from a class method (non-const, no ref-qualifier)
decltype(*std::declval< Iterator & >()) result_type
#define PYBIND11_SILENCE_MSVC_C4127(...)
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
cpp_function(Return(Class::*f)(Arg...) const &, const Extra &...extra)
detail::is_strict_base_of< Type, T > is_subtype
std::pair< decltype(internals::registered_types_py)::iterator, bool > all_type_info_get_cache(PyTypeObject *type)
void *(* operator_new)(size_t)
The global operator new can be overridden with a class-specific variant.
type_map< type_info * > registered_types_cpp
Rot2 R(Rot2::fromAngle(0.1))
class_ & def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
enum_ & value(char const *name, Type value, const char *doc=nullptr)
Add an enumeration entry.
class_ & def(const char *name_, Func &&f, const Extra &...extra)
exception< CppException > & register_local_exception(handle scope, const char *name, handle base=PyExc_Exception)
Wrapper for Python extension modules.
bool multiple_inheritance
Multiple inheritance marker.
void raise_from(PyObject *type, const char *message)
std::forward_list< ExceptionTranslator > registered_exception_translators
size_t type_size
How large is the underlying C++ type?
enum_(const handle &scope, const char *name, const Extra &...extra)
PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs)
#define PYBIND11_TRY_NEXT_OVERLOAD
static constexpr size_t size_in_ptrs(size_t s)
Helper class which loads arguments for C++ functions called from Python.
class_ & def_buffer(Return(Class::*func)(Args...) const)
static void add_base(detail::type_record &)
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
class_ & def_readwrite(const char *name, D C::*pm, const Extra &...extra)
static void postcall(function_call &call, handle fn_ret)
Binds C++ enumerations and enumeration classes to Python.
void register_exception_translator(ExceptionTranslator &&translator)
typename exactly_one< Predicate, Default, Ts... >::type exactly_one_t
EIGEN_CONSTEXPR Index first(const T &x) EIGEN_NOEXCEPT
module_ & def(const char *name_, Func &&f, const Extra &...extra)
Internal data associated with a single function call.
#define PYBIND11_NAMESPACE
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof') ...
op_id
Enumeration with all supported operator types.
function get_override(const T *this_ptr, const char *name)
class_ & def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
Uses return_value_policy::reference by default.
static const symbolic::SymbolExpr< internal::symbolic_last_tag > last
static const Similarity3 id
PYBIND11_NOINLINE void clean_type_id(std::string &name)
str enum_name(handle arg)
void g(const string &key, int i)
constexpr size_t constexpr_sum()
Compile-time integer sum.
cpp_function(Func &&f, const Extra &...extra)
Construct a cpp_function from a lambda function (possibly with internal state)
result_type operator()(Iterator &it) const
PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc=nullptr)
const char * c_str(Args &&...args)
class_ & def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
decltype(*std::declval< Iterator & >()) pair_type
PyExc_RuntimeError [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
class_ & def_readwrite_static(const char *name, D *pm, const Extra &...extra)
PyObject * make_new_python_type(const type_record &rec)
cout<< "Here is the matrix m:"<< endl<< m<< endl;Matrix< ptrdiff_t, 3, 1 > res
const handle & inc_ref() const &
decltype(*std::declval< Iterator & >()) pair_type
static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::false_type)
void add_patient(PyObject *nurse, PyObject *patient)
constexpr int constexpr_first()
bool has_kwargs
True if the function has a '**kwargs' argument.
bool convert
True if the argument is allowed to convert when loading.
cpp_function(Return(*f)(Args...), const Extra &...extra)
Construct a cpp_function from a vanilla function pointer.
const char * name
Argument name.
conditional_t< std::is_reference< decltype(*std::declval< Iterator & >())>::value, decltype(((*std::declval< Iterator & >()).first)), decltype(std::declval< pair_type >().first)> result_type
handle scope
Handle to the parent scope.
value_and_holder get_value_and_holder(const type_info *find_type=nullptr, bool throw_if_missing=true)
#define PYBIND11_STD_LAUNDER
PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible)
static void add_base(detail::type_record &rec)
class_ & def_readonly(const char *name, const D C::*pm, const Extra &...extra)
PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite=false)
void initialize(Func &&f, Return(*)(Args...), const Extra &...extra)
Special internal constructor for functors, lambda functions, etc.
handle(* impl)(function_call &)
Pointer to lambda function which converts arguments and performs the actual call. ...
detail::initimpl::pickle_factory< GetState, SetState > pickle(GetState &&g, SetState &&s)
exception< CppException > & register_exception(handle scope, const char *name, handle base=PyExc_Exception)
std::uint16_t nargs_pos_only
Number of leading arguments (counted in nargs) that are positional-only.
const char * name
Name of the class.
list bases
List of base classes of the newly created type.
object & operator=(const object &other)
#define PYBIND11_DESCR_CONSTEXPR
cpp_function(Return(Class::*f)(Arg...) &, const Extra &...extra)
#define PYBIND11_INSTANCE_METHOD_CHECK
void def_property_static_impl(const char *name, handle fget, handle fset, detail::function_record *rec_func)
static void init_instance(detail::instance *inst, const void *holder_ptr)
std::vector< bool > args_convert
The convert value the arguments should be loaded with.
object name() const
Return the function name.
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
std::string get_fully_qualified_tp_name(PyTypeObject *type)
PYBIND11_NOINLINE void export_values()
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const ArgReturnType arg() const
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
type_map< type_info * > registered_types_cpp
class_ & def(detail::initimpl::factory< Args... > &&init, const Extra &...extra)
unsigned __int64 uint64_t
static void precall(function_call &call)
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
Eigen::Triplet< double > T
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
static detail::function_record * get_function_record(handle h)
detail::is_holder_type< Type, T > is_holder
bool is_cpp_function() const
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
bool is_method
True if this is a method.
static return_value_policy policy(return_value_policy p)
bool is_constructor
True if name == 'init'.
class_(handle scope, const char *name, const Extra &...extra)
enum_base(const handle &base, const handle &parent)
Array< double, 1, 3 > e(1./3., 0.5, 2.)
typename std::remove_reference< T >::type remove_reference_t
bool module_local
Is the class definition local to the module shared object?
function get_type_override(const void *this_ptr, const type_info *this_type, const char *name)
static bool show_function_signatures()
typename void_t_impl< Ts... >::type void_t
const handle & dec_ref() const &
void reload()
Reload the module or throws error_already_set.
void mark_parents_nonsimple(PyTypeObject *value)
Helper function which tags all parents of a type using mult. inheritance.
Helper type to replace 'void' in some expressions.
class_ & def_property_readonly_static(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name)
handle get_function(handle value)
PyObject * dict_getitem(PyObject *v, PyObject *key)
void operator()(detail::function_record *rec)
conditional_t< std::is_reference< decltype(*std::declval< Iterator & >())>::value, decltype(((*std::declval< Iterator & >()).second)), decltype(std::declval< pair_type >().second)> result_type
#define PYBIND11_ENUM_OP_CONV(op, expr)
typename equivalent_integer< std::is_signed< IntLike >::value, sizeof(IntLike)>::type equivalent_integer_t
Matrix< Scalar, Dynamic, Dynamic > C
void add_class_method(object &cls, const char *name_, const cpp_function &cf)
static void destruct(detail::function_record *rec, bool free_strings=true)
When a cpp_function is GCed, release any memory allocated by pybind11.
#define PYBIND11_MODULE_LOCAL_ID
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... > > all_of
bool none
True if None is allowed when loading.
class_ & def_cast(const detail::op_< id, ot, L, R > &op, const Extra &...extra)
static void init(const Args &...args, function_record *r)
bool apply_exception_translators(std::forward_list< ExceptionTranslator > &translators)
function_record * next
Pointer to next overload.
void(* dealloc)(detail::value_and_holder &)
Function pointer to class_<..>::dealloc.
detail::type_info * get_global_type_info(const std::type_index &tp)
enum_ & export_values()
Export enumeration entries into the parent scope.
typename std::underlying_type< Type >::type Underlying
static void init_holder(detail::instance *inst, detail::value_and_holder &v_h, const holder_type *holder_ptr, const void *)
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...
std::vector< char * > strings
size_t holder_size
How large is the type's holder?
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 args_are_all_keyword_or_ds()
Special data structure which (temporarily) holds metadata about a bound class.
static module_ import(const char *name)
Import and return a module or throws error_already_set.
const std::vector< detail::type_info * > & all_type_info(PyTypeObject *type)
bool default_holder
Is the default (unique_ptr) holder type used?
object getattr(handle obj, handle name)
detail::type_info * get_local_type_info(const std::type_index &tp)
RAII wrapper that temporarily clears any Python error state.
std::is_same< intrinsic_t< T >, kw_only > is_kw_only
detail::is_strict_base_of< T, Type > is_base
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.
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
static EIGEN_DEPRECATED const end_t end
static void dealloc(detail::value_and_holder &v_h)
Deallocates an instance; via holder, if constructed; otherwise via operator delete.
std::vector< argument_record > args
List of registered keyword arguments.
const std::type_info * type
class_ & def(const detail::initimpl::constructor< Args... > &init, const Extra &...extra)
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
class_ & def_static(const char *name_, Func &&f, const Extra &...extra)
exception< CppException > & register_exception_impl(handle scope, const char *name, handle base, bool isLocal)
void implicitly_convertible()
char * name
Function name.
bool has_args
True if the function has a '*args' argument.
bool is_operator
True if this is an operator (add), etc.
class_ & def(detail::initimpl::pickle_factory< Args... > &&pf, const Extra &...extra)
result_type operator()(Iterator &it) const
static std::shared_ptr< T > try_get_shared_from_this(std::enable_shared_from_this< T > *holder_value_ptr)
static bool show_user_defined_docstrings()
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ::Eigen::internal::enable_if< dt !=data_source::global_mem, void >::type write(PacketType &packet_data, DataScalar ptr)
write, a template function used for storing the data to local memory. This function is used to guaran...
static PYBIND11_NOINLINE void * local_load(PyObject *src, const type_info *ti)
iterator make_key_iterator(Iterator &&first, Sentinel &&last, Extra &&...extra)
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
result_type operator()(Iterator &it) const
iterator make_iterator(Iterator &&first, Sentinel &&last, Extra &&...extra)
Makes a python iterator from a first and past-the-end C++ InputIterator.
#define PYBIND11_ENUM_OP_CONV_LHS(op, expr)
static module_ create_extension_module(const char *name, const char *doc, module_def *def)
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_)
Include Python header, disable linking to pythonX_d.lib on Windows in debug mode. ...
iterator make_value_iterator(Iterator &&first, Sentinel &&last, Extra &&...extra)
bool is_new_style_constructor
True if this is a new-style __init__ defined in detail/init.h
Annotation for function names.
const char * name
If non-null, this is a named kwargs argument.
Annotation indicating that a class derives from another given type.
std::unique_ptr< detail::function_record, InitializingFunctionRecordDeleter > unique_function_record
Information record describing a Python buffer object.
PyObject * ptr() const
Return the underlying PyObject * pointer.
function get_overload(const T *this_ptr, const char *name)
handle init_self
If this is a call to an initializer, this argument contains self
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
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)
bool equal(const T &obj1, const T &obj2, double tol)
constexpr descr< N - 1 > const_name(char const (&text)[N])
void register_instance(instance *self, void *valptr, const type_info *tinfo)
class_ & def_property_readonly(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
void setattr(handle obj, handle name, handle value)
static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr)
Annotation indicating that a function is an overload associated with a given "sibling".
#define PYBIND11_NOINLINE
detail::initimpl::alias_constructor< Args... > init_alias()
exception(handle scope, const char *name, handle base=PyExc_Exception)
class_ & def(const detail::initimpl::alias_constructor< Args... > &init, const Extra &...extra)
class_ & def(const detail::op_< id, ot, L, R > &op, const Extra &...extra)
void register_local_exception_translator(ExceptionTranslator &&translator)
bool contains(T &&key) const
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
class_ & def_readonly_static(const char *name, const D *pm, const Extra &...extra)
void operator()(const char *message)
handle()=default
The default constructor creates a handle with a nullptr-valued pointer.
negation< all_of< negation< Ts >... > > any_of
Internal data structure which holds metadata about a keyword argument.
#define PYBIND11_NAMESPACE_END(name)
#define PYBIND11_OBJECT(Name, Parent, CheckFun)
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
cpp_function(std::nullptr_t)
#define PYBIND11_NAMESPACE_BEGIN(name)
std::is_same< intrinsic_t< T >, pos_only > is_pos_only
const char * what() const noexcept override
char * operator()(const char *s)
void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *), void *get_buffer_data)