13 #if defined(__INTEL_COMPILER)
15 # pragma warning disable 68 // integer conversion resulted in a change of sign
16 # pragma warning disable 186 // pointless comparison of unsigned integer with zero
17 # pragma warning disable 878 // incompatible exception specifications
18 # pragma warning disable 1334 // the "template" keyword used for syntactic disambiguation may only be used within a template
19 # pragma warning disable 1682 // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem)
20 # pragma warning disable 1786 // function "strdup" was declared deprecated
21 # pragma warning disable 1875 // offsetof applied to non-POD (Plain Old Data) types is nonstandard
22 # pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
23 #elif defined(_MSC_VER)
24 # pragma warning(push)
25 # pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
26 # pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
27 # pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
28 # pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
29 # pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
30 # pragma warning(disable: 4702) // warning C4702: unreachable code
31 # pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
32 # pragma warning(disable: 4505) // warning C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
33 #elif defined(__GNUG__) && !defined(__clang__)
34 # pragma GCC diagnostic push
35 # pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
36 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
37 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
38 # pragma GCC diagnostic ignored "-Wstrict-aliasing"
39 # pragma GCC diagnostic ignored "-Wattributes"
41 # pragma GCC diagnostic ignored "-Wnoexcept-type"
47 #include "detail/class.h"
48 #include "detail/init.h"
55 #if defined(__GNUG__) && !defined(__clang__)
59 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
68 template <
typename Return,
typename... Args,
typename... Extra>
70 initialize(f, f, extra...);
74 template <
typename Func,
typename... Extra,
75 typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
77 initialize(std::forward<Func>(f),
78 (detail::function_signature_t<Func> *)
nullptr, extra...);
82 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
84 initialize([f](Class *c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(
args)...); },
85 (Return (*) (Class *, Arg...))
nullptr, extra...);
91 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
93 initialize([f](Class *c, Arg...
args) -> Return { return (c->*f)(
args...); },
94 (Return (*) (Class *, Arg...))
nullptr, extra...);
98 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
99 cpp_function(Return (Class::*f)(Arg...)
const,
const Extra&... extra) {
100 initialize([f](
const Class *c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(
args)...); },
101 (Return (*)(
const Class *, Arg ...))
nullptr, extra...);
107 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
108 cpp_function(Return (Class::*f)(Arg...)
const&,
const Extra&... extra) {
109 initialize([f](
const Class *c, Arg...
args) -> Return { return (c->*f)(
args...); },
110 (Return (*)(
const Class *, Arg ...))
nullptr, extra...);
114 object name()
const {
return attr(
"__name__"); }
119 return new detail::function_record();
123 template <
typename Func,
typename Return,
typename... Args,
typename... Extra>
124 void initialize(Func &&f, Return (*)(Args...),
const Extra&... extra) {
125 using namespace detail;
126 struct capture { remove_reference_t<Func> f; };
129 auto rec = make_function_record();
132 if (
sizeof(capture) <=
sizeof(rec->data)) {
136 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
137 # pragma GCC diagnostic push
138 # pragma GCC diagnostic ignored "-Wplacement-new"
140 new ((capture *) &rec->data) capture { std::forward<Func>(f) };
141 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
142 # pragma GCC diagnostic pop
144 if (!std::is_trivially_destructible<Func>::value)
145 rec->free_data = [](
function_record *r) { ((capture *) &r->data)->~capture(); };
147 rec->data[0] =
new capture { std::forward<Func>(f) };
148 rec->free_data = [](
function_record *r) {
delete ((capture *) r->data[0]); };
152 using cast_in = argument_loader<Args...>;
154 conditional_t<std::is_void<Return>::value,
void_type, Return>
157 static_assert(expected_num_args<Extra...>(
sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
158 "The number of argument annotations does not match the number of function arguments");
161 rec->impl = [](function_call &call) ->
handle {
162 cast_in args_converter;
165 if (!args_converter.load_args(call))
166 return PYBIND11_TRY_NEXT_OVERLOAD;
172 auto data = (
sizeof(capture) <=
sizeof(call.func.data)
173 ? &call.func.data : call.func.data[0]);
174 auto *cap =
const_cast<capture *
>(
reinterpret_cast<const capture *
>(data));
177 return_value_policy policy = return_value_policy_override<Return>::policy(call.func.policy);
180 using Guard = extract_guard_t<Extra...>;
183 handle result = cast_out::cast(
184 std::move(args_converter).
template call<Return, Guard>(cap->f), policy, call.parent);
200 static_assert(has_arg_annotations || !has_kw_only_args,
"py::kw_only requires the use of argument annotations");
201 static_assert(has_arg_annotations || !has_pos_only_args,
"py::pos_only requires the use of argument annotations (for docstrings and aligning the annotations to the argument)");
202 static_assert(!(has_args && has_kw_only_args),
"py::kw_only cannot be combined with a py::args argument");
206 static constexpr
auto signature = _(
"(") + cast_in::arg_names + _(
") -> ") + cast_out::name;
207 PYBIND11_DESCR_CONSTEXPR
auto types = decltype(signature)::types();
210 initialize_generic(rec, signature.text, types.data(),
sizeof...(Args));
212 if (cast_in::has_args) rec->has_args =
true;
213 if (cast_in::has_kwargs) rec->has_kwargs =
true;
216 using FunctionType = Return (*)(Args...);
217 constexpr
bool is_function_ptr =
218 std::is_convertible<Func, FunctionType>::value &&
219 sizeof(capture) ==
sizeof(
void *);
220 if (is_function_ptr) {
221 rec->is_stateless =
true;
222 rec->data[1] =
const_cast<void *
>(
reinterpret_cast<const void *
>(&
typeid(FunctionType)));
228 const std::type_info *
const *types,
size_t args) {
231 rec->name = strdup(rec->name ? rec->name :
"");
232 if (rec->doc) rec->doc = strdup(rec->doc);
233 for (
auto &a: rec->args) {
235 a.name = strdup(a.name);
237 a.descr = strdup(a.descr);
239 a.descr = strdup(repr(a.value).cast<std::string>().c_str());
242 rec->is_constructor = !strcmp(rec->name,
"__init__") || !strcmp(rec->name,
"__setstate__");
244 #if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
245 if (rec->is_constructor && !rec->is_new_style_constructor) {
246 const auto class_name = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
247 const auto func_name = std::string(rec->name);
250 (
"pybind11-bound class '" + class_name +
"' is using an old-style "
251 "placement-new '" + func_name +
"' which has been deprecated. See "
252 "the upgrade guide in pybind11's docs. This message is only visible "
253 "when compiled in debug mode.").c_str(), 0
259 std::string signature;
260 size_t type_index = 0, arg_index = 0;
261 for (
auto *pc = text; *pc !=
'\0'; ++pc) {
266 if (*(pc + 1) ==
'*')
270 if (rec->nargs_kw_only > 0 && arg_index + rec->nargs_kw_only == args)
272 if (arg_index < rec->args.size() && rec->args[arg_index].name) {
273 signature += rec->args[arg_index].name;
274 }
else if (arg_index == 0 && rec->is_method) {
277 signature +=
"arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
280 }
else if (c ==
'}') {
282 if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
284 signature += rec->args[arg_index].descr;
288 if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only)
291 }
else if (c ==
'%') {
292 const std::type_info *t = types[type_index++];
294 pybind11_fail(
"Internal error while parsing type signature (1)");
295 if (
auto tinfo = detail::get_type_info(*t)) {
296 handle th((PyObject *) tinfo->type);
298 th.attr(
"__module__").
cast<std::string>() +
"." +
299 th.attr(
"__qualname__").
cast<std::string>();
300 }
else if (rec->is_new_style_constructor && arg_index == 0) {
304 rec->scope.attr(
"__module__").cast<std::string>() +
"." +
305 rec->scope.attr(
"__qualname__").cast<std::string>();
307 std::string tname(t->name());
308 detail::clean_type_id(tname);
316 if (arg_index != args || types[type_index] !=
nullptr)
317 pybind11_fail(
"Internal error while parsing type signature (2)");
319 #if PY_MAJOR_VERSION < 3
320 if (strcmp(rec->name,
"__next__") == 0) {
321 std::free(rec->name);
322 rec->name = strdup(
"next");
323 }
else if (strcmp(rec->name,
"__bool__") == 0) {
324 std::free(rec->name);
325 rec->name = strdup(
"__nonzero__");
328 rec->signature = strdup(signature.c_str());
329 rec->args.shrink_to_fit();
330 rec->nargs = (std::uint16_t) args;
332 if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr()))
333 rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
335 detail::function_record *chain =
nullptr, *chain_start = rec;
337 if (PyCFunction_Check(rec->sibling.ptr())) {
338 auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
339 chain = (detail::function_record *) rec_capsule;
342 if (!chain->scope.is(rec->scope))
346 else if (!rec->sibling.is_none() && rec->name[0] !=
'_')
347 pybind11_fail(
"Cannot overload existing non-function object \"" + std::string(rec->name) +
348 "\" with a function of the same name");
353 rec->def =
new PyMethodDef();
354 std::memset(rec->def, 0,
sizeof(PyMethodDef));
355 rec->def->ml_name = rec->name;
356 rec->def->ml_meth =
reinterpret_cast<PyCFunction
>(
reinterpret_cast<void (*) (
void)
>(*dispatcher));
357 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
359 capsule rec_capsule(rec, [](
void *ptr) {
360 destruct((detail::function_record *) ptr);
365 if (hasattr(rec->scope,
"__module__")) {
366 scope_module = rec->scope.attr(
"__module__");
367 }
else if (hasattr(rec->scope,
"__name__")) {
368 scope_module = rec->scope.attr(
"__name__");
372 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
374 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate function object");
377 m_ptr = rec->sibling.ptr();
379 if (chain->is_method != rec->is_method)
380 pybind11_fail(
"overloading a method with both static and instance methods is not supported; "
382 "compile in debug mode for more details"
384 "error while attempting to bind " + std::string(rec->is_method ?
"instance" :
"static") +
" method " +
385 std::string(pybind11::str(rec->scope.attr(
"__name__"))) +
"." + std::string(rec->name) + signature
395 auto rec_capsule = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self);
396 rec_capsule.set_pointer(rec);
406 std::string signatures;
410 if (chain && options::show_function_signatures()) {
412 signatures += rec->name;
413 signatures +=
"(*args, **kwargs)\n";
414 signatures +=
"Overloaded function.\n\n";
417 bool first_user_def =
true;
418 for (
auto it = chain_start; it !=
nullptr; it = it->next) {
419 if (options::show_function_signatures()) {
420 if (index > 0) signatures +=
"\n";
422 signatures += std::to_string(++index) +
". ";
423 signatures += rec->name;
424 signatures += it->signature;
427 if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
430 if (!options::show_function_signatures()) {
431 if (first_user_def) first_user_def =
false;
432 else signatures +=
"\n";
434 if (options::show_function_signatures()) signatures +=
"\n";
435 signatures += it->doc;
436 if (options::show_function_signatures()) signatures +=
"\n";
441 auto *func = (PyCFunctionObject *) m_ptr;
442 if (func->m_ml->ml_doc)
443 std::free(const_cast<char *>(func->m_ml->ml_doc));
444 func->m_ml->ml_doc = strdup(signatures.c_str());
446 if (rec->is_method) {
447 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
449 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate instance method object");
455 static void destruct(detail::function_record *rec) {
458 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
459 static bool is_zero = Py_GetVersion()[4] ==
'0';
463 detail::function_record *next = rec->next;
466 std::free((
char *) rec->name);
467 std::free((
char *) rec->doc);
468 std::free((
char *) rec->signature);
469 for (
auto &arg: rec->args) {
470 std::free(const_cast<char *>(arg.name));
471 std::free(const_cast<char *>(arg.descr));
475 std::free(const_cast<char *>(rec->def->ml_doc));
479 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
492 static PyObject *
dispatcher(PyObject *
self, PyObject *args_in, PyObject *kwargs_in) {
493 using namespace detail;
500 const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
502 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) :
nullptr,
503 result = PYBIND11_TRY_NEXT_OVERLOAD;
506 if (overloads->is_constructor) {
507 const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
508 const auto pi =
reinterpret_cast<instance *
>(parent.ptr());
511 if (!self_value_and_holder.type || !self_value_and_holder.inst) {
512 PyErr_SetString(PyExc_TypeError,
"__init__(self, ...) called with invalid `self` argument");
518 if (self_value_and_holder.instance_registered())
527 std::vector<function_call> second_pass;
530 const bool overloaded = it !=
nullptr && it->next !=
nullptr;
532 for (; it !=
nullptr; it = it->next) {
554 size_t num_args = func.
nargs;
559 if (!func.
has_args && n_args_in > pos_args)
562 if (n_args_in < pos_args && func.
args.size() < pos_args)
565 function_call call(func, parent);
567 size_t args_to_copy = (std::min)(pos_args, n_args_in);
568 size_t args_copied = 0;
574 if (self_value_and_holder)
575 self_value_and_holder.type->dealloc(self_value_and_holder);
577 call.init_self = PyTuple_GET_ITEM(args_in, 0);
578 call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
579 call.args_convert.push_back(
false);
584 bool bad_arg =
false;
585 for (; args_copied < args_to_copy; ++args_copied) {
587 if (kwargs_in && arg_rec && arg_rec->
name && PyDict_GetItemString(kwargs_in, arg_rec->
name)) {
592 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
593 if (arg_rec && !arg_rec->
none && arg.is_none()) {
597 call.args.push_back(arg);
598 call.args_convert.push_back(arg_rec ? arg_rec->
convert :
true);
604 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
609 const auto &arg_rec = func.
args[args_copied];
613 value = arg_rec.value;
616 call.args.push_back(value);
617 call.args_convert.push_back(arg_rec.convert);
627 if (args_copied < num_args) {
628 bool copied_kwargs =
false;
630 for (; args_copied < num_args; ++args_copied) {
631 const auto &arg_rec = func.
args[args_copied];
634 if (kwargs_in && arg_rec.name)
635 value = PyDict_GetItemString(kwargs.
ptr(), arg_rec.name);
639 if (!copied_kwargs) {
640 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.
ptr()));
641 copied_kwargs =
true;
643 PyDict_DelItemString(kwargs.
ptr(), arg_rec.name);
644 }
else if (arg_rec.value) {
645 value = arg_rec.value;
648 if (!arg_rec.none && value.is_none()) {
653 call.args.push_back(value);
654 call.args_convert.push_back(arg_rec.convert);
660 if (args_copied < num_args)
665 if (kwargs && !kwargs.empty() && !func.
has_kwargs)
671 if (args_to_copy == 0) {
674 extra_args = reinterpret_borrow<tuple>(args_in);
675 }
else if (args_copied >= n_args_in) {
676 extra_args =
tuple(0);
678 size_t args_size = n_args_in - args_copied;
679 extra_args =
tuple(args_size);
680 for (
size_t i = 0; i < args_size; ++i) {
681 extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i);
684 call.args.push_back(extra_args);
685 call.args_convert.push_back(
false);
686 call.args_ref = std::move(extra_args);
693 call.args.push_back(kwargs);
694 call.args_convert.push_back(
false);
695 call.kwargs_ref = std::move(kwargs);
701 if (call.args.size() != func.
nargs || call.args_convert.size() != func.
nargs)
702 pybind11_fail(
"Internal error: function call dispatcher inserted wrong number of arguments!");
705 std::vector<bool> second_pass_convert;
710 second_pass_convert.resize(func.
nargs,
false);
711 call.args_convert.swap(second_pass_convert);
717 result = func.
impl(call);
718 }
catch (reference_cast_error &) {
719 result = PYBIND11_TRY_NEXT_OVERLOAD;
722 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
729 for (
size_t i = func.
is_method ? 1 : 0; i < pos_args; i++) {
730 if (second_pass_convert[i]) {
733 call.args_convert.swap(second_pass_convert);
734 second_pass.push_back(std::move(call));
741 if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
743 for (
auto &call : second_pass) {
746 result = call.func.impl(call);
747 }
catch (reference_cast_error &) {
748 result = PYBIND11_TRY_NEXT_OVERLOAD;
751 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
764 }
catch ( abi::__forced_unwind& ) {
779 auto last_exception = std::current_exception();
780 auto ®istered_exception_translators = get_internals().registered_exception_translators;
781 for (
auto& translator : registered_exception_translators) {
783 translator(last_exception);
785 last_exception = std::current_exception();
790 PyErr_SetString(PyExc_SystemError,
"Exception escaped from default exception translator!");
794 auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
795 if (msg.find(
"std::") != std::string::npos) {
797 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
798 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
799 "conversions are optional and require extra headers to be included\n"
800 "when compiling your pybind11 module.";
804 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
805 if (overloads->is_operator)
808 std::string msg = std::string(overloads->name) +
"(): incompatible " +
809 std::string(overloads->is_constructor ?
"constructor" :
"function") +
810 " arguments. The following argument types are supported:\n";
814 msg +=
" "+ std::to_string(++ctr) +
". ";
816 bool wrote_sig =
false;
817 if (overloads->is_constructor) {
819 std::string sig = it2->signature;
820 size_t start = sig.find(
'(') + 7;
821 if (start < sig.size()) {
823 size_t end = sig.find(
", "), next = end + 2;
824 size_t ret = sig.rfind(
" -> ");
826 if (end >= sig.size()) next = end = sig.find(
')');
827 if (start < end && next < sig.size()) {
828 msg.append(sig, start, end - start);
830 msg.append(sig, next, ret - next);
835 if (!wrote_sig) msg += it2->signature;
839 msg +=
"\nInvoked with: ";
840 auto args_ = reinterpret_borrow<tuple>(args_in);
841 bool some_args =
false;
842 for (
size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
843 if (!some_args) some_args =
true;
846 msg += pybind11::repr(args_[ti]);
848 msg +=
"<repr raised Error>";
852 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
854 if (some_args) msg +=
"; ";
857 for (
auto kwarg :
kwargs) {
858 if (first) first =
false;
860 msg += pybind11::str(
"{}=").format(kwarg.first);
862 msg += pybind11::repr(kwarg.second);
864 msg +=
"<repr raised Error>";
870 append_note_if_missing_header_is_suspected(msg);
871 PyErr_SetString(PyExc_TypeError, msg.c_str());
873 }
else if (!result) {
874 std::string msg =
"Unable to convert function return value to a "
875 "Python type! The signature was\n\t";
876 msg += it->signature;
877 append_note_if_missing_header_is_suspected(msg);
878 PyErr_SetString(PyExc_TypeError, msg.c_str());
881 if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
882 auto *pi =
reinterpret_cast<instance *
>(parent.ptr());
883 self_value_and_holder.type->init_instance(pi,
nullptr);
893 PYBIND11_OBJECT_DEFAULT(
module_,
object, PyModule_Check)
896 PYBIND11_DEPRECATED(
"Use PYBIND11_MODULE or module_::create_extension_module instead")
898 #if PY_MAJOR_VERSION >= 3
899 *
this = create_extension_module(name,
doc,
new PyModuleDef());
901 *
this = create_extension_module(name,
doc,
nullptr);
910 template <
typename Func,
typename... Extra>
911 module_ &
def(
const char *name_, Func &&f,
const Extra& ... extra) {
916 add_object(name_, func,
true );
931 std::string full_name = std::string(PyModule_GetName(m_ptr))
932 + std::string(
".") + std::string(name);
933 auto result = reinterpret_borrow<module_>(PyImport_AddModule(full_name.c_str()));
934 if (
doc && options::show_user_defined_docstrings())
935 result.attr(
"__doc__") = pybind11::str(
doc);
942 PyObject *obj = PyImport_ImportModule(
name);
945 return reinterpret_steal<module_>(obj);
950 PyObject *obj = PyImport_ReloadModule(ptr());
953 *
this = reinterpret_steal<module_>(obj);
964 if (!overwrite && hasattr(*
this, name))
965 pybind11_fail(
"Error during initialization: multiple incompatible definitions with name \"" +
966 std::string(name) +
"\"");
968 PyModule_AddObject(ptr(), name, obj.
inc_ref().
ptr() );
971 #if PY_MAJOR_VERSION >= 3
972 using module_def = PyModuleDef;
984 #if PY_MAJOR_VERSION >= 3
986 def =
new (def) PyModuleDef {
987 PyModuleDef_HEAD_INIT,
989 options::show_user_defined_docstrings() ? doc :
nullptr,
997 auto m = PyModule_Create(def);
1001 auto m = Py_InitModule3(name,
nullptr, options::show_user_defined_docstrings() ? doc :
nullptr);
1004 if (PyErr_Occurred())
1006 pybind11_fail(
"Internal error in module_::create_extension_module()");
1010 return reinterpret_borrow<module_>(m);
1023 PyObject *p = PyEval_GetGlobals();
1024 return reinterpret_borrow<dict>(p ? p :
module_::import(
"__main__").attr(
"__dict__").
ptr());
1027 PYBIND11_NAMESPACE_BEGIN(detail)
1031 PYBIND11_OBJECT_DEFAULT(
generic_type,
object, PyType_Check)
1034 if (rec.
scope && hasattr(rec.
scope,
"__dict__") && rec.
scope.attr(
"__dict__").contains(rec.
name))
1035 pybind11_fail(
"generic_type: cannot initialize type \"" + std::string(rec.
name) +
1036 "\": an object with that name is already defined");
1038 if (rec.
module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
1039 pybind11_fail(
"generic_type: type \"" + std::string(rec.
name) +
1040 "\" is already registered!");
1042 m_ptr = make_new_python_type(rec);
1045 auto *tinfo =
new detail::type_info();
1046 tinfo->type = (PyTypeObject *) m_ptr;
1047 tinfo->cpptype = rec.type;
1051 tinfo->holder_size_in_ptrs = size_in_ptrs(rec.
holder_size);
1054 tinfo->simple_type =
true;
1055 tinfo->simple_ancestors =
true;
1060 auto tindex = std::type_index(*rec.type);
1061 tinfo->direct_conversions = &
internals.direct_conversions[tindex];
1063 registered_local_types_cpp()[tindex] = tinfo;
1065 internals.registered_types_cpp[tindex] = tinfo;
1066 internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo };
1069 mark_parents_nonsimple(tinfo->type);
1070 tinfo->simple_ancestors =
false;
1072 else if (rec.
bases.size() == 1) {
1073 auto parent_tinfo = get_type_info((PyTypeObject *) rec.
bases[0].
ptr());
1074 tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
1079 tinfo->module_local_load = &type_caster_generic::local_load;
1080 setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID,
capsule(tinfo));
1086 auto t = reinterpret_borrow<tuple>(value->tp_bases);
1088 auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
1090 tinfo2->simple_type =
false;
1091 mark_parents_nonsimple((PyTypeObject *) h.ptr());
1095 void install_buffer_funcs(
1097 void *get_buffer_data) {
1098 auto *
type = (PyHeapTypeObject*) m_ptr;
1099 auto tinfo = detail::get_type_info(&
type->ht_type);
1101 if (!
type->ht_type.tp_as_buffer)
1103 "To be able to register buffer protocol support for the type '" +
1104 get_fully_qualified_tp_name(tinfo->type) +
1105 "' the associated class<>(..) invocation must "
1106 "include the pybind11::buffer_protocol() annotation!");
1108 tinfo->get_buffer = get_buffer;
1109 tinfo->get_buffer_data = get_buffer_data;
1113 void def_property_static_impl(
const char *
name,
1115 detail::function_record *rec_func) {
1116 const auto is_static = rec_func && !(rec_func->is_method && rec_func->scope);
1117 const auto has_doc = rec_func && rec_func->doc && pybind11::options::show_user_defined_docstrings();
1118 auto property =
handle((PyObject *) (is_static ? get_internals().static_property_type
1119 : &PyProperty_Type));
1120 attr(name) = property(fget.
ptr() ? fget :
none(),
1123 pybind11::str(has_doc ? rec_func->doc :
""));
1128 template <
typename T,
typename =
void_t<decltype(static_cast<
void *(*)(
size_t)>(T::operator new))>>
1131 template <
typename>
void set_operator_new(...) { }
1134 template <
typename T>
struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(
void *)>(T::operator
delete))>>
1135 : std::true_type { };
1138 : std::true_type { };
1140 template <typename T, enable_if_t<has_operator_delete<T>::value,
int> = 0>
1141 void call_operator_delete(T *p,
size_t,
size_t) { T::operator
delete(p); }
1143 void call_operator_delete(T *p,
size_t s,
size_t) { T::operator
delete(p, s); }
1145 inline void call_operator_delete(
void *p,
size_t s,
size_t a) {
1147 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1148 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1149 #ifdef __cpp_sized_deallocation
1150 ::operator
delete(p, s, std::align_val_t(a));
1152 ::operator
delete(p, std::align_val_t(a));
1157 #ifdef __cpp_sized_deallocation
1158 ::operator
delete(p, s);
1160 ::operator
delete(p);
1164 inline void add_class_method(
object& cls,
const char *name_,
const cpp_function &cf) {
1165 cls.attr(cf.
name()) = cf;
1166 if (strcmp(name_,
"__eq__") == 0 && !cls.attr(
"__dict__").contains(
"__hash__")) {
1167 cls.attr(
"__hash__") =
none();
1171 PYBIND11_NAMESPACE_END(detail)
1175 template <typename , typename F>
1176 auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
return std::forward<F>(f); }
1178 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1179 auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
1180 static_assert(detail::is_accessible_base_of<Class, Derived>::value,
1181 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1185 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1186 auto method_adaptor(Return (Class::*pmf)(Args...)
const) -> Return (Derived::*)(Args...)
const {
1187 static_assert(detail::is_accessible_base_of<Class, Derived>::value,
1188 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1192 template <
typename type_,
typename...
options>
1194 template <
typename T>
using is_holder = detail::is_holder_type<type_, T>;
1195 template <
typename T>
using is_subtype = detail::is_strict_base_of<type_, T>;
1196 template <
typename T>
using is_base = detail::is_strict_base_of<T, type_>;
1199 detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
1203 using type_alias = detail::exactly_one_t<is_subtype, void,
options...>;
1204 constexpr
static bool has_alias = !std::is_void<type_alias>::value;
1205 using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>,
options...>;
1208 "Unknown/invalid class_ template parameters provided");
1210 static_assert(!has_alias || std::is_polymorphic<type>::value,
1211 "Cannot use an alias class with a non-polymorphic type");
1215 template <typename... Extra>
1217 using namespace detail;
1221 none_of<is_pyobject<Extra>...>::value ||
1222 ( constexpr_sum(is_pyobject<Extra>::value...) == 1 &&
1223 constexpr_sum(is_base<options>::value...) == 0 &&
1224 none_of<std::is_same<multiple_inheritance, Extra>...>::value),
1225 "Error: multiple inheritance bases must be specified via class_ template options");
1228 record.
scope = scope;
1230 record.type = &
typeid(
type);
1231 record.type_size =
sizeof(conditional_t<has_alias, type_alias, type>);
1232 record.type_align =
alignof(conditional_t<has_alias, type_alias, type>&);
1233 record.holder_size =
sizeof(holder_type);
1234 record.init_instance = init_instance;
1235 record.dealloc = dealloc;
1236 record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
1238 set_operator_new<type>(&record);
1241 PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
1246 generic_type::initialize(record);
1249 auto &instances = record.module_local ? registered_local_types_cpp() : get_internals().registered_types_cpp;
1250 instances[std::type_index(
typeid(type_alias))] = instances[std::type_index(
typeid(
type))];
1254 template <typename Base, detail::enable_if_t<is_base<Base>::value,
int> = 0>
1255 static void add_base(detail::type_record &rec) {
1256 rec.add_base(
typeid(Base), [](
void *src) ->
void * {
1257 return static_cast<Base *
>(
reinterpret_cast<type *
>(src));
1261 template <typename Base, detail::enable_if_t<!is_base<Base>::value,
int> = 0>
1262 static void add_base(detail::type_record &) { }
1264 template <
typename Func,
typename... Extra>
1265 class_ &def(
const char *name_, Func&& f,
const Extra&... extra) {
1267 sibling(getattr(*
this, name_,
none())), extra...);
1268 add_class_method(*
this, name_, cf);
1272 template <
typename Func,
typename... Extra>
class_ &
1273 def_static(
const char *name_, Func &&f,
const Extra&... extra) {
1274 static_assert(!std::is_member_function_pointer<Func>::value,
1275 "def_static(...) called with a non-static member function pointer");
1276 cpp_function cf(std::forward<Func>(f), name(name_), scope(*
this),
1277 sibling(getattr(*
this, name_,
none())), extra...);
1282 template <detail::op_id id, detail::op_type ot,
typename L,
typename R,
typename... Extra>
1283 class_ &def(
const detail::op_<id, ot, L, R> &op,
const Extra&... extra) {
1284 op.execute(*
this, extra...);
1288 template <detail::op_id id, detail::op_type ot,
typename L,
typename R,
typename... Extra>
1289 class_ & def_cast(
const detail::op_<id, ot, L, R> &op,
const Extra&... extra) {
1290 op.execute_cast(*
this, extra...);
1294 template <
typename... Args,
typename... Extra>
1295 class_ &def(
const detail::initimpl::constructor<Args...> &init,
const Extra&... extra) {
1296 init.execute(*
this, extra...);
1300 template <
typename... Args,
typename... Extra>
1301 class_ &def(
const detail::initimpl::alias_constructor<Args...> &init,
const Extra&... extra) {
1302 init.execute(*
this, extra...);
1306 template <
typename... Args,
typename... Extra>
1307 class_ &def(detail::initimpl::factory<Args...> &&init,
const Extra&... extra) {
1308 std::move(init).execute(*
this, extra...);
1312 template <
typename... Args,
typename... Extra>
1313 class_ &def(detail::initimpl::pickle_factory<Args...> &&pf,
const Extra &...extra) {
1314 std::move(pf).execute(*
this, extra...);
1318 template <
typename Func>
class_& def_buffer(Func &&func) {
1319 struct capture { Func func; };
1320 auto *ptr =
new capture { std::forward<Func>(func) };
1321 install_buffer_funcs([](PyObject *obj,
void *ptr) ->
buffer_info* {
1322 detail::make_caster<type> caster;
1323 if (!caster.load(obj,
false))
1325 return new buffer_info(((capture *) ptr)->func(caster));
1330 template <
typename Return,
typename Class,
typename... Args>
1331 class_ &def_buffer(Return (Class::*func)(Args...)) {
1332 return def_buffer([func] (
type &obj) {
return (obj.*func)(); });
1335 template <
typename Return,
typename Class,
typename... Args>
1336 class_ &def_buffer(Return (Class::*func)(Args...)
const) {
1337 return def_buffer([func] (
const type &obj) {
return (obj.*func)(); });
1340 template <
typename C,
typename D,
typename... Extra>
1341 class_ &def_readwrite(
const char *name, D C::*pm,
const Extra&... extra) {
1342 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
"def_readwrite() requires a class member (or base class member)");
1344 fset([pm](
type &c,
const D &value) { c.*pm = value; },
is_method(*
this));
1345 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
1349 template <
typename C,
typename D,
typename... Extra>
1350 class_ &def_readonly(
const char *name,
const D C::*pm,
const Extra& ...extra) {
1351 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
"def_readonly() requires a class member (or base class member)");
1353 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
1357 template <
typename D,
typename... Extra>
1358 class_ &def_readwrite_static(
const char *name, D *pm,
const Extra& ...extra) {
1359 cpp_function fget([pm](
object) ->
const D &{
return *pm; }, scope(*
this)),
1360 fset([pm](
object,
const D &value) { *pm = value; }, scope(*
this));
1361 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
1365 template <
typename D,
typename... Extra>
1366 class_ &def_readonly_static(
const char *name,
const D *pm,
const Extra& ...extra) {
1367 cpp_function fget([pm](
object) ->
const D &{
return *pm; }, scope(*
this));
1368 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
1373 template <
typename Getter,
typename... Extra>
1375 return def_property_readonly(name,
cpp_function(method_adaptor<type>(fget)),
1376 return_value_policy::reference_internal, extra...);
1380 template <
typename... Extra>
1382 return def_property(name, fget,
nullptr, extra...);
1386 template <
typename Getter,
typename... Extra>
1388 return def_property_readonly_static(name,
cpp_function(fget), return_value_policy::reference, extra...);
1392 template <
typename... Extra>
1394 return def_property_static(name, fget,
nullptr, extra...);
1398 template <
typename Getter,
typename Setter,
typename... Extra>
1400 return def_property(name, fget,
cpp_function(method_adaptor<type>(fset)), extra...);
1402 template <
typename Getter,
typename... Extra>
1403 class_ &def_property(
const char *name,
const Getter &fget,
const cpp_function &fset,
const Extra& ...extra) {
1404 return def_property(name,
cpp_function(method_adaptor<type>(fget)), fset,
1405 return_value_policy::reference_internal, extra...);
1409 template <
typename... Extra>
1411 return def_property_static(name, fget, fset,
is_method(*
this), extra...);
1415 template <
typename Getter,
typename... Extra>
1417 return def_property_static(name,
cpp_function(fget), fset, return_value_policy::reference, extra...);
1421 template <
typename... Extra>
1423 static_assert( 0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
1424 "Argument annotations are not allowed for properties");
1425 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1426 auto *rec_active = rec_fget;
1428 char *doc_prev = rec_fget->doc;
1429 detail::process_attributes<Extra...>::init(extra..., rec_fget);
1430 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1432 rec_fget->doc = strdup(rec_fget->doc);
1436 char *doc_prev = rec_fset->doc;
1437 detail::process_attributes<Extra...>::init(extra..., rec_fset);
1438 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1440 rec_fset->doc = strdup(rec_fset->doc);
1442 if (! rec_active) rec_active = rec_fset;
1444 def_property_static_impl(name, fget, fset, rec_active);
1450 template <
typename T>
1451 static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1452 const holder_type * ,
const std::enable_shared_from_this<T> * ) {
1454 auto sh = std::dynamic_pointer_cast<
typename holder_type::element_type>(
1455 v_h.value_ptr<
type>()->shared_from_this());
1457 new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
1458 v_h.set_holder_constructed();
1460 }
catch (
const std::bad_weak_ptr &) {}
1462 if (!v_h.holder_constructed() && inst->owned) {
1463 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<
type>());
1464 v_h.set_holder_constructed();
1468 static void init_holder_from_existing(
const detail::value_and_holder &v_h,
1469 const holder_type *holder_ptr, std::true_type ) {
1470 new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1473 static void init_holder_from_existing(
const detail::value_and_holder &v_h,
1474 const holder_type *holder_ptr, std::false_type ) {
1475 new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1479 static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1480 const holder_type *holder_ptr,
const void * ) {
1482 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1483 v_h.set_holder_constructed();
1484 }
else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
1485 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<
type>());
1486 v_h.set_holder_constructed();
1495 auto v_h = inst->get_value_and_holder(detail::get_type_info(
typeid(
type)));
1496 if (!v_h.instance_registered()) {
1497 register_instance(inst, v_h.value_ptr(), v_h.type);
1498 v_h.set_instance_registered();
1500 init_holder(inst, v_h, (
const holder_type *) holder_ptr, v_h.value_ptr<
type>());
1504 static void dealloc(detail::value_and_holder &v_h) {
1512 if (v_h.holder_constructed()) {
1513 v_h.holder<holder_type>().~holder_type();
1514 v_h.set_holder_constructed(
false);
1517 detail::call_operator_delete(v_h.value_ptr<
type>(),
1518 v_h.type->type_size,
1519 v_h.type->type_align
1522 v_h.value_ptr() =
nullptr;
1525 static detail::function_record *get_function_record(
handle h) {
1526 h = detail::get_function(h);
1527 return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.
ptr()))
1533 template <
typename... Args> detail::initimpl::constructor<Args...> init() {
return {}; }
1536 template <
typename... Args> detail::initimpl::alias_constructor<Args...> init_alias() {
return {}; }
1539 template <
typename Func,
typename Ret = detail::initimpl::factory<Func>>
1540 Ret init(Func &&f) {
return {std::forward<Func>(f)}; }
1544 template <
typename CFunc,
typename AFunc,
typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1545 Ret init(CFunc &&c, AFunc &&a) {
1546 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1551 template <
typename GetState,
typename SetState>
1552 detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
1553 return {std::forward<GetState>(g), std::forward<SetState>(s)};
1556 PYBIND11_NAMESPACE_BEGIN(detail)
1559 dict entries = arg.get_type().attr(
"__entries");
1560 for (
auto kv : entries) {
1562 return pybind11::str(kv.first);
1570 PYBIND11_NOINLINE
void init(
bool is_arithmetic,
bool is_convertible) {
1571 m_base.attr(
"__entries") =
dict();
1572 auto property =
handle((PyObject *) &PyProperty_Type);
1573 auto static_property =
handle((PyObject *) get_internals().static_property_type);
1576 [](
object arg) ->
str {
1578 object type_name = type.attr(
"__name__");
1579 return pybind11::str(
"<{}.{}: {}>").format(type_name, enum_name(arg),
int_(arg));
1588 return pybind11::str(
"{}.{}").format(type_name, enum_name(arg));
1593 [](
handle arg) -> std::string {
1594 std::string docstring;
1595 dict entries = arg.attr(
"__entries");
1596 if (((PyTypeObject *) arg.
ptr())->tp_doc)
1597 docstring += std::string(((PyTypeObject *) arg.
ptr())->tp_doc) +
"\n\n";
1598 docstring +=
"Members:";
1599 for (
auto kv : entries) {
1600 auto key = std::string(pybind11::str(kv.first));
1601 auto comment = kv.second[
int_(1)];
1602 docstring +=
"\n\n " + key;
1603 if (!comment.is_none())
1604 docstring +=
" : " + (std::string) pybind11::str(comment);
1610 m_base.attr(
"__members__") = static_property(
cpp_function(
1612 dict entries = arg.attr(
"__entries"), m;
1613 for (
auto kv : entries)
1614 m[kv.first] = kv.second[
int_(0)];
1616 }, name(
"__members__")),
none(),
none(),
""
1619 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
1620 m_base.attr(op) = cpp_function( \
1621 [](object a, object b) { \
1622 if (!type::handle_of(a).is(type::handle_of(b))) \
1626 name(op), is_method(m_base))
1628 #define PYBIND11_ENUM_OP_CONV(op, expr) \
1629 m_base.attr(op) = cpp_function( \
1630 [](object a_, object b_) { \
1631 int_ a(a_), b(b_); \
1634 name(op), is_method(m_base))
1636 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
1637 m_base.attr(op) = cpp_function( \
1638 [](object a_, object b) { \
1642 name(op), is_method(m_base))
1644 if (is_convertible) {
1645 PYBIND11_ENUM_OP_CONV_LHS(
"__eq__", !b.is_none() && a.equal(b));
1646 PYBIND11_ENUM_OP_CONV_LHS(
"__ne__", b.is_none() || !a.equal(b));
1648 if (is_arithmetic) {
1649 PYBIND11_ENUM_OP_CONV(
"__lt__", a < b);
1650 PYBIND11_ENUM_OP_CONV(
"__gt__", a > b);
1651 PYBIND11_ENUM_OP_CONV(
"__le__", a <= b);
1652 PYBIND11_ENUM_OP_CONV(
"__ge__", a >= b);
1653 PYBIND11_ENUM_OP_CONV(
"__and__", a & b);
1654 PYBIND11_ENUM_OP_CONV(
"__rand__", a & b);
1655 PYBIND11_ENUM_OP_CONV(
"__or__", a | b);
1656 PYBIND11_ENUM_OP_CONV(
"__ror__", a | b);
1657 PYBIND11_ENUM_OP_CONV(
"__xor__", a ^ b);
1658 PYBIND11_ENUM_OP_CONV(
"__rxor__", a ^ b);
1660 [](
object arg) {
return ~(
int_(arg)); }, name(
"__invert__"),
is_method(m_base));
1663 PYBIND11_ENUM_OP_STRICT(
"__eq__",
int_(a).equal(
int_(b)),
return false);
1664 PYBIND11_ENUM_OP_STRICT(
"__ne__", !
int_(a).equal(
int_(b)),
return true);
1666 if (is_arithmetic) {
1667 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
1668 PYBIND11_ENUM_OP_STRICT(
"__lt__",
int_(a) <
int_(b), PYBIND11_THROW);
1669 PYBIND11_ENUM_OP_STRICT(
"__gt__",
int_(a) >
int_(b), PYBIND11_THROW);
1670 PYBIND11_ENUM_OP_STRICT(
"__le__",
int_(a) <=
int_(b), PYBIND11_THROW);
1671 PYBIND11_ENUM_OP_STRICT(
"__ge__",
int_(a) >=
int_(b), PYBIND11_THROW);
1672 #undef PYBIND11_THROW
1676 #undef PYBIND11_ENUM_OP_CONV_LHS
1677 #undef PYBIND11_ENUM_OP_CONV
1678 #undef PYBIND11_ENUM_OP_STRICT
1681 [](
object arg) {
return int_(arg); }, name(
"__getstate__"),
is_method(m_base));
1684 [](
object arg) {
return int_(arg); }, name(
"__hash__"),
is_method(m_base));
1687 PYBIND11_NOINLINE
void value(
char const* name_,
object value,
const char *
doc =
nullptr) {
1688 dict entries = m_base.attr(
"__entries");
1690 if (entries.contains(name)) {
1691 std::string type_name = (std::string)
str(m_base.attr(
"__name__"));
1692 throw value_error(type_name +
": element \"" + std::string(name_) +
"\" already exists!");
1695 entries[name] = std::make_pair(value,
doc);
1696 m_base.attr(name) = value;
1699 PYBIND11_NOINLINE
void export_values() {
1700 dict entries = m_base.attr(
"__entries");
1701 for (
auto kv : entries)
1702 m_parent.attr(kv.first) = kv.second[
int_(0)];
1709 PYBIND11_NAMESPACE_END(detail)
1717 using Base::def_property_readonly;
1718 using Base::def_property_readonly_static;
1719 using Scalar =
typename std::underlying_type<Type>::type;
1721 template <
typename... Extra>
1722 enum_(
const handle &scope,
const char *name,
const Extra&... extra)
1723 :
class_<Type>(scope, name, extra...), m_base(*
this, scope) {
1724 constexpr
bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
1725 constexpr
bool is_convertible = std::is_convertible<Type, Scalar>::value;
1726 m_base.init(is_arithmetic, is_convertible);
1728 def(init([](Scalar i) {
return static_cast<Type
>(i); }));
1729 def(
"__int__", [](Type value) {
return (Scalar) value; });
1730 #if PY_MAJOR_VERSION < 3
1731 def(
"__long__", [](Type value) {
return (Scalar) value; });
1733 #if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 8)
1734 def(
"__index__", [](Type value) {
return (Scalar) value; });
1738 [](detail::value_and_holder &v_h, Scalar arg) {
1739 detail::initimpl::setstate<Base>(v_h,
static_cast<Type
>(arg),
1740 Py_TYPE(v_h.inst) != v_h.type->type); },
1741 detail::is_new_style_constructor(),
1742 pybind11::name(
"__setstate__"),
is_method(*
this));
1752 enum_&
value(
char const* name, Type value,
const char *
doc =
nullptr) {
1753 m_base.
value(name, pybind11::cast(value, return_value_policy::copy),
doc);
1758 detail::enum_base m_base;
1761 PYBIND11_NAMESPACE_BEGIN(detail)
1764 inline
void keep_alive_impl(
handle nurse,
handle patient) {
1765 if (!nurse || !patient)
1766 pybind11_fail(
"Could not activate keep_alive!");
1768 if (patient.is_none() || nurse.is_none())
1771 auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
1772 if (!tinfo.empty()) {
1775 add_patient(nurse.ptr(), patient.ptr());
1784 weakref wr(nurse, disable_lifesupport);
1787 (void) wr.release();
1791 PYBIND11_NOINLINE
inline void keep_alive_impl(
size_t Nurse,
size_t Patient, function_call &call,
handle ret) {
1792 auto get_arg = [&](
size_t n) {
1795 else if (n == 1 && call.init_self)
1796 return call.init_self;
1797 else if (n <= call.args.size())
1798 return call.args[n - 1];
1802 keep_alive_impl(get_arg(Nurse), get_arg(Patient));
1805 inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *
type) {
1806 auto res = get_internals().registered_types_py
1807 #ifdef __cpp_lib_unordered_map_try_emplace
1810 .emplace(type, std::vector<detail::type_info *>());
1816 get_internals().registered_types_py.erase(type);
1824 template <
typename Iterator,
typename Sentinel,
bool KeyIterator, return_value_policy Policy>
1831 PYBIND11_NAMESPACE_END(detail)
1834 template <return_value_policy Policy = return_value_policy::reference_internal,
1837 typename ValueType = decltype(*std::declval<Iterator>()),
1839 iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1840 typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
1842 if (!detail::get_type_info(
typeid(state),
false)) {
1844 .def(
"__iter__", [](state &s) -> state& {
return s; })
1845 .def(
"__next__", [](state &s) -> ValueType {
1846 if (!s.first_or_done)
1849 s.first_or_done =
false;
1850 if (s.it == s.end) {
1851 s.first_or_done =
true;
1852 throw stop_iteration();
1855 }, std::forward<Extra>(extra)..., Policy);
1858 return cast(state{first, last,
true});
1863 template <return_value_policy Policy = return_value_policy::reference_internal,
1866 typename KeyType = decltype((*std::declval<Iterator>()).first),
1868 iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1869 using state = detail::iterator_state<Iterator, Sentinel, true, Policy>;
1871 if (!detail::get_type_info(
typeid(state),
false)) {
1873 .def(
"__iter__", [](state &s) -> state& {
return s; })
1874 .def(
"__next__", [](state &s) -> KeyType {
1875 if (!s.first_or_done)
1878 s.first_or_done =
false;
1879 if (s.it == s.end) {
1880 s.first_or_done =
true;
1881 throw stop_iteration();
1883 return (*s.it).first;
1884 }, std::forward<Extra>(extra)..., Policy);
1887 return cast(state{first, last,
true});
1892 template <return_value_policy Policy = return_value_policy::reference_internal,
1893 typename Type,
typename... Extra>
iterator make_iterator(Type &value, Extra&&... extra) {
1894 return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
1899 template <return_value_policy Policy = return_value_policy::reference_internal,
1900 typename Type,
typename... Extra>
iterator make_key_iterator(Type &value, Extra&&... extra) {
1901 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
1904 template <
typename InputType,
typename OutputType>
void implicitly_convertible() {
1907 set_flag(
bool &flag) : flag(flag) { flag =
true; }
1908 ~set_flag() { flag =
false; }
1910 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
1911 static bool currently_used =
false;
1914 set_flag flag_helper(currently_used);
1915 if (!detail::make_caster<InputType>().load(obj,
false))
1919 PyObject *result = PyObject_Call((PyObject *) type,
args.
ptr(),
nullptr);
1920 if (result ==
nullptr)
1925 if (
auto tinfo = detail::get_type_info(
typeid(OutputType)))
1926 tinfo->implicit_conversions.push_back(implicit_caster);
1928 pybind11_fail(
"implicitly_convertible: Unable to find type " + type_id<OutputType>());
1931 template <
typename ExceptionTranslator>
1932 void register_exception_translator(ExceptionTranslator&& translator) {
1933 detail::get_internals().registered_exception_translators.push_front(
1934 std::forward<ExceptionTranslator>(translator));
1944 template <
typename type>
1949 std::string full_name = scope.attr(
"__name__").
cast<std::string>() +
1950 std::string(
".") + name;
1951 m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()),
base.ptr(), NULL);
1952 if (hasattr(scope,
"__dict__") && scope.attr(
"__dict__").contains(name))
1953 pybind11_fail(
"Error during initialization: multiple incompatible "
1954 "definitions with name \"" + std::string(name) +
"\"");
1955 scope.attr(name) = *
this;
1959 void operator()(
const char *message) {
1960 PyErr_SetString(m_ptr, message);
1964 PYBIND11_NAMESPACE_BEGIN(detail)
1968 template <typename CppException>
1970 PYBIND11_NAMESPACE_END(detail)
1978 template <typename CppException>
1982 auto &ex = detail::get_exception_object<CppException>();
1985 register_exception_translator([](std::exception_ptr p) {
1988 std::rethrow_exception(p);
1989 }
catch (
const CppException &e) {
1990 detail::get_exception_object<CppException>()(e.what());
1996 PYBIND11_NAMESPACE_BEGIN(detail)
1998 auto strings =
tuple(args.size());
1999 for (
size_t i = 0; i < args.size(); ++i) {
2000 strings[i] =
str(args[i]);
2002 auto sep = kwargs.contains(
"sep") ? kwargs[
"sep"] : cast(
" ");
2003 auto line = sep.attr(
"join")(strings);
2006 if (kwargs.contains(
"file")) {
2007 file = kwargs[
"file"].cast<
object>();
2020 auto write = file.attr(
"write");
2022 write(kwargs.contains(
"end") ? kwargs[
"end"] : cast(
"\n"));
2024 if (kwargs.contains(
"flush") && kwargs[
"flush"].cast<
bool>())
2025 file.attr(
"flush")();
2027 PYBIND11_NAMESPACE_END(detail)
2029 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
2030 void print(Args &&...args) {
2031 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
2032 detail::print(c.args(), c.kwargs());
2035 #if defined(WITH_THREAD) && !defined(PYPY_VERSION)
2062 auto const &
internals = detail::get_internals();
2063 tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(
internals.tstate);
2071 tstate = PyGILState_GetThisThreadState();
2075 tstate = PyThreadState_New(
internals.istate);
2076 #if !defined(NDEBUG)
2078 pybind11_fail(
"scoped_acquire: could not create thread state!");
2080 tstate->gilstate_counter = 0;
2081 PYBIND11_TLS_REPLACE_VALUE(
internals.tstate, tstate);
2083 release = detail::get_thread_state_unchecked() != tstate;
2088 #if defined(Py_DEBUG)
2089 PyInterpreterState *interp = tstate->interp;
2090 tstate->interp =
nullptr;
2092 PyEval_AcquireThread(tstate);
2093 #if defined(Py_DEBUG)
2094 tstate->interp = interp;
2102 ++tstate->gilstate_counter;
2105 PYBIND11_NOINLINE
void dec_ref() {
2106 --tstate->gilstate_counter;
2107 #if !defined(NDEBUG)
2108 if (detail::get_thread_state_unchecked() != tstate)
2109 pybind11_fail(
"scoped_acquire::dec_ref(): thread state must be current!");
2110 if (tstate->gilstate_counter < 0)
2111 pybind11_fail(
"scoped_acquire::dec_ref(): reference count underflow!");
2113 if (tstate->gilstate_counter == 0) {
2114 #if !defined(NDEBUG)
2116 pybind11_fail(
"scoped_acquire::dec_ref(): internal error!");
2118 PyThreadState_Clear(tstate);
2119 PyThreadState_DeleteCurrent();
2120 PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
2128 PyEval_SaveThread();
2131 PyThreadState *tstate =
nullptr;
2132 bool release =
true;
2141 const auto &
internals = detail::get_internals();
2142 tstate = PyEval_SaveThread();
2145 PYBIND11_TLS_DELETE_VALUE(key);
2151 PyEval_RestoreThread(tstate);
2153 auto key = detail::get_internals().tstate;
2154 PYBIND11_TLS_REPLACE_VALUE(key, tstate);
2158 PyThreadState *tstate;
2161 #elif defined(PYPY_VERSION)
2163 PyGILState_STATE state;
2170 PyThreadState *state;
2180 error_already_set::~error_already_set() {
2190 PYBIND11_NAMESPACE_BEGIN(detail)
2191 inline function get_type_override(const
void *this_ptr, const
type_info *this_type, const
char *name) {
2192 handle self = get_object_handle(this_ptr, this_type);
2196 auto key = std::make_pair(type.
ptr(), name);
2200 auto &cache = get_internals().inactive_override_cache;
2201 if (cache.find(key) != cache.end())
2204 function override = getattr(
self, name,
function());
2205 if (
override.is_cpp_function()) {
2212 #if !defined(PYPY_VERSION)
2213 PyFrameObject *frame = PyThreadState_Get()->frame;
2214 if (frame && (std::string)
str(frame->f_code->co_name) == name &&
2215 frame->f_code->co_argcount > 0) {
2216 PyFrame_FastToLocals(frame);
2217 PyObject *self_caller = PyDict_GetItem(
2218 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2219 if (self_caller ==
self.ptr())
2226 dict d; d[
"self"] =
self; d[
"name"] = pybind11::str(name);
2227 PyObject *result = PyRun_String(
2229 "frame = inspect.currentframe()\n"
2230 "if frame is not None:\n"
2231 " frame = frame.f_back\n"
2232 " if frame is not None and str(frame.f_code.co_name) == name and "
2233 "frame.f_code.co_argcount > 0:\n"
2234 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2235 " if self_caller == self:\n"
2237 Py_file_input, d.
ptr(), d.
ptr());
2238 if (result ==
nullptr)
2240 if (d[
"self"].is_none())
2247 PYBIND11_NAMESPACE_END(detail)
2257 template <class T> function get_override(const T *this_ptr, const
char *name) {
2258 auto tinfo = detail::get_type_info(
typeid(T));
2259 return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
2262 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
2264 pybind11::gil_scoped_acquire gil; \
2265 pybind11::function override = pybind11::get_override(static_cast<const cname *>(this), name); \
2267 auto o = override(__VA_ARGS__); \
2268 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
2269 static pybind11::detail::override_caster_t<ret_type> caster; \
2270 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
2272 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2293 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
2295 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2296 return cname::fn(__VA_ARGS__); \
2303 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
2305 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2306 pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
2333 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
2334 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2340 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
2341 PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2346 PYBIND11_DEPRECATED(
"get_type_overload has been deprecated")
2347 inline function get_type_overload(const
void *this_ptr, const detail::
type_info *this_type, const
char *name) {
2348 return detail::get_type_override(this_ptr, this_type, name);
2352 inline function get_overload(
const T *this_ptr,
const char *name) {
2353 return get_override(this_ptr, name);
2356 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
2357 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
2358 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
2359 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
2360 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
2361 PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
2362 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
2363 PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
2364 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2365 PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
2367 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
2369 #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
2370 # pragma warning(pop)
2371 #elif defined(__GNUG__) && !defined(__clang__)
2372 # pragma GCC diagnostic pop
list bases
List of base classes of the newly created type.
bool multiple_inheritance
Multiple inheritance marker.
Annotation for parent scope.
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, if possible.
class_ & def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference by default.
Annotation for documentation.
void mark_parents_nonsimple(PyTypeObject *value)
Helper function which tags all parents of a type using mult. inheritance.
void initialize_generic(detail::function_record *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)
enum_ & export_values()
Export enumeration entries into the parent scope.
const handle & dec_ref() const &
Wrapper for Python extension modules.
static PyObject * dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in)
Main dispatch logic for calls to functions bound using pybind11.
bool is_method
True if this is a method.
Binds C++ enumerations and enumeration classes to Python.
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 module_ import(const char *name)
Import and return a module or throws error_already_set.
void initialize(Func &&f, Return(*)(Args...), const Extra &...extra)
Special internal constructor for functors, lambda functions, etc.
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.
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof') ...
void *(* operator_new)(size_t)
The global operator new can be overridden with a class-specific variant.
size_t type_align
What is the alignment of the underlying C++ type?
static void init_instance(detail::instance *inst, const void *holder_ptr)
enum_ & value(char const *name, Type value, const char *doc=nullptr)
Add an enumeration entry.
std::vector< argument_record > args
List of registered keyword arguments.
class_ & def_property_readonly(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
cpp_function(Return(Class::*f)(Arg...) const &, const Extra &...extra)
function_record * next
Pointer to next overload.
bool has_args
True if the function has a '*args' argument.
const char * name
Argument name.
object name() const
Return the function name.
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.
static void dealloc(detail::value_and_holder &v_h)
Deallocates an instance; via holder, if constructed; otherwise via operator delete.
cpp_function(Func &&f, const Extra &...extra)
Construct a cpp_function from a lambda function (possibly with internal state)
module_ & def(const char *name_, Func &&f, const Extra &...extra)
size_t holder_size
How large is the type's holder?
static module_ create_extension_module(const char *name, const char *doc, module_def *def)
bool convert
True if the argument is allowed to convert when loading.
cpp_function(Return(Class::*f)(Arg...)&, const Extra &...extra)
PyObject * ptr() const
Return the underlying PyObject * pointer.
Recursively iterate over variadic template arguments.
void(* init_instance)(instance *, const void *)
Function pointer to class_<..>::init_instance.
const handle & inc_ref() const &
Helper type to replace 'void' in some expressions.
const char * name
Name of the class.
PYBIND11_NOINLINE detail::function_record * make_function_record()
Space optimization: don't inline this frequently instantiated fragment.
module_ def_submodule(const char *name, const char *doc=nullptr)
bool is_new_style_constructor
True if this is a new-style __init__ defined in detail/init.h
static void destruct(detail::function_record *rec)
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.
value_and_holder get_value_and_holder(const type_info *find_type=nullptr, bool throw_if_missing=true)
Special data structure which (temporarily) holds metadata about a bound class.
class_ & def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
std::uint16_t nargs_pos_only
Number of leading arguments (counted in nargs) that are positional-only.
RAII wrapper that temporarily clears any Python error state.
handle(* impl)(function_call &)
Pointer to lambda function which converts arguments and performs the actual call. ...
bool none
True if None is allowed when loading.
class_ & def_property_readonly_static(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
cpp_function(Return(Class::*f)(Arg...), const Extra &...extra)
Construct a cpp_function from a class method (non-const, no ref-qualifier)
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
bool has_kwargs
True if the function has a '**kwargs' argument.
void reload()
Reload the module or throws error_already_set.
bool default_holder
Is the default (unique_ptr) holder type used?
PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite=false)
class_ & def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
Uses return_value_policy::reference by default.
Annotation for function names.
Annotation indicating that a class derives from another given type.
Information record describing a Python buffer object.
cpp_function(Return(Class::*f)(Arg...) const, const Extra &...extra)
Construct a cpp_function from a class method (const, no ref-qualifier)
Generic support for creating new Python heap types.
std::uint16_t nargs
Number of arguments (including py::args and/or py::kwargs, if present)
std::uint16_t nargs_kw_only
Number of trailing arguments (counted in nargs) that are keyword-only.
class_ & def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
Annotation indicating that a function is an overload associated with a given "sibling".
static handle handle_of()
Internal data structure which holds metadata about a bound function (signature, overloads, etc.)
handle scope
Handle to the parent scope.
Internal data structure which holds metadata about a keyword argument.
void(* dealloc)(detail::value_and_holder &)
Function pointer to class_<..>::dealloc.
size_t type_size
How large is the underlying C++ type?
bool module_local
Is the class definition local to the module shared object?