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