File indexing completed on 2026-08-01 09:16:34
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011 #pragma once
0012 #include "detail/class.h"
0013 #include "detail/dynamic_raw_ptr_cast_if_possible.h"
0014 #include "detail/exception_translation.h"
0015 #include "detail/function_record_pyobject.h"
0016 #include "detail/init.h"
0017 #include "detail/native_enum_data.h"
0018 #include "detail/using_smart_holder.h"
0019 #include "attr.h"
0020 #include "gil.h"
0021 #include "gil_safe_call_once.h"
0022 #include "options.h"
0023 #include "trampoline_self_life_support.h"
0024 #include "typing.h"
0025
0026 #include <cassert>
0027 #include <cstdlib>
0028 #include <cstring>
0029 #include <memory>
0030 #include <new>
0031 #include <stack>
0032 #include <string>
0033 #include <utility>
0034 #include <vector>
0035
0036
0037
0038 #if defined(__clang_major__) && __clang_major__ < 14
0039 PYBIND11_WARNING_DISABLE_CLANG("-Wgnu-zero-variadic-macro-arguments")
0040 #endif
0041
0042 #if defined(__GNUG__) && !defined(__clang__)
0043 # include <cxxabi.h>
0044 #endif
0045
0046 #if defined(__cpp_if_constexpr) && __cpp_if_constexpr >= 201606
0047 # define PYBIND11_MAYBE_CONSTEXPR constexpr
0048 #else
0049 # define PYBIND11_MAYBE_CONSTEXPR
0050 #endif
0051
0052 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0053
0054
0055
0056
0057
0058
0059
0060
0061 #if defined(__GNUC__) && __GNUC__ == 7
0062 PYBIND11_WARNING_DISABLE_GCC("-Wnoexcept-type")
0063 #endif
0064
0065 PYBIND11_WARNING_DISABLE_MSVC(4127)
0066
0067 PYBIND11_NAMESPACE_BEGIN(detail)
0068
0069 inline std::string replace_newlines_and_squash(const char *text) {
0070 const char *whitespaces = " \t\n\r\f\v";
0071 std::string result(text);
0072 bool previous_is_whitespace = false;
0073
0074 if (result.size() >= 2) {
0075
0076 char first_char = result[0];
0077 char last_char = result[result.size() - 1];
0078 if (first_char == last_char && first_char == '\'') {
0079 return result;
0080 }
0081 }
0082 result.clear();
0083
0084
0085 while (*text != '\0') {
0086 if (std::strchr(whitespaces, *text)) {
0087 if (!previous_is_whitespace) {
0088 result += ' ';
0089 previous_is_whitespace = true;
0090 }
0091 } else {
0092 result += *text;
0093 previous_is_whitespace = false;
0094 }
0095 ++text;
0096 }
0097
0098
0099 const size_t str_begin = result.find_first_not_of(whitespaces);
0100 if (str_begin == std::string::npos) {
0101 return "";
0102 }
0103
0104 const size_t str_end = result.find_last_not_of(whitespaces);
0105 const size_t str_range = str_end - str_begin + 1;
0106
0107 return result.substr(str_begin, str_range);
0108 }
0109
0110
0111 inline std::string generate_function_signature(const char *type_caster_name_field,
0112 detail::function_record *func_rec,
0113 const std::type_info *const *types,
0114 size_t &type_index,
0115 size_t &arg_index) {
0116 std::string signature;
0117 bool is_starred = false;
0118
0119
0120
0121 std::stack<bool> is_return_value({false});
0122
0123
0124 std::string special_chars("!@%{}-");
0125 for (const auto *pc = type_caster_name_field; *pc != '\0'; ++pc) {
0126 const auto c = *pc;
0127 if (c == '{') {
0128
0129
0130 is_starred = *(pc + 1) == '@' && *(pc + 2) == '*';
0131 if (is_starred) {
0132 continue;
0133 }
0134
0135
0136 if (!func_rec->has_args && arg_index == func_rec->nargs_pos) {
0137 signature += "*, ";
0138 }
0139 if (arg_index < func_rec->args.size() && func_rec->args[arg_index].name) {
0140 signature += func_rec->args[arg_index].name;
0141 } else if (arg_index == 0 && func_rec->is_method) {
0142 signature += "self";
0143 } else {
0144 signature += "arg" + std::to_string(arg_index - (func_rec->is_method ? 1 : 0));
0145 }
0146 signature += ": ";
0147 } else if (c == '}') {
0148
0149 if (!is_starred && arg_index < func_rec->args.size()
0150 && func_rec->args[arg_index].descr) {
0151 signature += " = ";
0152 signature += detail::replace_newlines_and_squash(func_rec->args[arg_index].descr);
0153 }
0154
0155
0156 if (func_rec->nargs_pos_only > 0 && (arg_index + 1) == func_rec->nargs_pos_only) {
0157 signature += ", /";
0158 }
0159 if (!is_starred) {
0160 arg_index++;
0161 }
0162 } else if (c == '%') {
0163 const std::type_info *t = types[type_index++];
0164 if (!t) {
0165 pybind11_fail("Internal error while parsing type signature (1)");
0166 }
0167 if (auto *tinfo = detail::get_type_info(*t)) {
0168 handle th(reinterpret_cast<PyObject *>(tinfo->type));
0169 signature += th.attr("__module__").cast<std::string>() + "."
0170 + th.attr("__qualname__").cast<std::string>();
0171 } else if (auto th = detail::global_internals_native_enum_type_map_get_item(*t)) {
0172 signature += th.attr("__module__").cast<std::string>() + "."
0173 + th.attr("__qualname__").cast<std::string>();
0174 } else if (func_rec->is_new_style_constructor && arg_index == 0) {
0175
0176
0177 signature += func_rec->scope.attr("__module__").cast<std::string>() + "."
0178 + func_rec->scope.attr("__qualname__").cast<std::string>();
0179 } else {
0180 signature += detail::quote_cpp_type_name(detail::clean_type_id(t->name()));
0181 }
0182 } else if (c == '!' && special_chars.find(*(pc + 1)) != std::string::npos) {
0183
0184 signature += *++pc;
0185 } else if (c == '@') {
0186
0187
0188 if (*(pc + 1) == '^') {
0189 is_return_value.emplace(false);
0190 ++pc;
0191 continue;
0192 }
0193 if (*(pc + 1) == '$') {
0194 is_return_value.emplace(true);
0195 ++pc;
0196 continue;
0197 }
0198 if (*(pc + 1) == '!') {
0199 is_return_value.pop();
0200 ++pc;
0201 continue;
0202 }
0203
0204
0205
0206 ++pc;
0207 if (!is_return_value.top()
0208 && (!(arg_index < func_rec->args.size() && !func_rec->args[arg_index].convert))) {
0209 while (*pc != '\0' && *pc != '@') {
0210 signature += *pc++;
0211 }
0212 if (*pc == '@') {
0213 ++pc;
0214 }
0215 while (*pc != '\0' && *pc != '@') {
0216 ++pc;
0217 }
0218 } else {
0219 while (*pc != '\0' && *pc != '@') {
0220 ++pc;
0221 }
0222 if (*pc == '@') {
0223 ++pc;
0224 }
0225 while (*pc != '\0' && *pc != '@') {
0226 signature += *pc++;
0227 }
0228 }
0229 } else {
0230 if (c == '-' && *(pc + 1) == '>') {
0231 is_return_value.emplace(true);
0232 }
0233 signature += c;
0234 }
0235 }
0236 return signature;
0237 }
0238
0239 template <typename T>
0240 inline std::string generate_type_signature() {
0241 static constexpr auto caster_name_field = make_caster<T>::name;
0242 PYBIND11_DESCR_CONSTEXPR auto descr_types = decltype(caster_name_field)::types();
0243
0244
0245 auto func_rec = function_record();
0246 size_t type_index = 0;
0247 size_t arg_index = 0;
0248 return generate_function_signature(
0249 caster_name_field.text, &func_rec, descr_types.data(), type_index, arg_index);
0250 }
0251
0252 #if defined(_MSC_VER)
0253 # define PYBIND11_COMPAT_STRDUP _strdup
0254 #else
0255 # define PYBIND11_COMPAT_STRDUP strdup
0256 #endif
0257
0258 #define PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR \
0259 detail::const_name("(") + cast_in::arg_names + detail::const_name(") -> ") + cast_out::name
0260
0261
0262
0263
0264 template <typename cast_in, typename cast_out>
0265 class ReadableFunctionSignature {
0266 public:
0267 using sig_type = decltype(PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR);
0268
0269 private:
0270
0271
0272
0273
0274 static constexpr sig_type sig() { return PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR; }
0275
0276 public:
0277 static constexpr sig_type kSig = sig();
0278
0279
0280
0281 #if !defined(_MSC_VER)
0282 using types_type = decltype(sig_type::types());
0283 static constexpr types_type kTypes = sig_type::types();
0284 #endif
0285 };
0286 #undef PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR
0287
0288
0289
0290 #if !defined(PYBIND11_CPP17)
0291 template <typename cast_in, typename cast_out>
0292 constexpr typename ReadableFunctionSignature<cast_in, cast_out>::sig_type
0293 ReadableFunctionSignature<cast_in, cast_out>::kSig;
0294 # if !defined(_MSC_VER)
0295 template <typename cast_in, typename cast_out>
0296 constexpr typename ReadableFunctionSignature<cast_in, cast_out>::types_type
0297 ReadableFunctionSignature<cast_in, cast_out>::kTypes;
0298 # endif
0299 #endif
0300
0301 PYBIND11_NAMESPACE_END(detail)
0302
0303
0304 class cpp_function : public function {
0305 public:
0306 cpp_function() = default;
0307
0308 cpp_function(std::nullptr_t) {}
0309 cpp_function(std::nullptr_t, const is_setter &) {}
0310
0311
0312 template <typename Return, typename... Args, typename... Extra>
0313
0314 cpp_function(Return (*f)(Args...), const Extra &...extra) {
0315 initialize(f, f, extra...);
0316 }
0317
0318
0319 template <typename Func,
0320 typename... Extra,
0321 typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
0322
0323 cpp_function(Func &&f, const Extra &...extra) {
0324 initialize(
0325 std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...);
0326 }
0327
0328
0329 template <typename Return, typename Class, typename... Arg, typename... Extra>
0330
0331 cpp_function(Return (Class::*f)(Arg...), const Extra &...extra) {
0332 initialize(
0333 [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0334 (Return (*)(Class *, Arg...)) nullptr,
0335 extra...);
0336 }
0337
0338
0339
0340
0341 template <typename Return, typename Class, typename... Arg, typename... Extra>
0342
0343 cpp_function(Return (Class::*f)(Arg...) &, const Extra &...extra) {
0344 initialize(
0345 [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0346 (Return (*)(Class *, Arg...)) nullptr,
0347 extra...);
0348 }
0349
0350
0351 template <typename Return, typename Class, typename... Arg, typename... Extra>
0352
0353 cpp_function(Return (Class::*f)(Arg...) const, const Extra &...extra) {
0354 initialize([f](const Class *c,
0355 Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0356 (Return (*)(const Class *, Arg...)) nullptr,
0357 extra...);
0358 }
0359
0360
0361
0362
0363 template <typename Return, typename Class, typename... Arg, typename... Extra>
0364
0365 cpp_function(Return (Class::*f)(Arg...) const &, const Extra &...extra) {
0366 initialize([f](const Class *c,
0367 Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0368 (Return (*)(const Class *, Arg...)) nullptr,
0369 extra...);
0370 }
0371
0372
0373 object name() const { return attr("__name__"); }
0374
0375 protected:
0376 struct InitializingFunctionRecordDeleter {
0377
0378
0379 void operator()(detail::function_record *rec) { destruct(rec, false); }
0380 };
0381 using unique_function_record
0382 = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
0383
0384
0385 PYBIND11_NOINLINE unique_function_record make_function_record() {
0386 return unique_function_record(new detail::function_record());
0387 }
0388
0389
0390 template <typename Func, typename Return, typename... Args, typename... Extra>
0391 void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) {
0392 using namespace detail;
0393 struct capture {
0394 remove_reference_t<Func> f;
0395
0396 static capture *from_data(void **data) {
0397 return PYBIND11_STD_LAUNDER(reinterpret_cast<capture *>(data));
0398 }
0399 };
0400
0401
0402
0403
0404 auto unique_rec = make_function_record();
0405 auto *rec = unique_rec.get();
0406
0407
0408 if (sizeof(capture) <= sizeof(rec->data)) {
0409
0410
0411
0412 PYBIND11_WARNING_PUSH
0413
0414 #if defined(__GNUG__) && __GNUC__ >= 6
0415 PYBIND11_WARNING_DISABLE_GCC("-Wplacement-new")
0416 #endif
0417
0418 new (capture::from_data(rec->data)) capture{std::forward<Func>(f)};
0419
0420 #if !PYBIND11_HAS_STD_LAUNDER
0421 PYBIND11_WARNING_DISABLE_GCC("-Wstrict-aliasing")
0422 #endif
0423
0424
0425
0426 if (!std::is_trivially_destructible<capture>::value) {
0427 rec->free_data = [](function_record *r) {
0428 auto data = capture::from_data(r->data);
0429 (void) data;
0430 data->~capture();
0431 };
0432 }
0433 PYBIND11_WARNING_POP
0434 } else {
0435 rec->data[0] = new capture{std::forward<Func>(f)};
0436 rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
0437 }
0438
0439
0440 using cast_in = argument_loader<Args...>;
0441 using cast_out
0442 = make_caster<conditional_t<std::is_void<Return>::value, void_type, Return>>;
0443
0444 static_assert(
0445 expected_num_args<Extra...>(
0446 sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
0447 "The number of argument annotations does not match the number of function arguments");
0448
0449
0450 rec->impl = [](function_call &call) -> handle {
0451 cast_in args_converter;
0452
0453
0454 if (!args_converter.load_args(call)) {
0455 return PYBIND11_TRY_NEXT_OVERLOAD;
0456 }
0457
0458
0459 process_attributes<Extra...>::precall(call);
0460
0461
0462 const auto *data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data
0463 : call.func.data[0]);
0464 auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
0465
0466
0467 return_value_policy policy
0468 = return_value_policy_override<Return>::policy(call.func.policy);
0469
0470
0471 using Guard = extract_guard_t<Extra...>;
0472
0473
0474 handle result;
0475 if (call.func.is_setter) {
0476 (void) std::move(args_converter).template call<Return, Guard>(cap->f);
0477 result = none().release();
0478 } else {
0479 result = cast_out::cast(
0480 std::move(args_converter).template call<Return, Guard>(cap->f),
0481 policy,
0482 call.parent);
0483 }
0484
0485
0486 process_attributes<Extra...>::postcall(call, result);
0487
0488 return result;
0489 };
0490
0491 rec->nargs_pos = cast_in::args_pos >= 0
0492 ? static_cast<std::uint16_t>(cast_in::args_pos)
0493 : sizeof...(Args) - cast_in::has_kwargs;
0494
0495 rec->has_args = cast_in::args_pos >= 0;
0496 rec->has_kwargs = cast_in::has_kwargs;
0497
0498
0499 process_attributes<Extra...>::init(extra..., rec);
0500
0501 {
0502 constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
0503 has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
0504 has_arg_annotations = any_of<is_keyword<Extra>...>::value;
0505 constexpr bool has_is_method = any_of<std::is_same<is_method, Extra>...>::value;
0506
0507 constexpr bool has_args = cast_in::args_pos >= 0;
0508 constexpr bool is_method_with_self_arg_only = has_is_method && !has_args;
0509 static_assert(has_arg_annotations || !has_kw_only_args,
0510 "py::kw_only requires the use of argument annotations");
0511 static_assert(((
0512 has_arg_annotations)
0513 || (
0514
0515
0516
0517 is_method_with_self_arg_only))
0518 || !has_pos_only_args,
0519 "py::pos_only requires the use of argument annotations (for docstrings "
0520 "and aligning the annotations to the argument)");
0521
0522 static_assert(constexpr_sum(is_kw_only<Extra>::value...) <= 1,
0523 "py::kw_only may be specified only once");
0524 static_assert(constexpr_sum(is_pos_only<Extra>::value...) <= 1,
0525 "py::pos_only may be specified only once");
0526 constexpr auto kw_only_pos = constexpr_first<is_kw_only, Extra...>();
0527 constexpr auto pos_only_pos = constexpr_first<is_pos_only, Extra...>();
0528 static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
0529 "py::pos_only must come before py::kw_only");
0530 }
0531
0532
0533
0534 static constexpr const auto &signature
0535 = detail::ReadableFunctionSignature<cast_in, cast_out>::kSig;
0536 #if !defined(_MSC_VER)
0537 static constexpr const auto &types
0538 = detail::ReadableFunctionSignature<cast_in, cast_out>::kTypes;
0539 #else
0540 PYBIND11_DESCR_CONSTEXPR auto types = std::decay<decltype(signature)>::type::types();
0541 #endif
0542
0543
0544
0545 initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));
0546
0547
0548 using FunctionType = Return (*)(Args...);
0549 constexpr bool is_function_ptr
0550 = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *);
0551 PYBIND11_ENSURE_PRECONDITION_FOR_FUNCTIONAL_H_PERFORMANCE_OPTIMIZATIONS(
0552 !is_function_ptr || std::is_standard_layout<capture>::value);
0553 if (is_function_ptr) {
0554 rec->is_stateless = true;
0555 rec->data[1]
0556 = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
0557 }
0558 }
0559
0560
0561
0562
0563 class strdup_guard {
0564 public:
0565 strdup_guard() = default;
0566 strdup_guard(const strdup_guard &) = delete;
0567 strdup_guard &operator=(const strdup_guard &) = delete;
0568
0569 ~strdup_guard() {
0570 for (auto *s : strings) {
0571 std::free(s);
0572 }
0573 }
0574 char *operator()(const char *s) {
0575 auto *t = PYBIND11_COMPAT_STRDUP(s);
0576 strings.push_back(t);
0577 return t;
0578 }
0579 void release() { strings.clear(); }
0580
0581 private:
0582 std::vector<char *> strings;
0583 };
0584
0585
0586 void initialize_generic(unique_function_record &&unique_rec,
0587 const char *text,
0588 const std::type_info *const *types,
0589 size_t args) {
0590
0591
0592
0593
0594 auto *rec = unique_rec.get();
0595
0596
0597
0598
0599
0600
0601
0602 strdup_guard guarded_strdup;
0603
0604
0605 rec->name = guarded_strdup(rec->name ? rec->name : "");
0606 if (rec->doc) {
0607 rec->doc = guarded_strdup(rec->doc);
0608 }
0609 for (auto &a : rec->args) {
0610 if (a.name) {
0611 a.name = guarded_strdup(a.name);
0612 }
0613 if (a.descr) {
0614 a.descr = guarded_strdup(a.descr);
0615 } else if (a.value) {
0616 a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());
0617 }
0618 }
0619
0620 rec->is_constructor = (std::strcmp(rec->name, "__init__") == 0)
0621 || (std::strcmp(rec->name, "__setstate__") == 0);
0622
0623 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
0624 if (rec->is_constructor && !rec->is_new_style_constructor) {
0625 const auto class_name
0626 = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
0627 const auto func_name = std::string(rec->name);
0628 PyErr_WarnEx(PyExc_FutureWarning,
0629 ("pybind11-bound class '" + class_name
0630 + "' is using an old-style "
0631 "placement-new '"
0632 + func_name
0633 + "' which has been deprecated. See "
0634 "the upgrade guide in pybind11's docs. This message is only visible "
0635 "when compiled in debug mode.")
0636 .c_str(),
0637 0);
0638 }
0639 #endif
0640
0641 size_t type_index = 0, arg_index = 0;
0642 std::string signature
0643 = detail::generate_function_signature(text, rec, types, type_index, arg_index);
0644
0645 if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] != nullptr) {
0646 pybind11_fail("Internal error while parsing type signature (2)");
0647 }
0648
0649 rec->signature = guarded_strdup(signature.c_str());
0650 rec->args.shrink_to_fit();
0651 rec->nargs = static_cast<std::uint16_t>(args);
0652
0653 if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) {
0654 rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
0655 }
0656
0657 detail::function_record *chain = nullptr, *chain_start = rec;
0658 if (rec->sibling) {
0659 if (PyCFunction_Check(rec->sibling.ptr())) {
0660 auto *self = PyCFunction_GET_SELF(rec->sibling.ptr());
0661 if (self == nullptr) {
0662 pybind11_fail(
0663 "initialize_generic: Unexpected nullptr from PyCFunction_GET_SELF");
0664 }
0665 chain = detail::function_record_ptr_from_PyObject(self);
0666 if (chain && !chain->scope.is(rec->scope)) {
0667
0668
0669 chain = nullptr;
0670 }
0671 }
0672
0673
0674 else if (!rec->sibling.is_none() && rec->name[0] != '_') {
0675 pybind11_fail("Cannot overload existing non-function object \""
0676 + std::string(rec->name) + "\" with a function of the same name");
0677 }
0678 }
0679
0680 if (!chain) {
0681
0682 rec->def = new PyMethodDef();
0683 std::memset(rec->def, 0, sizeof(PyMethodDef));
0684 rec->def->ml_name = rec->name;
0685 rec->def->ml_meth
0686 = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher));
0687 rec->def->ml_flags = METH_FASTCALL | METH_KEYWORDS;
0688
0689 object py_func_rec = detail::function_record_PyObject_New();
0690 (reinterpret_cast<detail::function_record_PyObject *>(py_func_rec.ptr()))->cpp_func_rec
0691 = unique_rec.release();
0692 guarded_strdup.release();
0693
0694 object scope_module = detail::get_scope_module(rec->scope);
0695 m_ptr = PyCFunction_NewEx(rec->def, py_func_rec.ptr(), scope_module.ptr());
0696 if (!m_ptr) {
0697 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
0698 }
0699 } else {
0700
0701 m_ptr = rec->sibling.ptr();
0702 inc_ref();
0703 if (chain->is_method != rec->is_method) {
0704 pybind11_fail(
0705 "overloading a method with both static and instance methods is not supported; "
0706 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
0707 "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more "
0708 "details"
0709 #else
0710 "error while attempting to bind "
0711 + std::string(rec->is_method ? "instance" : "static") + " method "
0712 + std::string(pybind11::str(rec->scope.attr("__name__"))) + "."
0713 + std::string(rec->name) + signature
0714 #endif
0715 );
0716 }
0717
0718 if (rec->prepend) {
0719
0720
0721
0722 chain_start = rec;
0723 rec->next = chain;
0724 auto *py_func_rec = reinterpret_cast<detail::function_record_PyObject *>(
0725 PyCFunction_GET_SELF(m_ptr));
0726 py_func_rec->cpp_func_rec = unique_rec.release();
0727 guarded_strdup.release();
0728 } else {
0729
0730 chain_start = chain;
0731 while (chain->next) {
0732 chain = chain->next;
0733 }
0734 chain->next = unique_rec.release();
0735 guarded_strdup.release();
0736 }
0737 }
0738
0739 std::string signatures;
0740 int index = 0;
0741
0742
0743 if (chain && options::show_function_signatures()
0744 && std::strcmp(rec->name, "_pybind11_conduit_v1_") != 0) {
0745
0746 signatures += rec->name;
0747 signatures += "(*args, **kwargs)\n";
0748 signatures += "Overloaded function.\n\n";
0749 }
0750
0751 bool first_user_def = true;
0752 for (auto *it = chain_start; it != nullptr; it = it->next) {
0753 if (options::show_function_signatures()
0754 && std::strcmp(rec->name, "_pybind11_conduit_v1_") != 0) {
0755 if (index > 0) {
0756 signatures += '\n';
0757 }
0758 if (chain) {
0759 signatures += std::to_string(++index) + ". ";
0760 }
0761 signatures += rec->name;
0762 signatures += it->signature;
0763 signatures += '\n';
0764 }
0765 if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) {
0766
0767
0768 if (!options::show_function_signatures()) {
0769 if (first_user_def) {
0770 first_user_def = false;
0771 } else {
0772 signatures += '\n';
0773 }
0774 }
0775 if (options::show_function_signatures()) {
0776 signatures += '\n';
0777 }
0778 signatures += it->doc;
0779 if (options::show_function_signatures()) {
0780 signatures += '\n';
0781 }
0782 }
0783 }
0784
0785 auto *func = reinterpret_cast<PyCFunctionObject *>(m_ptr);
0786
0787 auto *doc = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());
0788 std::free(const_cast<char *>(PYBIND11_PYCFUNCTION_GET_DOC(func)));
0789 PYBIND11_PYCFUNCTION_SET_DOC(func, doc);
0790
0791 if (rec->is_method) {
0792 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
0793 if (!m_ptr) {
0794 pybind11_fail(
0795 "cpp_function::cpp_function(): Could not allocate instance method object");
0796 }
0797 Py_DECREF(func);
0798 }
0799 }
0800
0801 friend void detail::function_record_PyTypeObject_methods::tp_dealloc_impl(PyObject *);
0802
0803
0804 static void destruct(detail::function_record *rec, bool free_strings = true) {
0805
0806
0807 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
0808 static bool is_zero = Py_GetVersion()[4] == '0';
0809 #endif
0810
0811 while (rec) {
0812 detail::function_record *next = rec->next;
0813 if (rec->free_data) {
0814 rec->free_data(rec);
0815 }
0816
0817
0818
0819 if (free_strings) {
0820 std::free(rec->name);
0821 std::free(rec->doc);
0822 std::free(rec->signature);
0823 for (auto &arg : rec->args) {
0824 std::free(const_cast<char *>(arg.name));
0825 std::free(const_cast<char *>(arg.descr));
0826 }
0827 }
0828 for (auto &arg : rec->args) {
0829 arg.value.dec_ref();
0830 }
0831 if (rec->def) {
0832 std::free(const_cast<char *>(rec->def->ml_doc));
0833
0834
0835
0836 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
0837 if (!is_zero) {
0838 delete rec->def;
0839 }
0840 #else
0841 delete rec->def;
0842 #endif
0843 }
0844 delete rec;
0845 rec = next;
0846 }
0847 }
0848
0849
0850 static PyObject *
0851 dispatcher(PyObject *self, PyObject *const *args_in_arr, size_t nargsf, PyObject *kwnames_in) {
0852 using namespace detail;
0853 const function_record *overloads = function_record_ptr_from_PyObject(self);
0854 assert(overloads != nullptr);
0855
0856
0857 const function_record *current_overload = overloads;
0858
0859
0860
0861 const auto n_args_in = static_cast<size_t>(PyVectorcall_NARGS(nargsf));
0862
0863 handle parent = n_args_in > 0 ? args_in_arr[0] : nullptr,
0864 result = PYBIND11_TRY_NEXT_OVERLOAD;
0865
0866 auto self_value_and_holder = value_and_holder();
0867 if (overloads->is_constructor) {
0868 if (!parent
0869 || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
0870 set_error(PyExc_TypeError,
0871 "__init__(self, ...) called with invalid or missing `self` argument");
0872 return nullptr;
0873 }
0874
0875 auto *const tinfo
0876 = get_type_info(reinterpret_cast<PyTypeObject *>(overloads->scope.ptr()));
0877 auto *const pi = reinterpret_cast<instance *>(parent.ptr());
0878 self_value_and_holder = pi->get_value_and_holder(tinfo, true);
0879
0880
0881
0882 if (self_value_and_holder.instance_registered()) {
0883 return none().release().ptr();
0884 }
0885 }
0886
0887 try {
0888
0889
0890
0891
0892 std::vector<function_call> second_pass;
0893
0894
0895 const bool overloaded
0896 = current_overload != nullptr && current_overload->next != nullptr;
0897
0898 for (; current_overload != nullptr; current_overload = current_overload->next) {
0899
0900
0901
0902
0903
0904
0905
0906
0907
0908
0909
0910
0911
0912
0913
0914
0915
0916
0917
0918
0919 const function_record &func = *current_overload;
0920 size_t num_args = func.nargs;
0921 if (func.has_args) {
0922 --num_args;
0923 }
0924 if (func.has_kwargs) {
0925 --num_args;
0926 }
0927 size_t pos_args = func.nargs_pos;
0928
0929 if (!func.has_args && n_args_in > pos_args) {
0930 continue;
0931 }
0932
0933 if (n_args_in < pos_args && func.args.size() < pos_args) {
0934 continue;
0935
0936 }
0937
0938 function_call call(func, parent);
0939
0940
0941 size_t args_to_copy = (std::min) (pos_args, n_args_in);
0942 size_t args_copied = 0;
0943
0944
0945 if (func.is_new_style_constructor) {
0946
0947
0948 if (self_value_and_holder) {
0949 self_value_and_holder.type->dealloc(self_value_and_holder);
0950 }
0951
0952 call.init_self = args_in_arr[0];
0953 call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
0954 call.args_convert.push_back(false);
0955 ++args_copied;
0956 }
0957
0958
0959 bool bad_arg = false;
0960 for (; args_copied < args_to_copy; ++args_copied) {
0961 const argument_record *arg_rec
0962 = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
0963
0964
0965
0966
0967
0968
0969 if (kwnames_in && arg_rec && arg_rec->name
0970 && keyword_index(kwnames_in, arg_rec->name) >= 0) {
0971 bad_arg = true;
0972 break;
0973 }
0974
0975 handle arg(args_in_arr[args_copied]);
0976 if (arg_rec && !arg_rec->none && arg.is_none()) {
0977 bad_arg = true;
0978 break;
0979 }
0980
0981 call.args.push_back(arg);
0982 call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
0983 }
0984 if (bad_arg) {
0985 continue;
0986 }
0987
0988
0989
0990 size_t positional_args_copied = args_copied;
0991
0992
0993 if (args_copied < func.nargs_pos_only) {
0994 for (; args_copied < func.nargs_pos_only; ++args_copied) {
0995 const auto &arg_rec = func.args[args_copied];
0996 if (arg_rec.value) {
0997 call.args.push_back(arg_rec.value);
0998 call.args_convert.push_back(arg_rec.convert);
0999 } else {
1000 break;
1001 }
1002 }
1003
1004 if (args_copied < func.nargs_pos_only) {
1005 continue;
1006 }
1007 }
1008
1009
1010 small_vector<bool, arg_vector_small_size> used_kwargs(
1011 kwnames_in ? static_cast<size_t>(PyTuple_GET_SIZE(kwnames_in)) : 0, false);
1012 size_t used_kwargs_count = 0;
1013 if (args_copied < num_args) {
1014 for (; args_copied < num_args; ++args_copied) {
1015 const auto &arg_rec = func.args[args_copied];
1016
1017 handle value;
1018 if (kwnames_in && arg_rec.name) {
1019 ssize_t i = keyword_index(kwnames_in, arg_rec.name);
1020 if (i >= 0) {
1021 value = args_in_arr[n_args_in + static_cast<size_t>(i)];
1022 used_kwargs.set(static_cast<size_t>(i), true);
1023 used_kwargs_count++;
1024 }
1025 }
1026
1027 if (!value) {
1028 value = arg_rec.value;
1029 if (!value) {
1030 break;
1031 }
1032 }
1033
1034 if (!arg_rec.none && value.is_none()) {
1035 break;
1036 }
1037
1038
1039
1040 if (func.has_args && call.args.size() == func.nargs_pos) {
1041 call.args.push_back(none());
1042 }
1043
1044 call.args.push_back(value);
1045 call.args_convert.push_back(arg_rec.convert);
1046 }
1047
1048 if (args_copied < num_args) {
1049 continue;
1050
1051 }
1052 }
1053
1054
1055 if (!func.has_kwargs && used_kwargs_count < used_kwargs.size()) {
1056 continue;
1057 }
1058
1059
1060 if (func.has_args) {
1061 if (positional_args_copied >= n_args_in) {
1062 call.args_ref = tuple(0);
1063 } else {
1064 size_t args_size = n_args_in - positional_args_copied;
1065 tuple extra_args(args_size);
1066 for (size_t i = 0; i < args_size; ++i) {
1067 extra_args[i] = args_in_arr[positional_args_copied + i];
1068 }
1069 call.args_ref = std::move(extra_args);
1070 }
1071 if (call.args.size() <= func.nargs_pos) {
1072 call.args.push_back(call.args_ref);
1073 } else {
1074 call.args[func.nargs_pos] = call.args_ref;
1075 }
1076 call.args_convert.push_back(false);
1077 }
1078
1079
1080 if (func.has_kwargs) {
1081 dict kwargs;
1082 for (size_t i = 0; i < used_kwargs.size(); ++i) {
1083 if (!used_kwargs[i]) {
1084
1085
1086 handle arg_in_arr = args_in_arr[n_args_in + i],
1087 kwname = PyTuple_GET_ITEM(kwnames_in, i);
1088 kwargs[kwname] = arg_in_arr;
1089 }
1090 }
1091 call.args.push_back(kwargs);
1092 call.args_convert.push_back(false);
1093 call.kwargs_ref = std::move(kwargs);
1094 }
1095
1096
1097
1098
1099 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1100 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) {
1101 pybind11_fail("Internal error: function call dispatcher inserted wrong number "
1102 "of arguments!");
1103 }
1104 #endif
1105
1106 args_convert_vector<arg_vector_small_size> second_pass_convert;
1107 if (overloaded) {
1108
1109
1110
1111 second_pass_convert = std::move(call.args_convert);
1112 call.args_convert
1113 = args_convert_vector<arg_vector_small_size>(func.nargs, false);
1114 }
1115
1116
1117 try {
1118 loader_life_support guard{};
1119 result = func.impl(call);
1120 } catch (reference_cast_error &) {
1121 result = PYBIND11_TRY_NEXT_OVERLOAD;
1122 }
1123
1124 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
1125 break;
1126 }
1127
1128 if (overloaded) {
1129
1130
1131
1132 for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
1133 if (second_pass_convert[i]) {
1134
1135
1136 call.args_convert.swap(second_pass_convert);
1137 second_pass.push_back(std::move(call));
1138 break;
1139 }
1140 }
1141 }
1142 }
1143
1144 if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
1145
1146
1147 for (auto &call : second_pass) {
1148 try {
1149 loader_life_support guard{};
1150 result = call.func.impl(call);
1151 } catch (reference_cast_error &) {
1152 result = PYBIND11_TRY_NEXT_OVERLOAD;
1153 }
1154
1155 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
1156
1157
1158 if (!result) {
1159 current_overload = &call.func;
1160 }
1161 break;
1162 }
1163 }
1164 }
1165 } catch (error_already_set &e) {
1166 e.restore();
1167 return nullptr;
1168 #ifdef __GLIBCXX__
1169 } catch (abi::__forced_unwind &) {
1170 throw;
1171 #endif
1172 } catch (...) {
1173 try_translate_exceptions();
1174 return nullptr;
1175 }
1176
1177 auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
1178 if (msg.find("std::") != std::string::npos) {
1179 msg += "\n\n"
1180 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1181 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1182 "conversions are optional and require extra headers to be included\n"
1183 "when compiling your pybind11 module.";
1184 }
1185 };
1186
1187 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
1188 if (overloads->is_operator) {
1189 return handle(Py_NotImplemented).inc_ref().ptr();
1190 }
1191
1192 std::string msg = std::string(overloads->name) + "(): incompatible "
1193 + std::string(overloads->is_constructor ? "constructor" : "function")
1194 + " arguments. The following argument types are supported:\n";
1195
1196 int ctr = 0;
1197 for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
1198 msg += " " + std::to_string(++ctr) + ". ";
1199
1200 bool wrote_sig = false;
1201 if (overloads->is_constructor) {
1202
1203
1204 std::string sig = it2->signature;
1205 size_t start = sig.find('(') + 7;
1206 if (start < sig.size()) {
1207
1208 size_t end = sig.find(", "), next = end + 2;
1209 size_t ret = sig.rfind(" -> ");
1210
1211 if (end >= sig.size()) {
1212 next = end = sig.find(')');
1213 }
1214 if (start < end && next < sig.size()) {
1215 msg.append(sig, start, end - start);
1216 msg += '(';
1217 msg.append(sig, next, ret - next);
1218 wrote_sig = true;
1219 }
1220 }
1221 }
1222 if (!wrote_sig) {
1223 msg += it2->signature;
1224 }
1225
1226 msg += '\n';
1227 }
1228 msg += "\nInvoked with: ";
1229 bool some_args = false;
1230 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < n_args_in; ++ti) {
1231 if (!some_args) {
1232 some_args = true;
1233 } else {
1234 msg += ", ";
1235 }
1236 try {
1237 msg += pybind11::repr(args_in_arr[ti]);
1238 } catch (const error_already_set &) {
1239 msg += "<repr raised Error>";
1240 }
1241 }
1242 if (kwnames_in && PyTuple_GET_SIZE(kwnames_in) > 0) {
1243 if (some_args) {
1244 msg += "; ";
1245 }
1246 msg += "kwargs: ";
1247 bool first = true;
1248 for (size_t i = 0; i < static_cast<size_t>(PyTuple_GET_SIZE(kwnames_in)); ++i) {
1249 if (first) {
1250 first = false;
1251 } else {
1252 msg += ", ";
1253 }
1254 msg += reinterpret_borrow<pybind11::str>(PyTuple_GET_ITEM(kwnames_in, i));
1255 msg += '=';
1256 try {
1257 msg += pybind11::repr(args_in_arr[n_args_in + i]);
1258 } catch (const error_already_set &) {
1259 msg += "<repr raised Error>";
1260 }
1261 }
1262 }
1263
1264 append_note_if_missing_header_is_suspected(msg);
1265
1266 if (PyErr_Occurred()) {
1267
1268 raise_from(PyExc_TypeError, msg.c_str());
1269 return nullptr;
1270 }
1271 set_error(PyExc_TypeError, msg.c_str());
1272 return nullptr;
1273 }
1274 if (!result) {
1275 std::string msg = "Unable to convert function return value to a "
1276 "Python type! The signature was\n\t";
1277 assert(current_overload != nullptr);
1278 msg += current_overload->signature;
1279 append_note_if_missing_header_is_suspected(msg);
1280
1281 if (PyErr_Occurred()) {
1282 raise_from(PyExc_TypeError, msg.c_str());
1283 return nullptr;
1284 }
1285 set_error(PyExc_TypeError, msg.c_str());
1286 return nullptr;
1287 }
1288 if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
1289 auto *pi = reinterpret_cast<instance *>(parent.ptr());
1290 self_value_and_holder.type->init_instance(pi, nullptr);
1291 }
1292 return result.ptr();
1293 }
1294
1295 static ssize_t keyword_index(PyObject *haystack, char const *needle) {
1296
1297
1298
1299
1300
1301
1302 auto n = PyTuple_GET_SIZE(haystack);
1303 auto s = reinterpret_steal<pybind11::str>(PyUnicode_InternFromString(needle));
1304 for (ssize_t i = 0; i < n; ++i) {
1305 if (PyTuple_GET_ITEM(haystack, i) == s.ptr()) {
1306 return i;
1307 }
1308 }
1309 for (ssize_t i = 0; i < n; ++i) {
1310 if (PyUnicode_Compare(PyTuple_GET_ITEM(haystack, i), s.ptr()) == 0) {
1311 return i;
1312 }
1313 }
1314 return -1;
1315 }
1316 };
1317
1318 PYBIND11_NAMESPACE_BEGIN(detail)
1319
1320 PYBIND11_NAMESPACE_BEGIN(function_record_PyTypeObject_methods)
1321
1322
1323 inline void tp_dealloc_impl(PyObject *self) {
1324 auto *py_func_rec = reinterpret_cast<function_record_PyObject *>(self);
1325 cpp_function::destruct(py_func_rec->cpp_func_rec);
1326 py_func_rec->cpp_func_rec = nullptr;
1327 }
1328
1329 PYBIND11_NAMESPACE_END(function_record_PyTypeObject_methods)
1330
1331 template <>
1332 struct handle_type_name<cpp_function> {
1333 static constexpr auto name = const_name("collections.abc.Callable");
1334 };
1335
1336 PYBIND11_NAMESPACE_END(detail)
1337
1338
1339 class mod_gil_not_used {
1340 public:
1341 explicit mod_gil_not_used(bool flag = true) : flag_(flag) {}
1342 bool flag() const { return flag_; }
1343
1344 private:
1345 bool flag_;
1346 };
1347
1348 class multiple_interpreters {
1349 public:
1350 enum class level {
1351 not_supported,
1352 shared_gil,
1353 per_interpreter_gil
1354 };
1355
1356 static multiple_interpreters not_supported() {
1357 return multiple_interpreters(level::not_supported);
1358 }
1359 static multiple_interpreters shared_gil() { return multiple_interpreters(level::shared_gil); }
1360 static multiple_interpreters per_interpreter_gil() {
1361 return multiple_interpreters(level::per_interpreter_gil);
1362 }
1363
1364 explicit constexpr multiple_interpreters(level l) : level_(l) {}
1365 level value() const { return level_; }
1366
1367 private:
1368 level level_;
1369 };
1370
1371 PYBIND11_NAMESPACE_BEGIN(detail)
1372
1373 inline bool gil_not_used_option() { return false; }
1374 template <typename F, typename... O>
1375 bool gil_not_used_option(F &&, O &&...o);
1376 template <typename... O>
1377 inline bool gil_not_used_option(mod_gil_not_used f, O &&...o) {
1378 return f.flag() || gil_not_used_option(o...);
1379 }
1380 template <typename F, typename... O>
1381 inline bool gil_not_used_option(F &&, O &&...o) {
1382 return gil_not_used_option(o...);
1383 }
1384
1385 #ifdef Py_mod_multiple_interpreters
1386 inline void *multi_interp_slot() { return Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED; }
1387 template <typename... O>
1388 inline void *multi_interp_slot(multiple_interpreters mi, O &&...o) {
1389 switch (mi.value()) {
1390 case multiple_interpreters::level::per_interpreter_gil:
1391 return Py_MOD_PER_INTERPRETER_GIL_SUPPORTED;
1392 case multiple_interpreters::level::shared_gil:
1393 return Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED;
1394 case multiple_interpreters::level::not_supported:
1395 return Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED;
1396 }
1397
1398 return multi_interp_slot(o...);
1399 }
1400 template <typename F, typename... O>
1401 inline void *multi_interp_slot(F &&, O &&...o) {
1402 return multi_interp_slot(o...);
1403 }
1404 #endif
1405
1406
1407
1408
1409
1410 inline PyObject *get_cached_module(pybind11::str const &nameobj) {
1411 dict state = detail::get_python_state_dict();
1412 if (!state.contains("__pybind11_module_cache")) {
1413 return nullptr;
1414 }
1415 dict cache = state["__pybind11_module_cache"];
1416 if (!cache.contains(nameobj)) {
1417 return nullptr;
1418 }
1419 return cache[nameobj].ptr();
1420 }
1421
1422
1423
1424
1425
1426
1427 inline void cache_completed_module(pybind11::object const &mod) {
1428 dict state = detail::get_python_state_dict();
1429 if (!state.contains("__pybind11_module_cache")) {
1430 state["__pybind11_module_cache"] = dict();
1431 }
1432 state["__pybind11_module_cache"][mod.attr("__spec__").attr("name")] = mod;
1433 }
1434
1435
1436
1437
1438
1439 inline PyObject *cached_create_module(PyObject *spec, PyModuleDef *) {
1440 (void) &cache_completed_module;
1441
1442 auto nameobj = getattr(reinterpret_borrow<object>(spec), "name", none());
1443 if (nameobj.is_none()) {
1444 set_error(PyExc_ImportError, "module spec is missing a name");
1445 return nullptr;
1446 }
1447
1448 auto *mod = get_cached_module(nameobj);
1449 if (mod) {
1450 Py_INCREF(mod);
1451 } else {
1452 mod = PyModule_NewObject(nameobj.ptr());
1453 }
1454 return mod;
1455 }
1456
1457
1458
1459 using slots_array = std::array<PyModuleDef_Slot, 5>;
1460
1461
1462 template <typename... Options>
1463 inline slots_array init_slots(int (*exec_fn)(PyObject *), Options &&...options) noexcept {
1464
1465
1466 slots_array mod_def_slots;
1467 size_t next_slot = 0;
1468
1469 mod_def_slots[next_slot++] = {Py_mod_create, reinterpret_cast<void *>(&cached_create_module)};
1470
1471 if (exec_fn != nullptr) {
1472 mod_def_slots[next_slot++] = {Py_mod_exec, reinterpret_cast<void *>(exec_fn)};
1473 }
1474
1475 #ifdef Py_mod_multiple_interpreters
1476 mod_def_slots[next_slot++] = {Py_mod_multiple_interpreters, multi_interp_slot(options...)};
1477 #endif
1478
1479 if (gil_not_used_option(options...)) {
1480 #if defined(Py_mod_gil) && defined(Py_GIL_DISABLED)
1481 mod_def_slots[next_slot++] = {Py_mod_gil, Py_MOD_GIL_NOT_USED};
1482 #endif
1483 }
1484
1485
1486 mod_def_slots[next_slot++] = {0, nullptr};
1487
1488 return mod_def_slots;
1489 }
1490
1491 PYBIND11_NAMESPACE_END(detail)
1492
1493
1494 class module_ : public object {
1495 public:
1496 PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)
1497
1498
1499 PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead")
1500 explicit module_(const char *name, const char *doc = nullptr) {
1501 *this = create_extension_module(name, doc, new PyModuleDef());
1502 }
1503
1504
1505
1506
1507
1508
1509 template <typename Func, typename... Extra>
1510 module_ &def(const char *name_, Func &&f, const Extra &...extra) {
1511 cpp_function func(std::forward<Func>(f),
1512 name(name_),
1513 scope(*this),
1514 sibling(getattr(*this, name_, none())),
1515 extra...);
1516
1517
1518
1519 add_object(name_, func, true );
1520 return *this;
1521 }
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533 module_ def_submodule(const char *name, const char *doc = nullptr) {
1534 const char *this_name = PyModule_GetName(m_ptr);
1535 if (this_name == nullptr) {
1536 throw error_already_set();
1537 }
1538 std::string full_name = std::string(this_name) + '.' + name;
1539 handle submodule = PyImport_AddModule(full_name.c_str());
1540 if (!submodule) {
1541 throw error_already_set();
1542 }
1543 auto result = reinterpret_borrow<module_>(submodule);
1544 if (doc && options::show_user_defined_docstrings()) {
1545 result.attr("__doc__") = pybind11::str(doc);
1546 }
1547
1548 #if defined(GRAALVM_PYTHON) && (!defined(GRAALPY_VERSION_NUM) || GRAALPY_VERSION_NUM < 0x190000)
1549
1550
1551 handle this_module = m_ptr;
1552 if (object this_file = getattr(this_module, "__file__", none())) {
1553 result.attr("__file__") = this_file;
1554 }
1555 #else
1556 handle this_file = PyModule_GetFilenameObject(m_ptr);
1557 if (this_file) {
1558 result.attr("__file__") = this_file;
1559 } else if (PyErr_ExceptionMatches(PyExc_SystemError) != 0) {
1560 PyErr_Clear();
1561 } else {
1562 throw error_already_set();
1563 }
1564 #endif
1565 attr(name) = result;
1566 return result;
1567 }
1568
1569
1570 static module_ import(const char *name) {
1571 PyObject *obj = PyImport_ImportModule(name);
1572 if (!obj) {
1573 throw error_already_set();
1574 }
1575 return reinterpret_steal<module_>(obj);
1576 }
1577
1578
1579 void reload() {
1580 PyObject *obj = PyImport_ReloadModule(ptr());
1581 if (!obj) {
1582 throw error_already_set();
1583 }
1584 *this = reinterpret_steal<module_>(obj);
1585 }
1586
1587
1588
1589
1590
1591
1592
1593
1594 PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
1595 if (!overwrite && hasattr(*this, name)) {
1596 pybind11_fail(
1597 "Error during initialization: multiple incompatible definitions with name \""
1598 + std::string(name) + "\"");
1599 }
1600
1601 PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() );
1602 }
1603
1604
1605 using module_def = PyModuleDef;
1606
1607
1608
1609
1610
1611
1612 static module_ create_extension_module(const char *name,
1613 const char *doc,
1614 PyModuleDef *def,
1615 mod_gil_not_used gil_not_used
1616 = mod_gil_not_used(false)) {
1617
1618 new (def) PyModuleDef{ PyModuleDef_HEAD_INIT,
1619 name,
1620 options::show_user_defined_docstrings() ? doc : nullptr,
1621 -1,
1622 nullptr,
1623 nullptr,
1624 nullptr,
1625 nullptr,
1626 nullptr};
1627 auto *m = PyModule_Create(def);
1628 if (m == nullptr) {
1629 if (PyErr_Occurred()) {
1630 throw error_already_set();
1631 }
1632 pybind11_fail("Internal error in module_::create_extension_module()");
1633 }
1634 if (gil_not_used.flag()) {
1635 #ifdef Py_GIL_DISABLED
1636 PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
1637 #endif
1638 }
1639
1640
1641
1642 return reinterpret_borrow<module_>(m);
1643 }
1644 };
1645
1646 PYBIND11_NAMESPACE_BEGIN(detail)
1647
1648 template <>
1649 struct handle_type_name<module_> {
1650 static constexpr auto name = const_name("types.ModuleType");
1651 };
1652
1653 PYBIND11_NAMESPACE_END(detail)
1654
1655
1656
1657
1658 using module = module_;
1659
1660
1661
1662
1663 inline dict globals() {
1664 #if PY_VERSION_HEX >= 0x030d0000
1665 PyObject *p = PyEval_GetFrameGlobals();
1666 return p ? reinterpret_steal<dict>(p)
1667 : reinterpret_borrow<dict>(module_::import("__main__").attr("__dict__").ptr());
1668 #else
1669 PyObject *p = PyEval_GetGlobals();
1670 return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
1671 #endif
1672 }
1673
1674 PYBIND11_NAMESPACE_BEGIN(detail)
1675
1676 class generic_type : public object {
1677 public:
1678 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
1679 protected:
1680 void initialize(const type_record &rec) {
1681 if (rec.scope && hasattr(rec.scope, "__dict__")
1682 && rec.scope.attr("__dict__").contains(rec.name)) {
1683 pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name)
1684 + "\": an object with that name is already defined");
1685 }
1686
1687 if ((rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
1688 != nullptr) {
1689 pybind11_fail("generic_type: type \"" + std::string(rec.name)
1690 + "\" is already registered!");
1691 }
1692
1693 m_ptr = make_new_python_type(rec);
1694
1695
1696 auto *tinfo = new detail::type_info();
1697 tinfo->type = reinterpret_cast<PyTypeObject *>(m_ptr);
1698 tinfo->cpptype = rec.type;
1699 tinfo->type_size = rec.type_size;
1700 tinfo->type_align = rec.type_align;
1701 tinfo->operator_new = rec.operator_new;
1702 tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
1703 tinfo->init_instance = rec.init_instance;
1704 tinfo->dealloc = rec.dealloc;
1705 tinfo->get_trampoline_self_life_support = rec.get_trampoline_self_life_support;
1706 tinfo->simple_type = true;
1707 tinfo->simple_ancestors = true;
1708 tinfo->module_local = rec.module_local;
1709 tinfo->holder_enum_v = rec.holder_enum_v;
1710
1711 with_internals([&](internals &internals) {
1712 auto tindex = std::type_index(*rec.type);
1713 tinfo->direct_conversions = &internals.direct_conversions[tindex];
1714 auto &local_internals = get_local_internals();
1715 if (rec.module_local) {
1716 local_internals.registered_types_cpp[rec.type] = tinfo;
1717 } else {
1718 internals.registered_types_cpp[tindex] = tinfo;
1719 #if PYBIND11_INTERNALS_VERSION >= 12
1720 internals.registered_types_cpp_fast[rec.type] = tinfo;
1721 #endif
1722 }
1723
1724 PYBIND11_WARNING_PUSH
1725 #if defined(__GNUC__) && __GNUC__ == 12
1726
1727
1728
1729 PYBIND11_WARNING_DISABLE_GCC("-Warray-bounds")
1730 PYBIND11_WARNING_DISABLE_GCC("-Wstringop-overread")
1731 #endif
1732 internals.registered_types_py[reinterpret_cast<PyTypeObject *>(m_ptr)] = {tinfo};
1733 PYBIND11_WARNING_POP
1734 });
1735
1736 if (rec.bases.size() > 1 || rec.multiple_inheritance) {
1737 mark_parents_nonsimple(tinfo->type);
1738 tinfo->simple_ancestors = false;
1739 } else if (rec.bases.size() == 1) {
1740 auto *parent_tinfo
1741 = get_type_info(reinterpret_cast<PyTypeObject *>(rec.bases[0].ptr()));
1742 assert(parent_tinfo != nullptr);
1743 bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1744 tinfo->simple_ancestors = parent_simple_ancestors;
1745
1746 parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1747 }
1748
1749 if (rec.module_local) {
1750
1751 tinfo->module_local_load = &type_caster_generic::local_load;
1752 setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
1753 }
1754 }
1755
1756
1757 void mark_parents_nonsimple(PyTypeObject *value) {
1758 auto t = reinterpret_borrow<tuple>(value->tp_bases);
1759 for (handle h : t) {
1760 auto *tinfo2 = get_type_info(reinterpret_cast<PyTypeObject *>(h.ptr()));
1761 if (tinfo2) {
1762 tinfo2->simple_type = false;
1763 }
1764 mark_parents_nonsimple(reinterpret_cast<PyTypeObject *>(h.ptr()));
1765 }
1766 }
1767
1768 void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *),
1769 void *get_buffer_data) {
1770 auto *type = reinterpret_cast<PyHeapTypeObject *>(m_ptr);
1771 auto *tinfo = detail::get_type_info(&type->ht_type);
1772
1773 if (!type->ht_type.tp_as_buffer) {
1774 pybind11_fail("To be able to register buffer protocol support for the type '"
1775 + get_fully_qualified_tp_name(tinfo->type)
1776 + "' the associated class<>(..) invocation must "
1777 "include the pybind11::buffer_protocol() annotation!");
1778 }
1779
1780 tinfo->get_buffer = get_buffer;
1781 tinfo->get_buffer_data = get_buffer_data;
1782 }
1783
1784
1785 void def_property_static_impl(const char *name,
1786 handle fget,
1787 handle fset,
1788 detail::function_record *rec_func) {
1789 const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);
1790 const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)
1791 && pybind11::options::show_user_defined_docstrings();
1792 auto property = handle(reinterpret_cast<PyObject *>(
1793 is_static ? get_internals().static_property_type : &PyProperty_Type));
1794 attr(name) = property(fget.ptr() ? fget : none(),
1795 fset.ptr() ? fset : none(),
1796 none(),
1797 pybind11::str(has_doc ? rec_func->doc : ""));
1798 }
1799 };
1800
1801
1802 template <typename T,
1803 typename = void_t<decltype(static_cast<void *(*) (size_t)>(T::operator new))>>
1804 void set_operator_new(type_record *r) {
1805 r->operator_new = &T::operator new;
1806 }
1807
1808 template <typename>
1809 void set_operator_new(...) {}
1810
1811 template <typename T, typename SFINAE = void>
1812 struct has_operator_delete : std::false_type {};
1813 template <typename T>
1814 struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
1815 : std::true_type {};
1816 template <typename T, typename SFINAE = void>
1817 struct has_operator_delete_size : std::false_type {};
1818 template <typename T>
1819 struct has_operator_delete_size<
1820 T,
1821 void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type {
1822 };
1823
1824 template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
1825 void call_operator_delete(T *p, size_t, size_t) {
1826 T::operator delete(p);
1827 }
1828 template <typename T,
1829 enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int>
1830 = 0>
1831 void call_operator_delete(T *p, size_t s, size_t) {
1832 T::operator delete(p, s);
1833 }
1834
1835 inline void call_operator_delete(void *p, size_t s, size_t a) {
1836 (void) s;
1837 (void) a;
1838 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1839 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1840 # ifdef __cpp_sized_deallocation
1841 ::operator delete(p, s, std::align_val_t(a));
1842 # else
1843 ::operator delete(p, std::align_val_t(a));
1844 # endif
1845 return;
1846 }
1847 #endif
1848 #ifdef __cpp_sized_deallocation
1849 ::operator delete(p, s);
1850 #else
1851 ::operator delete(p);
1852 #endif
1853 }
1854
1855 inline void add_class_method(object &cls, const char *name_, const cpp_function &cf) {
1856 cls.attr(cf.name()) = cf;
1857 if (std::strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) {
1858 cls.attr("__hash__") = none();
1859 }
1860 }
1861
1862 PYBIND11_NAMESPACE_END(detail)
1863
1864
1865
1866 template <typename , typename F>
1867 auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
1868 return std::forward<F>(f);
1869 }
1870
1871 template <typename Derived, typename Return, typename Class, typename... Args>
1872 auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
1873 static_assert(
1874 detail::is_accessible_base_of<Class, Derived>::value,
1875 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1876 return pmf;
1877 }
1878
1879 template <typename Derived, typename Return, typename Class, typename... Args>
1880 auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
1881 static_assert(
1882 detail::is_accessible_base_of<Class, Derived>::value,
1883 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1884 return pmf;
1885 }
1886
1887 PYBIND11_NAMESPACE_BEGIN(detail)
1888
1889
1890
1891
1892
1893
1894
1895 template <typename PM>
1896 using must_be_member_function_pointer = enable_if_t<std::is_member_pointer<PM>::value, int>;
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906 template <typename T, typename D>
1907 struct property_cpp_function_classic {
1908 template <typename PM, must_be_member_function_pointer<PM> = 0>
1909 static cpp_function readonly(PM pm, const handle &hdl) {
1910 return cpp_function([pm](const T &c) -> const D & { return c.*pm; }, is_method(hdl));
1911 }
1912
1913 template <typename PM, must_be_member_function_pointer<PM> = 0>
1914 static cpp_function read(PM pm, const handle &hdl) {
1915 return readonly(pm, hdl);
1916 }
1917
1918 template <typename PM, must_be_member_function_pointer<PM> = 0>
1919 static cpp_function write(PM pm, const handle &hdl) {
1920 return cpp_function([pm](T &c, const D &value) { c.*pm = value; }, is_method(hdl));
1921 }
1922 };
1923
1924 PYBIND11_NAMESPACE_END(detail)
1925
1926 template <typename T, typename D, typename SFINAE = void>
1927 struct property_cpp_function : detail::property_cpp_function_classic<T, D> {};
1928
1929 PYBIND11_NAMESPACE_BEGIN(detail)
1930
1931 template <typename T, typename D, typename SFINAE = void>
1932 struct both_t_and_d_use_type_caster_base : std::false_type {};
1933
1934
1935
1936 template <typename T, typename D>
1937 struct both_t_and_d_use_type_caster_base<
1938 T,
1939 D,
1940 enable_if_t<all_of<std::is_base_of<type_caster_base<T>, type_caster<T>>,
1941 std::is_base_of<type_caster_base<intrinsic_t<D>>, make_caster<D>>>::value>>
1942 : std::true_type {};
1943
1944
1945
1946
1947
1948
1949
1950
1951 template <typename T, typename D>
1952 struct property_cpp_function_sh_raw_ptr_member {
1953 using drp = typename std::remove_pointer<D>::type;
1954
1955 template <typename PM, must_be_member_function_pointer<PM> = 0>
1956 static cpp_function readonly(PM pm, const handle &hdl) {
1957 type_info *tinfo = get_type_info(typeid(T), true);
1958 if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
1959 return cpp_function(
1960 [pm](handle c_hdl) -> std::shared_ptr<drp> {
1961 std::shared_ptr<T> c_sp
1962 = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(
1963 c_hdl);
1964 D ptr = (*c_sp).*pm;
1965 return std::shared_ptr<drp>(c_sp, ptr);
1966 },
1967 is_method(hdl));
1968 }
1969 return property_cpp_function_classic<T, D>::readonly(pm, hdl);
1970 }
1971
1972 template <typename PM, must_be_member_function_pointer<PM> = 0>
1973 static cpp_function read(PM pm, const handle &hdl) {
1974 return readonly(pm, hdl);
1975 }
1976
1977 template <typename PM, must_be_member_function_pointer<PM> = 0>
1978 static cpp_function write(PM pm, const handle &hdl) {
1979 type_info *tinfo = get_type_info(typeid(T), true);
1980 if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
1981 return cpp_function([pm](T &c, D value) { c.*pm = std::forward<D>(std::move(value)); },
1982 is_method(hdl));
1983 }
1984 return property_cpp_function_classic<T, D>::write(pm, hdl);
1985 }
1986 };
1987
1988
1989
1990
1991
1992
1993 template <typename T, typename D>
1994 struct property_cpp_function_sh_member_held_by_value {
1995 template <typename PM, must_be_member_function_pointer<PM> = 0>
1996 static cpp_function readonly(PM pm, const handle &hdl) {
1997 type_info *tinfo = get_type_info(typeid(T), true);
1998 if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
1999 return cpp_function(
2000 [pm](handle c_hdl) -> std::shared_ptr<typename std::add_const<D>::type> {
2001 std::shared_ptr<T> c_sp
2002 = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(
2003 c_hdl);
2004 return std::shared_ptr<typename std::add_const<D>::type>(c_sp,
2005 &(c_sp.get()->*pm));
2006 },
2007 is_method(hdl));
2008 }
2009 return property_cpp_function_classic<T, D>::readonly(pm, hdl);
2010 }
2011
2012 template <typename PM, must_be_member_function_pointer<PM> = 0>
2013 static cpp_function read(PM pm, const handle &hdl) {
2014 type_info *tinfo = get_type_info(typeid(T), true);
2015 if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
2016 return cpp_function(
2017 [pm](handle c_hdl) -> std::shared_ptr<D> {
2018 std::shared_ptr<T> c_sp
2019 = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(
2020 c_hdl);
2021 return std::shared_ptr<D>(c_sp, &(c_sp.get()->*pm));
2022 },
2023 is_method(hdl));
2024 }
2025 return property_cpp_function_classic<T, D>::read(pm, hdl);
2026 }
2027
2028 template <typename PM, must_be_member_function_pointer<PM> = 0>
2029 static cpp_function write(PM pm, const handle &hdl) {
2030 type_info *tinfo = get_type_info(typeid(T), true);
2031 if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
2032 return cpp_function([pm](T &c, const D &value) { c.*pm = value; }, is_method(hdl));
2033 }
2034 return property_cpp_function_classic<T, D>::write(pm, hdl);
2035 }
2036 };
2037
2038
2039
2040
2041
2042
2043
2044
2045 template <typename T, typename D>
2046 struct property_cpp_function_sh_unique_ptr_member {
2047 template <typename PM, must_be_member_function_pointer<PM> = 0>
2048 static cpp_function readonly(PM, const handle &) {
2049 static_assert(!is_instantiation<std::unique_ptr, D>::value,
2050 "def_readonly cannot be used for std::unique_ptr members.");
2051 return cpp_function{};
2052 }
2053
2054 template <typename PM, must_be_member_function_pointer<PM> = 0>
2055 static cpp_function read(PM pm, const handle &hdl) {
2056 type_info *tinfo = get_type_info(typeid(T), true);
2057 if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
2058 return cpp_function(
2059 [pm](handle c_hdl) -> D {
2060 std::shared_ptr<T> c_sp
2061 = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(
2062 c_hdl);
2063 return D{std::move(c_sp.get()->*pm)};
2064 },
2065 is_method(hdl));
2066 }
2067 return property_cpp_function_classic<T, D>::read(pm, hdl);
2068 }
2069
2070 template <typename PM, must_be_member_function_pointer<PM> = 0>
2071 static cpp_function write(PM pm, const handle &hdl) {
2072 return cpp_function([pm](T &c, D &&value) { c.*pm = std::move(value); }, is_method(hdl));
2073 }
2074 };
2075
2076 PYBIND11_NAMESPACE_END(detail)
2077
2078 template <typename T, typename D>
2079 struct property_cpp_function<
2080 T,
2081 D,
2082 detail::enable_if_t<detail::all_of<std::is_pointer<D>,
2083 detail::both_t_and_d_use_type_caster_base<T, D>>::value>>
2084 : detail::property_cpp_function_sh_raw_ptr_member<T, D> {};
2085
2086 template <typename T, typename D>
2087 struct property_cpp_function<T,
2088 D,
2089 detail::enable_if_t<detail::all_of<
2090 detail::none_of<std::is_pointer<D>,
2091 std::is_array<D>,
2092 detail::is_instantiation<std::unique_ptr, D>,
2093 detail::is_instantiation<std::shared_ptr, D>>,
2094 detail::both_t_and_d_use_type_caster_base<T, D>>::value>>
2095 : detail::property_cpp_function_sh_member_held_by_value<T, D> {};
2096
2097 template <typename T, typename D>
2098 struct property_cpp_function<
2099 T,
2100 D,
2101 detail::enable_if_t<detail::all_of<
2102 detail::is_instantiation<std::unique_ptr, D>,
2103 detail::both_t_and_d_use_type_caster_base<T, typename D::element_type>>::value>>
2104 : detail::property_cpp_function_sh_unique_ptr_member<T, D> {};
2105
2106 #ifdef PYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE
2107
2108
2109
2110
2111
2112
2113 template <typename>
2114 using default_holder_type = smart_holder;
2115 #else
2116 template <typename T>
2117 using default_holder_type = std::unique_ptr<T>;
2118 #endif
2119
2120 template <typename type_, typename... options>
2121 class class_ : public detail::generic_type {
2122 template <typename T>
2123 using is_holder = detail::is_holder_type<type_, T>;
2124 template <typename T>
2125 using is_subtype = detail::is_strict_base_of<type_, T>;
2126 template <typename T>
2127 using is_base = detail::is_strict_base_of<T, type_>;
2128
2129 template <typename T>
2130 struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
2131
2132 public:
2133 using type = type_;
2134 using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
2135 constexpr static bool has_alias = !std::is_void<type_alias>::value;
2136 using holder_type = detail::exactly_one_t<is_holder, default_holder_type<type>, options...>;
2137
2138 static_assert(detail::all_of<is_valid_class_option<options>...>::value,
2139 "Unknown/invalid class_ template parameters provided");
2140
2141 static_assert(!has_alias || std::is_polymorphic<type>::value,
2142 "Cannot use an alias class (aka trampoline) with a non-polymorphic type");
2143
2144 #ifndef PYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE
2145 static_assert(!has_alias || !detail::is_smart_holder<holder_type>::value
2146 || std::is_base_of<trampoline_self_life_support, type_alias>::value,
2147 "Alias class (aka trampoline) must inherit from"
2148 " pybind11::trampoline_self_life_support if used in combination with"
2149 " pybind11::smart_holder");
2150 #endif
2151 static_assert(!has_alias || detail::is_smart_holder<holder_type>::value
2152 || !std::is_base_of<trampoline_self_life_support, type_alias>::value,
2153 "pybind11::trampoline_self_life_support is a smart_holder feature, therefore"
2154 " an alias class (aka trampoline) should inherit from"
2155 " pybind11::trampoline_self_life_support only if used in combination with"
2156 " pybind11::smart_holder");
2157
2158 PYBIND11_OBJECT(class_, generic_type, PyType_Check)
2159
2160 template <typename... Extra>
2161 class_(handle scope, const char *name, const Extra &...extra) {
2162 using namespace detail;
2163
2164
2165 static_assert(
2166 none_of<is_pyobject<Extra>...>::value ||
2167 (constexpr_sum(is_pyobject<Extra>::value...) == 1 &&
2168 constexpr_sum(is_base<options>::value...) == 0 &&
2169
2170 none_of<std::is_same<multiple_inheritance, Extra>...>::value),
2171 "Error: multiple inheritance bases must be specified via class_ template options");
2172
2173 type_record record;
2174 record.scope = scope;
2175 record.name = name;
2176 record.type = &typeid(type);
2177 record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
2178 record.type_align = alignof(conditional_t<has_alias, type_alias, type> &);
2179 record.holder_size = sizeof(holder_type);
2180 record.init_instance = init_instance;
2181
2182 if (detail::is_instantiation<std::unique_ptr, holder_type>::value) {
2183 record.holder_enum_v = detail::holder_enum_t::std_unique_ptr;
2184 } else if (detail::is_instantiation<std::shared_ptr, holder_type>::value) {
2185 record.holder_enum_v = detail::holder_enum_t::std_shared_ptr;
2186 } else if (std::is_same<holder_type, smart_holder>::value) {
2187 record.holder_enum_v = detail::holder_enum_t::smart_holder;
2188 } else {
2189 record.holder_enum_v = detail::holder_enum_t::custom_holder;
2190 }
2191
2192 set_operator_new<type>(&record);
2193
2194
2195 PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
2196
2197
2198 process_attributes<Extra...>::init(extra..., &record);
2199
2200 if (record.release_gil_before_calling_cpp_dtor) {
2201 record.dealloc = dealloc_release_gil_before_calling_cpp_dtor;
2202 } else {
2203 record.dealloc = dealloc_without_manipulating_gil;
2204 }
2205
2206 if (std::is_base_of<trampoline_self_life_support, type_alias>::value) {
2207
2208
2209
2210 record.get_trampoline_self_life_support = [](void *type_ptr) {
2211 return dynamic_raw_ptr_cast_if_possible<trampoline_self_life_support>(
2212 static_cast<type *>(type_ptr));
2213 };
2214 }
2215
2216 generic_type::initialize(record);
2217
2218 if (has_alias) {
2219 with_internals([&](internals &internals) {
2220 auto &local_internals = get_local_internals();
2221 if (record.module_local) {
2222 local_internals.registered_types_cpp[&typeid(type_alias)]
2223 = local_internals.registered_types_cpp[&typeid(type)];
2224 } else {
2225 type_info *const val
2226 = internals.registered_types_cpp[std::type_index(typeid(type))];
2227 internals.registered_types_cpp[std::type_index(typeid(type_alias))] = val;
2228 #if PYBIND11_INTERNALS_VERSION >= 12
2229 internals.registered_types_cpp_fast[&typeid(type_alias)] = val;
2230 #endif
2231 }
2232 });
2233 }
2234 def("_pybind11_conduit_v1_", cpp_conduit_method);
2235 }
2236
2237 template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
2238 static void add_base(detail::type_record &rec) {
2239 rec.add_base(typeid(Base), [](void *src) -> void * {
2240 return static_cast<Base *>(reinterpret_cast<type *>(src));
2241 });
2242 }
2243
2244 template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
2245 static void add_base(detail::type_record &) {}
2246
2247 template <typename Func, typename... Extra>
2248 class_ &def(const char *name_, Func &&f, const Extra &...extra) {
2249 cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
2250 name(name_),
2251 is_method(*this),
2252 sibling(getattr(*this, name_, none())),
2253 extra...);
2254 add_class_method(*this, name_, cf);
2255 return *this;
2256 }
2257
2258 template <typename Func, typename... Extra>
2259 class_ &def_static(const char *name_, Func &&f, const Extra &...extra) {
2260 static_assert(!std::is_member_function_pointer<Func>::value,
2261 "def_static(...) called with a non-static member function pointer");
2262 cpp_function cf(std::forward<Func>(f),
2263 name(name_),
2264 scope(*this),
2265 sibling(getattr(*this, name_, none())),
2266 extra...);
2267 auto cf_name = cf.name();
2268 attr(std::move(cf_name)) = staticmethod(std::move(cf));
2269 return *this;
2270 }
2271
2272 template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
2273 class_ &def(const T &op, const Extra &...extra) {
2274 op.execute(*this, extra...);
2275 return *this;
2276 }
2277
2278 template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
2279 class_ &def_cast(const T &op, const Extra &...extra) {
2280 op.execute_cast(*this, extra...);
2281 return *this;
2282 }
2283
2284 template <typename... Args, typename... Extra>
2285 class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra &...extra) {
2286 PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
2287 init.execute(*this, extra...);
2288 return *this;
2289 }
2290
2291 template <typename... Args, typename... Extra>
2292 class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra &...extra) {
2293 PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
2294 init.execute(*this, extra...);
2295 return *this;
2296 }
2297
2298 template <typename... Args, typename... Extra>
2299 class_ &def(detail::initimpl::factory<Args...> &&init, const Extra &...extra) {
2300 std::move(init).execute(*this, extra...);
2301 return *this;
2302 }
2303
2304 template <typename... Args, typename... Extra>
2305 class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
2306 std::move(pf).execute(*this, extra...);
2307 return *this;
2308 }
2309
2310 template <typename Func>
2311 class_ &def_buffer(Func &&func) {
2312 struct capture {
2313 Func func;
2314 };
2315 auto *ptr = new capture{std::forward<Func>(func)};
2316 install_buffer_funcs(
2317 [](PyObject *obj, void *ptr) -> buffer_info * {
2318 detail::make_caster<type> caster;
2319 if (!caster.load(obj, false)) {
2320 return nullptr;
2321 }
2322 return new buffer_info(((capture *) ptr)->func(std::move(caster)));
2323 },
2324 ptr);
2325 weakref(m_ptr, cpp_function([ptr](handle wr) {
2326 delete ptr;
2327 wr.dec_ref();
2328 }))
2329 .release();
2330 return *this;
2331 }
2332
2333 template <typename Return, typename Class, typename... Args>
2334 class_ &def_buffer(Return (Class::*func)(Args...)) {
2335 return def_buffer([func](type &obj) { return (obj.*func)(); });
2336 }
2337
2338 template <typename Return, typename Class, typename... Args>
2339 class_ &def_buffer(Return (Class::*func)(Args...) const) {
2340 return def_buffer([func](const type &obj) { return (obj.*func)(); });
2341 }
2342
2343 template <typename C, typename D, typename... Extra>
2344 class_ &def_readwrite(const char *name, D C::*pm, const Extra &...extra) {
2345 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
2346 "def_readwrite() requires a class member (or base class member)");
2347 def_property(name,
2348 property_cpp_function<type, D>::read(pm, *this),
2349 property_cpp_function<type, D>::write(pm, *this),
2350 return_value_policy::reference_internal,
2351 extra...);
2352 return *this;
2353 }
2354
2355 template <typename C, typename D, typename... Extra>
2356 class_ &def_readonly(const char *name, const D C::*pm, const Extra &...extra) {
2357 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
2358 "def_readonly() requires a class member (or base class member)");
2359 def_property_readonly(name,
2360 property_cpp_function<type, D>::readonly(pm, *this),
2361 return_value_policy::reference_internal,
2362 extra...);
2363 return *this;
2364 }
2365
2366 template <typename D, typename... Extra>
2367 class_ &def_readwrite_static(const char *name, D *pm, const Extra &...extra) {
2368 cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)),
2369 fset([pm](const object &, const D &value) { *pm = value; }, scope(*this));
2370 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
2371 return *this;
2372 }
2373
2374 template <typename D, typename... Extra>
2375 class_ &def_readonly_static(const char *name, const D *pm, const Extra &...extra) {
2376 cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this));
2377 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
2378 return *this;
2379 }
2380
2381
2382 template <typename Getter, typename... Extra>
2383 class_ &def_property_readonly(const char *name, const Getter &fget, const Extra &...extra) {
2384 return def_property_readonly(name,
2385 cpp_function(method_adaptor<type>(fget)),
2386 return_value_policy::reference_internal,
2387 extra...);
2388 }
2389
2390
2391 template <typename... Extra>
2392 class_ &
2393 def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra) {
2394 return def_property(name, fget, nullptr, extra...);
2395 }
2396
2397
2398 template <typename Getter, typename... Extra>
2399 class_ &
2400 def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra) {
2401 return def_property_readonly_static(
2402 name, cpp_function(fget), return_value_policy::reference, extra...);
2403 }
2404
2405
2406 template <typename... Extra>
2407 class_ &def_property_readonly_static(const char *name,
2408 const cpp_function &fget,
2409 const Extra &...extra) {
2410 return def_property_static(name, fget, nullptr, extra...);
2411 }
2412
2413
2414 template <typename Getter, typename Setter, typename... Extra>
2415 class_ &
2416 def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) {
2417 return def_property(
2418 name, fget, cpp_function(method_adaptor<type>(fset), is_setter()), extra...);
2419 }
2420 template <typename Getter, typename... Extra>
2421 class_ &def_property(const char *name,
2422 const Getter &fget,
2423 const cpp_function &fset,
2424 const Extra &...extra) {
2425 return def_property(name,
2426 cpp_function(method_adaptor<type>(fget)),
2427 fset,
2428 return_value_policy::reference_internal,
2429 extra...);
2430 }
2431
2432
2433 template <typename... Extra>
2434 class_ &def_property(const char *name,
2435 const cpp_function &fget,
2436 const cpp_function &fset,
2437 const Extra &...extra) {
2438 return def_property_static(name, fget, fset, is_method(*this), extra...);
2439 }
2440
2441
2442 template <typename Getter, typename... Extra>
2443 class_ &def_property_static(const char *name,
2444 const Getter &fget,
2445 const cpp_function &fset,
2446 const Extra &...extra) {
2447 return def_property_static(
2448 name, cpp_function(fget), fset, return_value_policy::reference, extra...);
2449 }
2450
2451
2452 template <typename... Extra>
2453 class_ &def_property_static(const char *name,
2454 const cpp_function &fget,
2455 const cpp_function &fset,
2456 const Extra &...extra) {
2457 static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
2458 "Argument annotations are not allowed for properties");
2459 static_assert(0 == detail::constexpr_sum(detail::is_call_guard<Extra>::value...),
2460 "def_property family does not currently support call_guard. Use a "
2461 "py::cpp_function instead.");
2462 static_assert(0 == detail::constexpr_sum(detail::is_keep_alive<Extra>::value...),
2463 "def_property family does not currently support keep_alive. Use a "
2464 "py::cpp_function instead.");
2465 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
2466 auto *rec_active = rec_fget;
2467 if (rec_fget) {
2468 char *doc_prev = rec_fget->doc;
2469
2470 detail::process_attributes<Extra...>::init(extra..., rec_fget);
2471 if (rec_fget->doc && rec_fget->doc != doc_prev) {
2472 std::free(doc_prev);
2473 rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc);
2474 }
2475 }
2476 if (rec_fset) {
2477 char *doc_prev = rec_fset->doc;
2478 detail::process_attributes<Extra...>::init(extra..., rec_fset);
2479 if (rec_fset->doc && rec_fset->doc != doc_prev) {
2480 std::free(doc_prev);
2481 rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc);
2482 }
2483 if (!rec_active) {
2484 rec_active = rec_fset;
2485 }
2486 }
2487 def_property_static_impl(name, fget, fset, rec_active);
2488 return *this;
2489 }
2490
2491 private:
2492
2493 template <typename T>
2494 static void init_holder(detail::instance *inst,
2495 detail::value_and_holder &v_h,
2496 const holder_type * ,
2497 const std::enable_shared_from_this<T> * ) {
2498
2499 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
2500 detail::try_get_shared_from_this(v_h.value_ptr<type>()));
2501 if (sh) {
2502 new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
2503 v_h.set_holder_constructed();
2504 }
2505
2506 if (!v_h.holder_constructed() && inst->owned) {
2507 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
2508 v_h.set_holder_constructed();
2509 }
2510 }
2511
2512 static void init_holder_from_existing(const detail::value_and_holder &v_h,
2513 const holder_type *holder_ptr,
2514 std::true_type ) {
2515 new (std::addressof(v_h.holder<holder_type>())) holder_type(*holder_ptr);
2516 }
2517
2518 static void init_holder_from_existing(const detail::value_and_holder &v_h,
2519 const holder_type *holder_ptr,
2520 std::false_type ) {
2521 new (std::addressof(v_h.holder<holder_type>()))
2522 holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
2523 }
2524
2525
2526
2527 static void init_holder(detail::instance *inst,
2528 detail::value_and_holder &v_h,
2529 const holder_type *holder_ptr,
2530 const void * ) {
2531 if (holder_ptr) {
2532 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
2533 v_h.set_holder_constructed();
2534 } else if (detail::always_construct_holder<holder_type>::value || inst->owned) {
2535 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
2536 v_h.set_holder_constructed();
2537 }
2538 }
2539
2540
2541
2542
2543
2544 template <typename H = holder_type,
2545 detail::enable_if_t<!detail::is_smart_holder<H>::value, int> = 0>
2546 static void init_instance(detail::instance *inst, const void *holder_ptr) {
2547 auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
2548 if (!v_h.instance_registered()) {
2549 register_instance(inst, v_h.value_ptr(), v_h.type);
2550 v_h.set_instance_registered();
2551 }
2552 init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
2553 }
2554
2555 template <typename WrappedType>
2556 static bool try_initialization_using_shared_from_this(holder_type *, WrappedType *, ...) {
2557 return false;
2558 }
2559
2560
2561
2562
2563
2564
2565 template <typename WrappedType, typename SomeBaseOfWrappedType>
2566 static bool try_initialization_using_shared_from_this(
2567 holder_type *uninitialized_location,
2568 WrappedType *value_ptr_w_t,
2569 const std::enable_shared_from_this<SomeBaseOfWrappedType> *) {
2570 auto shd_ptr = std::dynamic_pointer_cast<WrappedType>(
2571 detail::try_get_shared_from_this(value_ptr_w_t));
2572 if (!shd_ptr) {
2573 return false;
2574 }
2575
2576 new (uninitialized_location) holder_type(holder_type::from_shared_ptr(shd_ptr));
2577 return true;
2578 }
2579
2580 template <typename H = holder_type,
2581 detail::enable_if_t<detail::is_smart_holder<H>::value, int> = 0>
2582 static void init_instance(detail::instance *inst, const void *holder_const_void_ptr) {
2583
2584
2585 auto *holder_void_ptr = const_cast<void *>(holder_const_void_ptr);
2586
2587 auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
2588 if (!v_h.instance_registered()) {
2589 register_instance(inst, v_h.value_ptr(), v_h.type);
2590 v_h.set_instance_registered();
2591 }
2592 auto *uninitialized_location = std::addressof(v_h.holder<holder_type>());
2593 auto *value_ptr_w_t = v_h.value_ptr<type>();
2594
2595 inst->is_alias
2596 = detail::dynamic_raw_ptr_cast_if_possible<type_alias>(value_ptr_w_t) != nullptr;
2597 if (holder_void_ptr) {
2598
2599 auto *holder_ptr = static_cast<holder_type *>(holder_void_ptr);
2600 new (uninitialized_location) holder_type(std::move(*holder_ptr));
2601 } else if (!try_initialization_using_shared_from_this(
2602 uninitialized_location, value_ptr_w_t, value_ptr_w_t)) {
2603 if (inst->owned) {
2604 new (uninitialized_location) holder_type(holder_type::from_raw_ptr_take_ownership(
2605 value_ptr_w_t, inst->is_alias));
2606 } else {
2607 new (uninitialized_location)
2608 holder_type(holder_type::from_raw_ptr_unowned(value_ptr_w_t));
2609 }
2610 }
2611 v_h.set_holder_constructed();
2612 }
2613
2614
2615
2616
2617
2618
2619
2620
2621 static void dealloc_impl(detail::value_and_holder &v_h) {
2622 if (v_h.holder_constructed()) {
2623 v_h.holder<holder_type>().~holder_type();
2624 v_h.set_holder_constructed(false);
2625 } else {
2626 detail::call_operator_delete(
2627 v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align);
2628 }
2629 v_h.value_ptr() = nullptr;
2630 }
2631
2632 static void dealloc_without_manipulating_gil(detail::value_and_holder &v_h) {
2633 error_scope scope;
2634 dealloc_impl(v_h);
2635 }
2636
2637 static void dealloc_release_gil_before_calling_cpp_dtor(detail::value_and_holder &v_h) {
2638 error_scope scope;
2639
2640
2641
2642
2643 PyThreadState *py_ts = PyEval_SaveThread();
2644 try {
2645 dealloc_impl(v_h);
2646 } catch (...) {
2647
2648
2649
2650
2651
2652 PyEval_RestoreThread(py_ts);
2653 throw;
2654 }
2655 PyEval_RestoreThread(py_ts);
2656 }
2657
2658 static detail::function_record *get_function_record(handle h) {
2659 h = detail::get_function(h);
2660 if (!h) {
2661 return nullptr;
2662 }
2663
2664 handle func_self = PyCFunction_GET_SELF(h.ptr());
2665 if (!func_self) {
2666 throw error_already_set();
2667 }
2668 return detail::function_record_ptr_from_PyObject(func_self.ptr());
2669 }
2670 };
2671
2672
2673
2674 template <typename type_, typename... options>
2675 using classh = class_<type_, smart_holder, options...>;
2676
2677
2678 template <typename... Args>
2679 detail::initimpl::constructor<Args...> init() {
2680 return {};
2681 }
2682
2683
2684 template <typename... Args>
2685 detail::initimpl::alias_constructor<Args...> init_alias() {
2686 return {};
2687 }
2688
2689
2690 template <typename Func, typename Ret = detail::initimpl::factory<Func>>
2691 Ret init(Func &&f) {
2692 return {std::forward<Func>(f)};
2693 }
2694
2695
2696
2697
2698 template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
2699 Ret init(CFunc &&c, AFunc &&a) {
2700 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
2701 }
2702
2703
2704
2705 template <typename GetState, typename SetState>
2706 detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
2707 return {std::forward<GetState>(g), std::forward<SetState>(s)};
2708 }
2709
2710 PYBIND11_NAMESPACE_BEGIN(detail)
2711
2712 inline str enum_name(handle arg) {
2713 dict entries = type::handle_of(arg).attr("__entries");
2714 for (auto kv : entries) {
2715 if (handle(kv.second[int_(0)]).equal(arg)) {
2716 return pybind11::str(kv.first);
2717 }
2718 }
2719 return "???";
2720 }
2721
2722 struct enum_base {
2723 enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) {}
2724
2725 PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
2726 m_base.attr("__entries") = dict();
2727 auto property = handle(reinterpret_cast<PyObject *>(&PyProperty_Type));
2728 auto static_property
2729 = handle(reinterpret_cast<PyObject *>(get_internals().static_property_type));
2730
2731 m_base.attr("__repr__") = cpp_function(
2732 [](const object &arg) -> str {
2733 handle type = type::handle_of(arg);
2734 object type_name = type.attr("__name__");
2735 return pybind11::str("<{}.{}: {}>")
2736 .format(std::move(type_name), enum_name(arg), int_(arg));
2737 },
2738 name("__repr__"),
2739 is_method(m_base),
2740 pos_only());
2741
2742 m_base.attr("name")
2743 = property(cpp_function(&enum_name, name("name"), is_method(m_base), pos_only()));
2744
2745 m_base.attr("__str__") = cpp_function(
2746 [](handle arg) -> str {
2747 object type_name = type::handle_of(arg).attr("__name__");
2748 return pybind11::str("{}.{}").format(std::move(type_name), enum_name(arg));
2749 },
2750 name("__str__"),
2751 is_method(m_base),
2752 pos_only());
2753
2754 if (options::show_enum_members_docstring()) {
2755 m_base.attr("__doc__") = static_property(
2756 cpp_function(
2757 [](handle arg) -> std::string {
2758 std::string docstring;
2759 dict entries = arg.attr("__entries");
2760 if ((reinterpret_cast<PyTypeObject *>(arg.ptr()))->tp_doc) {
2761 docstring += std::string(
2762 reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);
2763 docstring += "\n\n";
2764 }
2765 docstring += "Members:";
2766 for (auto kv : entries) {
2767 auto key = std::string(pybind11::str(kv.first));
2768 auto comment = kv.second[int_(1)];
2769 docstring += "\n\n ";
2770 docstring += key;
2771 if (!comment.is_none()) {
2772 docstring += " : ";
2773 docstring += pybind11::str(comment).cast<std::string>();
2774 }
2775 }
2776 return docstring;
2777 },
2778 name("__doc__")),
2779 none(),
2780 none(),
2781 "");
2782 }
2783
2784 m_base.attr("__members__") = static_property(cpp_function(
2785 [](handle arg) -> dict {
2786 dict entries = arg.attr("__entries"),
2787 m;
2788 for (auto kv : entries) {
2789 m[kv.first] = kv.second[int_(0)];
2790 }
2791 return m;
2792 },
2793 name("__members__")),
2794 none(),
2795 none(),
2796 "");
2797
2798 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
2799 m_base.attr(op) = cpp_function( \
2800 [](const object &a, const object &b) { \
2801 if (!type::handle_of(a).is(type::handle_of(b))) \
2802 strict_behavior; \
2803 return expr; \
2804 }, \
2805 name(op), \
2806 is_method(m_base), \
2807 arg("other"), \
2808 pos_only())
2809
2810 #define PYBIND11_ENUM_OP_CONV(op, expr) \
2811 m_base.attr(op) = cpp_function( \
2812 [](const object &a_, const object &b_) { \
2813 int_ a(a_), b(b_); \
2814 return expr; \
2815 }, \
2816 name(op), \
2817 is_method(m_base), \
2818 arg("other"), \
2819 pos_only())
2820
2821 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
2822 m_base.attr(op) = cpp_function( \
2823 [](const object &a_, const object &b) { \
2824 int_ a(a_); \
2825 return expr; \
2826 }, \
2827 name(op), \
2828 is_method(m_base), \
2829 arg("other"), \
2830 pos_only())
2831
2832 if (is_convertible) {
2833 PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
2834 PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
2835
2836 if (is_arithmetic) {
2837 PYBIND11_ENUM_OP_CONV("__lt__", a < b);
2838 PYBIND11_ENUM_OP_CONV("__gt__", a > b);
2839 PYBIND11_ENUM_OP_CONV("__le__", a <= b);
2840 PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
2841 PYBIND11_ENUM_OP_CONV("__and__", a & b);
2842 PYBIND11_ENUM_OP_CONV("__rand__", a & b);
2843 PYBIND11_ENUM_OP_CONV("__or__", a | b);
2844 PYBIND11_ENUM_OP_CONV("__ror__", a | b);
2845 PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
2846 PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
2847 m_base.attr("__invert__")
2848 = cpp_function([](const object &arg) { return ~(int_(arg)); },
2849 name("__invert__"),
2850 is_method(m_base),
2851 pos_only());
2852 }
2853 } else {
2854 PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
2855 PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
2856
2857 if (is_arithmetic) {
2858 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
2859 PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
2860 PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
2861 PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
2862 PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
2863 #undef PYBIND11_THROW
2864 }
2865 }
2866
2867 #undef PYBIND11_ENUM_OP_CONV_LHS
2868 #undef PYBIND11_ENUM_OP_CONV
2869 #undef PYBIND11_ENUM_OP_STRICT
2870
2871 m_base.attr("__getstate__") = cpp_function([](const object &arg) { return int_(arg); },
2872 name("__getstate__"),
2873 is_method(m_base),
2874 pos_only());
2875
2876 m_base.attr("__hash__") = cpp_function([](const object &arg) { return int_(arg); },
2877 name("__hash__"),
2878 is_method(m_base),
2879 pos_only());
2880 }
2881
2882 PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc = nullptr) {
2883 dict entries = m_base.attr("__entries");
2884 str name(name_);
2885 if (entries.contains(name)) {
2886 std::string type_name = std::string(str(m_base.attr("__name__")));
2887 throw value_error(std::move(type_name) + ": element \"" + std::string(name_)
2888 + "\" already exists!");
2889 }
2890
2891 entries[name] = pybind11::make_tuple(value, doc);
2892 m_base.attr(std::move(name)) = std::move(value);
2893 }
2894
2895 PYBIND11_NOINLINE void export_values() {
2896 dict entries = m_base.attr("__entries");
2897 for (auto kv : entries) {
2898 m_parent.attr(kv.first) = kv.second[int_(0)];
2899 }
2900 }
2901
2902 handle m_base;
2903 handle m_parent;
2904 };
2905
2906 template <bool is_signed, size_t length>
2907 struct equivalent_integer {};
2908 template <>
2909 struct equivalent_integer<true, 1> {
2910 using type = int8_t;
2911 };
2912 template <>
2913 struct equivalent_integer<false, 1> {
2914 using type = uint8_t;
2915 };
2916 template <>
2917 struct equivalent_integer<true, 2> {
2918 using type = int16_t;
2919 };
2920 template <>
2921 struct equivalent_integer<false, 2> {
2922 using type = uint16_t;
2923 };
2924 template <>
2925 struct equivalent_integer<true, 4> {
2926 using type = int32_t;
2927 };
2928 template <>
2929 struct equivalent_integer<false, 4> {
2930 using type = uint32_t;
2931 };
2932 template <>
2933 struct equivalent_integer<true, 8> {
2934 using type = int64_t;
2935 };
2936 template <>
2937 struct equivalent_integer<false, 8> {
2938 using type = uint64_t;
2939 };
2940
2941 template <typename IntLike>
2942 using equivalent_integer_t =
2943 typename equivalent_integer<std::is_signed<IntLike>::value, sizeof(IntLike)>::type;
2944
2945 PYBIND11_NAMESPACE_END(detail)
2946
2947
2948 template <typename Type>
2949 class enum_ : public class_<Type> {
2950 public:
2951 using Base = class_<Type>;
2952 using Base::attr;
2953 using Base::def;
2954 using Base::def_property_readonly;
2955 using Base::def_property_readonly_static;
2956 using Underlying = typename std::underlying_type<Type>::type;
2957
2958 using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2959 std::is_same<Underlying, bool>>::value,
2960 detail::equivalent_integer_t<Underlying>,
2961 Underlying>;
2962
2963 template <typename... Extra>
2964 enum_(const handle &scope, const char *name, const Extra &...extra)
2965 : class_<Type>(scope, name, extra...), m_base(*this, scope) {
2966 {
2967 if (detail::global_internals_native_enum_type_map_contains(
2968 std::type_index(typeid(Type)))) {
2969 pybind11_fail("pybind11::enum_ \"" + std::string(name)
2970 + "\" is already registered as a pybind11::native_enum!");
2971 }
2972 }
2973
2974 constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
2975 constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
2976 m_base.init(is_arithmetic, is_convertible);
2977
2978 def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
2979 def_property_readonly("value", [](Type value) { return (Scalar) value; }, pos_only());
2980 def("__int__", [](Type value) { return (Scalar) value; }, pos_only());
2981 def("__index__", [](Type value) { return (Scalar) value; }, pos_only());
2982 attr("__setstate__") = cpp_function(
2983 [](detail::value_and_holder &v_h, Scalar arg) {
2984 detail::initimpl::setstate<Base>(
2985 v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type);
2986 },
2987 detail::is_new_style_constructor(),
2988 pybind11::name("__setstate__"),
2989 is_method(*this),
2990 arg("state"),
2991 pos_only());
2992 }
2993
2994
2995 enum_ &export_values() {
2996 m_base.export_values();
2997 return *this;
2998 }
2999
3000
3001 enum_ &value(char const *name, Type value, const char *doc = nullptr) {
3002 m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
3003 return *this;
3004 }
3005
3006 private:
3007 detail::enum_base m_base;
3008 };
3009
3010 PYBIND11_NAMESPACE_BEGIN(detail)
3011
3012 PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient) {
3013 if (!nurse || !patient) {
3014 pybind11_fail("Could not activate keep_alive!");
3015 }
3016
3017 if (patient.is_none() || nurse.is_none()) {
3018 return;
3019 }
3020
3021 auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
3022 if (!tinfo.empty()) {
3023
3024
3025 add_patient(nurse.ptr(), patient.ptr());
3026 } else {
3027
3028
3029
3030 cpp_function disable_lifesupport([patient](handle weakref) {
3031 patient.dec_ref();
3032 weakref.dec_ref();
3033 });
3034
3035 weakref wr(nurse, disable_lifesupport);
3036
3037 patient.inc_ref();
3038 (void) wr.release();
3039 }
3040 }
3041
3042 PYBIND11_NOINLINE void
3043 keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
3044 auto get_arg = [&](size_t n) {
3045 if (n == 0) {
3046 return ret;
3047 }
3048 if (n == 1 && call.init_self) {
3049 return call.init_self;
3050 }
3051 if (n <= call.args.size()) {
3052 return call.args[n - 1];
3053 }
3054 return handle();
3055 };
3056
3057 keep_alive_impl(get_arg(Nurse), get_arg(Patient));
3058 }
3059
3060 inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
3061 all_type_info_get_cache(PyTypeObject *type) {
3062 auto res = with_internals([type](internals &internals) {
3063 auto ins = internals
3064 .registered_types_py
3065 #ifdef __cpp_lib_unordered_map_try_emplace
3066 .try_emplace(type);
3067 #else
3068 .emplace(type, std::vector<detail::type_info *>());
3069 #endif
3070 if (ins.second) {
3071
3072
3073
3074 all_type_info_populate(type, ins.first->second);
3075 }
3076 return ins;
3077 });
3078 if (res.second) {
3079
3080
3081 weakref(reinterpret_cast<PyObject *>(type), cpp_function([type](handle wr) {
3082 with_internals([type](internals &internals) {
3083 internals.registered_types_py.erase(type);
3084
3085
3086 auto &cache = internals.inactive_override_cache;
3087 for (auto it = cache.begin(), last = cache.end(); it != last;) {
3088 if (it->first == reinterpret_cast<PyObject *>(type)) {
3089 it = cache.erase(it);
3090 } else {
3091 ++it;
3092 }
3093 }
3094 });
3095
3096 wr.dec_ref();
3097 }))
3098 .release();
3099 }
3100
3101 return res;
3102 }
3103
3104
3105
3106
3107 template <typename Access,
3108 return_value_policy Policy,
3109 typename Iterator,
3110 typename Sentinel,
3111 typename ValueType,
3112 typename... Extra>
3113 struct iterator_state {
3114 Iterator it;
3115 Sentinel end;
3116 bool first_or_done;
3117 };
3118
3119
3120
3121
3122
3123 template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
3124 struct iterator_access {
3125 using result_type = decltype(*std::declval<Iterator &>());
3126
3127 result_type operator()(Iterator &it) const { return *it; }
3128 };
3129
3130 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).first)>
3131 class iterator_key_access {
3132 private:
3133 using pair_type = decltype(*std::declval<Iterator &>());
3134
3135 public:
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145 using result_type
3146 = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
3147 decltype(((*std::declval<Iterator &>()).first)),
3148 decltype(std::declval<pair_type>().first)>;
3149 result_type operator()(Iterator &it) const { return (*it).first; }
3150 };
3151
3152 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
3153 class iterator_value_access {
3154 private:
3155 using pair_type = decltype(*std::declval<Iterator &>());
3156
3157 public:
3158 using result_type
3159 = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
3160 decltype(((*std::declval<Iterator &>()).second)),
3161 decltype(std::declval<pair_type>().second)>;
3162 result_type operator()(Iterator &it) const { return (*it).second; }
3163 };
3164
3165 template <typename Access,
3166 return_value_policy Policy,
3167 typename Iterator,
3168 typename Sentinel,
3169 typename ValueType,
3170 typename... Extra>
3171
3172 iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra) {
3173 using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
3174
3175
3176
3177
3178 #if PY_VERSION_HEX >= 0x030E00C1
3179 PYBIND11_LOCK_INTERNALS(get_internals());
3180 #endif
3181 if (!detail::get_type_info(typeid(state), false)) {
3182 class_<state>(handle(), "iterator", pybind11::module_local())
3183 .def(
3184 "__iter__", [](state &s) -> state & { return s; }, pos_only())
3185 .def(
3186 "__next__",
3187 [](state &s) -> ValueType {
3188 if (!s.first_or_done) {
3189 ++s.it;
3190 } else {
3191 s.first_or_done = false;
3192 }
3193 if (s.it == s.end) {
3194 s.first_or_done = true;
3195 throw stop_iteration();
3196 }
3197 return Access()(s.it);
3198
3199 },
3200 std::forward<Extra>(extra)...,
3201 pos_only(),
3202 Policy);
3203 }
3204
3205 return cast(state{std::forward<Iterator>(first), std::forward<Sentinel>(last), true});
3206 }
3207
3208 PYBIND11_NAMESPACE_END(detail)
3209
3210
3211 template <return_value_policy Policy = return_value_policy::reference_internal,
3212 typename Iterator,
3213 typename Sentinel,
3214 typename ValueType = typename detail::iterator_access<Iterator>::result_type,
3215 typename... Extra>
3216
3217 typing::Iterator<ValueType> make_iterator(Iterator first, Sentinel last, Extra &&...extra) {
3218 return detail::make_iterator_impl<detail::iterator_access<Iterator>,
3219 Policy,
3220 Iterator,
3221 Sentinel,
3222 ValueType,
3223 Extra...>(std::forward<Iterator>(first),
3224 std::forward<Sentinel>(last),
3225 std::forward<Extra>(extra)...);
3226 }
3227
3228
3229
3230 template <return_value_policy Policy = return_value_policy::reference_internal,
3231 typename Iterator,
3232 typename Sentinel,
3233 typename KeyType = typename detail::iterator_key_access<Iterator>::result_type,
3234 typename... Extra>
3235 typing::Iterator<KeyType> make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) {
3236 return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
3237 Policy,
3238 Iterator,
3239 Sentinel,
3240 KeyType,
3241 Extra...>(std::forward<Iterator>(first),
3242 std::forward<Sentinel>(last),
3243 std::forward<Extra>(extra)...);
3244 }
3245
3246
3247
3248 template <return_value_policy Policy = return_value_policy::reference_internal,
3249 typename Iterator,
3250 typename Sentinel,
3251 typename ValueType = typename detail::iterator_value_access<Iterator>::result_type,
3252 typename... Extra>
3253 typing::Iterator<ValueType> make_value_iterator(Iterator first, Sentinel last, Extra &&...extra) {
3254 return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
3255 Policy,
3256 Iterator,
3257 Sentinel,
3258 ValueType,
3259 Extra...>(std::forward<Iterator>(first),
3260 std::forward<Sentinel>(last),
3261 std::forward<Extra>(extra)...);
3262 }
3263
3264
3265
3266 template <return_value_policy Policy = return_value_policy::reference_internal,
3267 typename Type,
3268 typename ValueType = typename detail::iterator_access<
3269 decltype(std::begin(std::declval<Type &>()))>::result_type,
3270 typename... Extra>
3271 typing::Iterator<ValueType> make_iterator(Type &value, Extra &&...extra) {
3272 return make_iterator<Policy>(
3273 std::begin(value), std::end(value), std::forward<Extra>(extra)...);
3274 }
3275
3276
3277
3278 template <return_value_policy Policy = return_value_policy::reference_internal,
3279 typename Type,
3280 typename KeyType = typename detail::iterator_key_access<
3281 decltype(std::begin(std::declval<Type &>()))>::result_type,
3282 typename... Extra>
3283 typing::Iterator<KeyType> make_key_iterator(Type &value, Extra &&...extra) {
3284 return make_key_iterator<Policy>(
3285 std::begin(value), std::end(value), std::forward<Extra>(extra)...);
3286 }
3287
3288
3289
3290 template <return_value_policy Policy = return_value_policy::reference_internal,
3291 typename Type,
3292 typename ValueType = typename detail::iterator_value_access<
3293 decltype(std::begin(std::declval<Type &>()))>::result_type,
3294 typename... Extra>
3295 typing::Iterator<ValueType> make_value_iterator(Type &value, Extra &&...extra) {
3296 return make_value_iterator<Policy>(
3297 std::begin(value), std::end(value), std::forward<Extra>(extra)...);
3298 }
3299
3300 template <typename InputType, typename OutputType>
3301 void implicitly_convertible() {
3302 static int tss_sentinel_pointee = 1;
3303 struct set_flag {
3304 thread_specific_storage<int> &flag;
3305 explicit set_flag(thread_specific_storage<int> &flag_) : flag(flag_) {
3306 flag = &tss_sentinel_pointee;
3307 }
3308 ~set_flag() { flag.reset(nullptr); }
3309
3310
3311 set_flag(const set_flag &) = delete;
3312 set_flag(set_flag &&) = delete;
3313 set_flag &operator=(const set_flag &) = delete;
3314 set_flag &operator=(set_flag &&) = delete;
3315 };
3316 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
3317 static thread_specific_storage<int> currently_used;
3318 if (currently_used) {
3319 return nullptr;
3320 }
3321 set_flag flag_helper(currently_used);
3322 if (!detail::make_caster<InputType>().load(obj, false)) {
3323 return nullptr;
3324 }
3325 tuple args(1);
3326 args[0] = obj;
3327 PyObject *result = PyObject_Call(reinterpret_cast<PyObject *>(type), args.ptr(), nullptr);
3328 if (result == nullptr) {
3329 PyErr_Clear();
3330 }
3331 return result;
3332 };
3333
3334 if (auto *tinfo = detail::get_type_info(typeid(OutputType))) {
3335 tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
3336 } else {
3337 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
3338 }
3339 }
3340
3341 inline void register_exception_translator(ExceptionTranslator &&translator) {
3342 detail::with_exception_translators(
3343 [&](std::forward_list<ExceptionTranslator> &exception_translators,
3344 std::forward_list<ExceptionTranslator> &local_exception_translators) {
3345 (void) local_exception_translators;
3346 exception_translators.push_front(std::forward<ExceptionTranslator>(translator));
3347 });
3348 }
3349
3350
3351
3352
3353
3354
3355
3356 inline void register_local_exception_translator(ExceptionTranslator &&translator) {
3357 detail::with_exception_translators(
3358 [&](std::forward_list<ExceptionTranslator> &exception_translators,
3359 std::forward_list<ExceptionTranslator> &local_exception_translators) {
3360 (void) exception_translators;
3361 local_exception_translators.push_front(std::forward<ExceptionTranslator>(translator));
3362 });
3363 }
3364
3365
3366
3367
3368
3369
3370
3371
3372 template <typename type>
3373 class exception : public object {
3374 public:
3375 exception() = default;
3376 exception(handle scope, const char *name, handle base = PyExc_Exception) {
3377 std::string full_name
3378 = scope.attr("__name__").cast<std::string>() + std::string(".") + name;
3379 m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), nullptr);
3380 if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name)) {
3381 pybind11_fail("Error during initialization: multiple incompatible "
3382 "definitions with name \""
3383 + std::string(name) + "\"");
3384 }
3385 scope.attr(name) = *this;
3386 }
3387
3388
3389 PYBIND11_DEPRECATED("Please use py::set_error() instead "
3390 "(https://github.com/pybind/pybind11/pull/4772)")
3391 void operator()(const char *message) const { set_error(*this, message); }
3392 };
3393
3394 PYBIND11_NAMESPACE_BEGIN(detail)
3395
3396 template <>
3397 struct handle_type_name<exception<void>> {
3398 static constexpr auto name = const_name("Exception");
3399 };
3400
3401
3402 template <typename CppException>
3403 exception<CppException> &
3404 register_exception_impl(handle scope, const char *name, handle base, bool isLocal) {
3405 PYBIND11_CONSTINIT static gil_safe_call_once_and_store<exception<CppException>> exc_storage;
3406 exc_storage.call_once_and_store_result(
3407 [&]() { return exception<CppException>(scope, name, base); });
3408
3409 auto register_func
3410 = isLocal ? ®ister_local_exception_translator : ®ister_exception_translator;
3411
3412 register_func([](std::exception_ptr p) {
3413 if (!p) {
3414 return;
3415 }
3416 try {
3417 std::rethrow_exception(p);
3418 } catch (const CppException &e) {
3419 set_error(exc_storage.get_stored(), e.what());
3420 }
3421 });
3422 return exc_storage.get_stored();
3423 }
3424
3425 PYBIND11_NAMESPACE_END(detail)
3426
3427
3428
3429
3430
3431
3432
3433 template <typename CppException>
3434 exception<CppException> &
3435 register_exception(handle scope, const char *name, handle base = PyExc_Exception) {
3436 return detail::register_exception_impl<CppException>(scope, name, base, false );
3437 }
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447 template <typename CppException>
3448 exception<CppException> &
3449 register_local_exception(handle scope, const char *name, handle base = PyExc_Exception) {
3450 return detail::register_exception_impl<CppException>(scope, name, base, true );
3451 }
3452
3453 PYBIND11_NAMESPACE_BEGIN(detail)
3454 PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) {
3455 auto strings = tuple(args.size());
3456 for (size_t i = 0; i < args.size(); ++i) {
3457 strings[i] = str(args[i]);
3458 }
3459 auto sep = kwargs.contains("sep") ? kwargs["sep"] : str(" ");
3460 auto line = sep.attr("join")(std::move(strings));
3461
3462 object file;
3463 if (kwargs.contains("file")) {
3464 file = kwargs["file"].cast<object>();
3465 } else {
3466 try {
3467 file = module_::import("sys").attr("stdout");
3468 } catch (const error_already_set &) {
3469
3470
3471
3472
3473 return;
3474 }
3475 }
3476
3477 auto write = file.attr("write");
3478 write(std::move(line));
3479 write(kwargs.contains("end") ? kwargs["end"] : str("\n"));
3480
3481 if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) {
3482 file.attr("flush")();
3483 }
3484 }
3485 PYBIND11_NAMESPACE_END(detail)
3486
3487 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
3488 void print(Args &&...args) {
3489 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
3490 detail::print(c.args(), c.kwargs());
3491 }
3492
3493 inline void
3494 error_already_set::m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr) {
3495 gil_scoped_acquire gil;
3496 error_scope scope;
3497 delete raw_ptr;
3498 }
3499
3500 inline const char *error_already_set::what() const noexcept {
3501 gil_scoped_acquire gil;
3502 error_scope scope;
3503 return m_fetched_error->error_string().c_str();
3504 }
3505
3506 PYBIND11_NAMESPACE_BEGIN(detail)
3507
3508 inline function
3509 get_type_override(const void *this_ptr, const type_info *this_type, const char *name) {
3510 handle self = get_object_handle(this_ptr, this_type);
3511 if (!self) {
3512 return function();
3513 }
3514 handle type = type::handle_of(self);
3515 auto key = std::make_pair(type.ptr(), name);
3516
3517
3518
3519 bool not_overridden = with_internals([&key](internals &internals) {
3520 auto &cache = internals.inactive_override_cache;
3521 return cache.find(key) != cache.end();
3522 });
3523 if (not_overridden) {
3524 return function();
3525 }
3526
3527 function override = getattr(self, name, function());
3528 if (override.is_cpp_function()) {
3529 with_internals([&](internals &internals) {
3530 internals.inactive_override_cache.insert(std::move(key));
3531 });
3532 return function();
3533 }
3534
3535
3536
3537 #if !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON)
3538 # if PY_VERSION_HEX >= 0x03090000
3539 PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
3540 if (frame != nullptr) {
3541 PyCodeObject *f_code = PyFrame_GetCode(frame);
3542
3543 if (std::string(str(f_code->co_name)) == name && f_code->co_argcount > 0) {
3544 # if PY_VERSION_HEX >= 0x030d0000
3545 PyObject *locals = PyEval_GetFrameLocals();
3546 # else
3547 PyObject *locals = PyEval_GetLocals();
3548 Py_XINCREF(locals);
3549 # endif
3550 if (locals != nullptr) {
3551 # if PY_VERSION_HEX >= 0x030b0000
3552 PyObject *co_varnames = PyCode_GetVarnames(f_code);
3553 # else
3554 PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code, "co_varnames");
3555 # endif
3556 PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
3557 Py_DECREF(co_varnames);
3558 PyObject *self_caller = dict_getitem(locals, self_arg);
3559 Py_DECREF(locals);
3560 if (self_caller == self.ptr()) {
3561 Py_DECREF(f_code);
3562 Py_DECREF(frame);
3563 return function();
3564 }
3565 }
3566 }
3567 Py_DECREF(f_code);
3568 Py_DECREF(frame);
3569 }
3570 # else
3571 PyFrameObject *frame = PyThreadState_Get()->frame;
3572 if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name
3573 && frame->f_code->co_argcount > 0) {
3574 PyFrame_FastToLocals(frame);
3575 PyObject *self_caller
3576 = dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
3577 if (self_caller == self.ptr()) {
3578 return function();
3579 }
3580 }
3581 # endif
3582
3583 #else
3584
3585
3586
3587 dict d;
3588 d["self"] = self;
3589 d["name"] = pybind11::str(name);
3590 PyObject *result
3591 = PyRun_String("import inspect\n"
3592 "frame = inspect.currentframe()\n"
3593 "if frame is not None:\n"
3594 " frame = frame.f_back\n"
3595 " if frame is not None and str(frame.f_code.co_name) == name and "
3596 "frame.f_code.co_argcount > 0:\n"
3597 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
3598 " if self_caller == self:\n"
3599 " self = None\n",
3600 Py_file_input,
3601 d.ptr(),
3602 d.ptr());
3603 if (result == nullptr)
3604 throw error_already_set();
3605 Py_DECREF(result);
3606 if (d["self"].is_none())
3607 return function();
3608 #endif
3609
3610 return override;
3611 }
3612 PYBIND11_NAMESPACE_END(detail)
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623 template <class T>
3624 function get_override(const T *this_ptr, const char *name) {
3625 auto *tinfo = detail::get_type_info(typeid(T));
3626 return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
3627 }
3628
3629 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
3630 do { \
3631 pybind11::gil_scoped_acquire gil; \
3632 pybind11::function override \
3633 = pybind11::get_override(static_cast<const cname *>(this), name); \
3634 if (override) { \
3635 auto o = override(__VA_ARGS__); \
3636 PYBIND11_WARNING_PUSH \
3637 PYBIND11_WARNING_DISABLE_MSVC(4127) \
3638 if PYBIND11_MAYBE_CONSTEXPR ( \
3639 pybind11::detail::cast_is_temporary_value_reference<ret_type>::value \
3640 && !pybind11::detail::is_same_ignoring_cvref<ret_type, PyObject *>::value) { \
3641 static pybind11::detail::override_caster_t<ret_type> caster; \
3642 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
3643 } else { \
3644 return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
3645 } \
3646 PYBIND11_WARNING_POP \
3647 } \
3648 } while (false)
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
3669 do { \
3670 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
3671 return cname::fn(__VA_ARGS__); \
3672 } while (false)
3673
3674
3675
3676
3677
3678 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
3679 do { \
3680 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
3681 pybind11::pybind11_fail( \
3682 "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
3683 } while (false)
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
3711 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
3712
3713
3714
3715
3716
3717 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
3718 PYBIND11_OVERRIDE_PURE_NAME( \
3719 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
3720
3721
3722
3723 PYBIND11_DEPRECATED("get_type_overload has been deprecated")
3724 inline function
3725 get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
3726 return detail::get_type_override(this_ptr, this_type, name);
3727 }
3728
3729 template <class T>
3730 inline function get_overload(const T *this_ptr, const char *name) {
3731 return get_override(this_ptr, name);
3732 }
3733
3734 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
3735 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
3736 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
3737 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
3738 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
3739 PYBIND11_OVERRIDE_PURE_NAME( \
3740 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
3741 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
3742 PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
3743 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
3744 PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
3745
3746 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)