Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 10:17:49

0001 /*
0002     pybind11/pybind11.h: Main header file of the C++11 python
0003     binding generator library
0004 
0005     Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
0006 
0007     All rights reserved. Use of this source code is governed by a
0008     BSD-style license that can be found in the LICENSE file.
0009 */
0010 
0011 #pragma once
0012 
0013 #include "detail/class.h"
0014 #include "detail/init.h"
0015 #include "attr.h"
0016 #include "gil.h"
0017 #include "options.h"
0018 
0019 #include <cstdlib>
0020 #include <cstring>
0021 #include <memory>
0022 #include <new>
0023 #include <string>
0024 #include <utility>
0025 #include <vector>
0026 
0027 #if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914))
0028 #    define PYBIND11_STD_LAUNDER std::launder
0029 #    define PYBIND11_HAS_STD_LAUNDER 1
0030 #else
0031 #    define PYBIND11_STD_LAUNDER
0032 #    define PYBIND11_HAS_STD_LAUNDER 0
0033 #endif
0034 #if defined(__GNUG__) && !defined(__clang__)
0035 #    include <cxxabi.h>
0036 #endif
0037 
0038 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0039 
0040 /* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning
0041    This warning is about ABI compatibility, not code health.
0042    It is only actually needed in a couple places, but apparently GCC 7 "generates this warning if
0043    and only if the first template instantiation ... involves noexcept" [stackoverflow], therefore
0044    it could get triggered from seemingly random places, depending on user code.
0045    No other GCC version generates this warning.
0046  */
0047 #if defined(__GNUC__) && __GNUC__ == 7
0048 PYBIND11_WARNING_DISABLE_GCC("-Wnoexcept-type")
0049 #endif
0050 
0051 PYBIND11_WARNING_DISABLE_MSVC(4127)
0052 
0053 PYBIND11_NAMESPACE_BEGIN(detail)
0054 
0055 // Apply all the extensions translators from a list
0056 // Return true if one of the translators completed without raising an exception
0057 // itself. Return of false indicates that if there are other translators
0058 // available, they should be tried.
0059 inline bool apply_exception_translators(std::forward_list<ExceptionTranslator> &translators) {
0060     auto last_exception = std::current_exception();
0061 
0062     for (auto &translator : translators) {
0063         try {
0064             translator(last_exception);
0065             return true;
0066         } catch (...) {
0067             last_exception = std::current_exception();
0068         }
0069     }
0070     return false;
0071 }
0072 
0073 #if defined(_MSC_VER)
0074 #    define PYBIND11_COMPAT_STRDUP _strdup
0075 #else
0076 #    define PYBIND11_COMPAT_STRDUP strdup
0077 #endif
0078 
0079 PYBIND11_NAMESPACE_END(detail)
0080 
0081 /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
0082 class cpp_function : public function {
0083 public:
0084     cpp_function() = default;
0085     // NOLINTNEXTLINE(google-explicit-constructor)
0086     cpp_function(std::nullptr_t) {}
0087 
0088     /// Construct a cpp_function from a vanilla function pointer
0089     template <typename Return, typename... Args, typename... Extra>
0090     // NOLINTNEXTLINE(google-explicit-constructor)
0091     cpp_function(Return (*f)(Args...), const Extra &...extra) {
0092         initialize(f, f, extra...);
0093     }
0094 
0095     /// Construct a cpp_function from a lambda function (possibly with internal state)
0096     template <typename Func,
0097               typename... Extra,
0098               typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
0099     // NOLINTNEXTLINE(google-explicit-constructor)
0100     cpp_function(Func &&f, const Extra &...extra) {
0101         initialize(
0102             std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...);
0103     }
0104 
0105     /// Construct a cpp_function from a class method (non-const, no ref-qualifier)
0106     template <typename Return, typename Class, typename... Arg, typename... Extra>
0107     // NOLINTNEXTLINE(google-explicit-constructor)
0108     cpp_function(Return (Class::*f)(Arg...), const Extra &...extra) {
0109         initialize(
0110             [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0111             (Return(*)(Class *, Arg...)) nullptr,
0112             extra...);
0113     }
0114 
0115     /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier)
0116     /// A copy of the overload for non-const functions without explicit ref-qualifier
0117     /// but with an added `&`.
0118     template <typename Return, typename Class, typename... Arg, typename... Extra>
0119     // NOLINTNEXTLINE(google-explicit-constructor)
0120     cpp_function(Return (Class::*f)(Arg...) &, const Extra &...extra) {
0121         initialize(
0122             [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0123             (Return(*)(Class *, Arg...)) nullptr,
0124             extra...);
0125     }
0126 
0127     /// Construct a cpp_function from a class method (const, no ref-qualifier)
0128     template <typename Return, typename Class, typename... Arg, typename... Extra>
0129     // NOLINTNEXTLINE(google-explicit-constructor)
0130     cpp_function(Return (Class::*f)(Arg...) const, const Extra &...extra) {
0131         initialize([f](const Class *c,
0132                        Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0133                    (Return(*)(const Class *, Arg...)) nullptr,
0134                    extra...);
0135     }
0136 
0137     /// Construct a cpp_function from a class method (const, lvalue ref-qualifier)
0138     /// A copy of the overload for const functions without explicit ref-qualifier
0139     /// but with an added `&`.
0140     template <typename Return, typename Class, typename... Arg, typename... Extra>
0141     // NOLINTNEXTLINE(google-explicit-constructor)
0142     cpp_function(Return (Class::*f)(Arg...) const &, const Extra &...extra) {
0143         initialize([f](const Class *c,
0144                        Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0145                    (Return(*)(const Class *, Arg...)) nullptr,
0146                    extra...);
0147     }
0148 
0149     /// Return the function name
0150     object name() const { return attr("__name__"); }
0151 
0152 protected:
0153     struct InitializingFunctionRecordDeleter {
0154         // `destruct(function_record, false)`: `initialize_generic` copies strings and
0155         // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`.
0156         void operator()(detail::function_record *rec) { destruct(rec, false); }
0157     };
0158     using unique_function_record
0159         = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
0160 
0161     /// Space optimization: don't inline this frequently instantiated fragment
0162     PYBIND11_NOINLINE unique_function_record make_function_record() {
0163         return unique_function_record(new detail::function_record());
0164     }
0165 
0166     /// Special internal constructor for functors, lambda functions, etc.
0167     template <typename Func, typename Return, typename... Args, typename... Extra>
0168     void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) {
0169         using namespace detail;
0170         struct capture {
0171             remove_reference_t<Func> f;
0172         };
0173 
0174         /* Store the function including any extra state it might have (e.g. a lambda capture
0175          * object) */
0176         // The unique_ptr makes sure nothing is leaked in case of an exception.
0177         auto unique_rec = make_function_record();
0178         auto *rec = unique_rec.get();
0179 
0180         /* Store the capture object directly in the function record if there is enough space */
0181         if (sizeof(capture) <= sizeof(rec->data)) {
0182             /* Without these pragmas, GCC warns that there might not be
0183                enough space to use the placement new operator. However, the
0184                'if' statement above ensures that this is the case. */
0185             PYBIND11_WARNING_PUSH
0186 
0187 #if defined(__GNUG__) && __GNUC__ >= 6
0188             PYBIND11_WARNING_DISABLE_GCC("-Wplacement-new")
0189 #endif
0190 
0191             new ((capture *) &rec->data) capture{std::forward<Func>(f)};
0192 
0193 #if !PYBIND11_HAS_STD_LAUNDER
0194             PYBIND11_WARNING_DISABLE_GCC("-Wstrict-aliasing")
0195 #endif
0196 
0197             // UB without std::launder, but without breaking ABI and/or
0198             // a significant refactoring it's "impossible" to solve.
0199             if (!std::is_trivially_destructible<capture>::value) {
0200                 rec->free_data = [](function_record *r) {
0201                     auto data = PYBIND11_STD_LAUNDER((capture *) &r->data);
0202                     (void) data;
0203                     data->~capture();
0204                 };
0205             }
0206             PYBIND11_WARNING_POP
0207         } else {
0208             rec->data[0] = new capture{std::forward<Func>(f)};
0209             rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
0210         }
0211 
0212         /* Type casters for the function arguments and return value */
0213         using cast_in = argument_loader<Args...>;
0214         using cast_out
0215             = make_caster<conditional_t<std::is_void<Return>::value, void_type, Return>>;
0216 
0217         static_assert(
0218             expected_num_args<Extra...>(
0219                 sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
0220             "The number of argument annotations does not match the number of function arguments");
0221 
0222         /* Dispatch code which converts function arguments and performs the actual function call */
0223         rec->impl = [](function_call &call) -> handle {
0224             cast_in args_converter;
0225 
0226             /* Try to cast the function arguments into the C++ domain */
0227             if (!args_converter.load_args(call)) {
0228                 return PYBIND11_TRY_NEXT_OVERLOAD;
0229             }
0230 
0231             /* Invoke call policy pre-call hook */
0232             process_attributes<Extra...>::precall(call);
0233 
0234             /* Get a pointer to the capture object */
0235             const auto *data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data
0236                                                                           : call.func.data[0]);
0237             auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
0238 
0239             /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
0240             return_value_policy policy
0241                 = return_value_policy_override<Return>::policy(call.func.policy);
0242 
0243             /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
0244             using Guard = extract_guard_t<Extra...>;
0245 
0246             /* Perform the function call */
0247             handle result
0248                 = cast_out::cast(std::move(args_converter).template call<Return, Guard>(cap->f),
0249                                  policy,
0250                                  call.parent);
0251 
0252             /* Invoke call policy post-call hook */
0253             process_attributes<Extra...>::postcall(call, result);
0254 
0255             return result;
0256         };
0257 
0258         rec->nargs_pos = cast_in::args_pos >= 0
0259                              ? static_cast<std::uint16_t>(cast_in::args_pos)
0260                              : sizeof...(Args) - cast_in::has_kwargs; // Will get reduced more if
0261                                                                       // we have a kw_only
0262         rec->has_args = cast_in::args_pos >= 0;
0263         rec->has_kwargs = cast_in::has_kwargs;
0264 
0265         /* Process any user-provided function attributes */
0266         process_attributes<Extra...>::init(extra..., rec);
0267 
0268         {
0269             constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
0270                            has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
0271                            has_arg_annotations = any_of<is_keyword<Extra>...>::value;
0272             static_assert(has_arg_annotations || !has_kw_only_args,
0273                           "py::kw_only requires the use of argument annotations");
0274             static_assert(has_arg_annotations || !has_pos_only_args,
0275                           "py::pos_only requires the use of argument annotations (for docstrings "
0276                           "and aligning the annotations to the argument)");
0277 
0278             static_assert(constexpr_sum(is_kw_only<Extra>::value...) <= 1,
0279                           "py::kw_only may be specified only once");
0280             static_assert(constexpr_sum(is_pos_only<Extra>::value...) <= 1,
0281                           "py::pos_only may be specified only once");
0282             constexpr auto kw_only_pos = constexpr_first<is_kw_only, Extra...>();
0283             constexpr auto pos_only_pos = constexpr_first<is_pos_only, Extra...>();
0284             static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
0285                           "py::pos_only must come before py::kw_only");
0286         }
0287 
0288         /* Generate a readable signature describing the function's arguments and return
0289            value types */
0290         static constexpr auto signature
0291             = const_name("(") + cast_in::arg_names + const_name(") -> ") + cast_out::name;
0292         PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
0293 
0294         /* Register the function with Python from generic (non-templated) code */
0295         // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid.
0296         initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));
0297 
0298         /* Stash some additional information used by an important optimization in 'functional.h' */
0299         using FunctionType = Return (*)(Args...);
0300         constexpr bool is_function_ptr
0301             = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *);
0302         if (is_function_ptr) {
0303             rec->is_stateless = true;
0304             rec->data[1]
0305                 = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
0306         }
0307     }
0308 
0309     // Utility class that keeps track of all duplicated strings, and cleans them up in its
0310     // destructor, unless they are released. Basically a RAII-solution to deal with exceptions
0311     // along the way.
0312     class strdup_guard {
0313     public:
0314         strdup_guard() = default;
0315         strdup_guard(const strdup_guard &) = delete;
0316         strdup_guard &operator=(const strdup_guard &) = delete;
0317 
0318         ~strdup_guard() {
0319             for (auto *s : strings) {
0320                 std::free(s);
0321             }
0322         }
0323         char *operator()(const char *s) {
0324             auto *t = PYBIND11_COMPAT_STRDUP(s);
0325             strings.push_back(t);
0326             return t;
0327         }
0328         void release() { strings.clear(); }
0329 
0330     private:
0331         std::vector<char *> strings;
0332     };
0333 
0334     /// Register a function call with Python (generic non-templated code goes here)
0335     void initialize_generic(unique_function_record &&unique_rec,
0336                             const char *text,
0337                             const std::type_info *const *types,
0338                             size_t args) {
0339         // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr,
0340         // we do not want this to destruct the pointer. `initialize` (the caller) still relies on
0341         // the pointee being alive after this call. Only move out if a `capsule` is going to keep
0342         // it alive.
0343         auto *rec = unique_rec.get();
0344 
0345         // Keep track of strdup'ed strings, and clean them up as long as the function's capsule
0346         // has not taken ownership yet (when `unique_rec.release()` is called).
0347         // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the
0348         // strings are only referenced before strdup'ing. So only *after* the following block could
0349         // `destruct` safely be called, but even then, `repr` could still throw in the middle of
0350         // copying all strings.
0351         strdup_guard guarded_strdup;
0352 
0353         /* Create copies of all referenced C-style strings */
0354         rec->name = guarded_strdup(rec->name ? rec->name : "");
0355         if (rec->doc) {
0356             rec->doc = guarded_strdup(rec->doc);
0357         }
0358         for (auto &a : rec->args) {
0359             if (a.name) {
0360                 a.name = guarded_strdup(a.name);
0361             }
0362             if (a.descr) {
0363                 a.descr = guarded_strdup(a.descr);
0364             } else if (a.value) {
0365                 a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());
0366             }
0367         }
0368 
0369         rec->is_constructor = (std::strcmp(rec->name, "__init__") == 0)
0370                               || (std::strcmp(rec->name, "__setstate__") == 0);
0371 
0372 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
0373         if (rec->is_constructor && !rec->is_new_style_constructor) {
0374             const auto class_name
0375                 = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
0376             const auto func_name = std::string(rec->name);
0377             PyErr_WarnEx(PyExc_FutureWarning,
0378                          ("pybind11-bound class '" + class_name
0379                           + "' is using an old-style "
0380                             "placement-new '"
0381                           + func_name
0382                           + "' which has been deprecated. See "
0383                             "the upgrade guide in pybind11's docs. This message is only visible "
0384                             "when compiled in debug mode.")
0385                              .c_str(),
0386                          0);
0387         }
0388 #endif
0389 
0390         /* Generate a proper function signature */
0391         std::string signature;
0392         size_t type_index = 0, arg_index = 0;
0393         bool is_starred = false;
0394         for (const auto *pc = text; *pc != '\0'; ++pc) {
0395             const auto c = *pc;
0396 
0397             if (c == '{') {
0398                 // Write arg name for everything except *args and **kwargs.
0399                 is_starred = *(pc + 1) == '*';
0400                 if (is_starred) {
0401                     continue;
0402                 }
0403                 // Separator for keyword-only arguments, placed before the kw
0404                 // arguments start (unless we are already putting an *args)
0405                 if (!rec->has_args && arg_index == rec->nargs_pos) {
0406                     signature += "*, ";
0407                 }
0408                 if (arg_index < rec->args.size() && rec->args[arg_index].name) {
0409                     signature += rec->args[arg_index].name;
0410                 } else if (arg_index == 0 && rec->is_method) {
0411                     signature += "self";
0412                 } else {
0413                     signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
0414                 }
0415                 signature += ": ";
0416             } else if (c == '}') {
0417                 // Write default value if available.
0418                 if (!is_starred && arg_index < rec->args.size() && rec->args[arg_index].descr) {
0419                     signature += " = ";
0420                     signature += rec->args[arg_index].descr;
0421                 }
0422                 // Separator for positional-only arguments (placed after the
0423                 // argument, rather than before like *
0424                 if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
0425                     signature += ", /";
0426                 }
0427                 if (!is_starred) {
0428                     arg_index++;
0429                 }
0430             } else if (c == '%') {
0431                 const std::type_info *t = types[type_index++];
0432                 if (!t) {
0433                     pybind11_fail("Internal error while parsing type signature (1)");
0434                 }
0435                 if (auto *tinfo = detail::get_type_info(*t)) {
0436                     handle th((PyObject *) tinfo->type);
0437                     signature += th.attr("__module__").cast<std::string>() + "."
0438                                  + th.attr("__qualname__").cast<std::string>();
0439                 } else if (rec->is_new_style_constructor && arg_index == 0) {
0440                     // A new-style `__init__` takes `self` as `value_and_holder`.
0441                     // Rewrite it to the proper class type.
0442                     signature += rec->scope.attr("__module__").cast<std::string>() + "."
0443                                  + rec->scope.attr("__qualname__").cast<std::string>();
0444                 } else {
0445                     std::string tname(t->name());
0446                     detail::clean_type_id(tname);
0447                     signature += tname;
0448                 }
0449             } else {
0450                 signature += c;
0451             }
0452         }
0453 
0454         if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] != nullptr) {
0455             pybind11_fail("Internal error while parsing type signature (2)");
0456         }
0457 
0458         rec->signature = guarded_strdup(signature.c_str());
0459         rec->args.shrink_to_fit();
0460         rec->nargs = (std::uint16_t) args;
0461 
0462         if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) {
0463             rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
0464         }
0465 
0466         detail::function_record *chain = nullptr, *chain_start = rec;
0467         if (rec->sibling) {
0468             if (PyCFunction_Check(rec->sibling.ptr())) {
0469                 auto *self = PyCFunction_GET_SELF(rec->sibling.ptr());
0470                 if (!isinstance<capsule>(self)) {
0471                     chain = nullptr;
0472                 } else {
0473                     auto rec_capsule = reinterpret_borrow<capsule>(self);
0474                     if (detail::is_function_record_capsule(rec_capsule)) {
0475                         chain = rec_capsule.get_pointer<detail::function_record>();
0476                         /* Never append a method to an overload chain of a parent class;
0477                            instead, hide the parent's overloads in this case */
0478                         if (!chain->scope.is(rec->scope)) {
0479                             chain = nullptr;
0480                         }
0481                     } else {
0482                         chain = nullptr;
0483                     }
0484                 }
0485             }
0486             // Don't trigger for things like the default __init__, which are wrapper_descriptors
0487             // that we are intentionally replacing
0488             else if (!rec->sibling.is_none() && rec->name[0] != '_') {
0489                 pybind11_fail("Cannot overload existing non-function object \""
0490                               + std::string(rec->name) + "\" with a function of the same name");
0491             }
0492         }
0493 
0494         if (!chain) {
0495             /* No existing overload was found, create a new function object */
0496             rec->def = new PyMethodDef();
0497             std::memset(rec->def, 0, sizeof(PyMethodDef));
0498             rec->def->ml_name = rec->name;
0499             rec->def->ml_meth
0500                 = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher));
0501             rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
0502 
0503             capsule rec_capsule(unique_rec.release(),
0504                                 [](void *ptr) { destruct((detail::function_record *) ptr); });
0505             rec_capsule.set_name(detail::get_function_record_capsule_name());
0506             guarded_strdup.release();
0507 
0508             object scope_module;
0509             if (rec->scope) {
0510                 if (hasattr(rec->scope, "__module__")) {
0511                     scope_module = rec->scope.attr("__module__");
0512                 } else if (hasattr(rec->scope, "__name__")) {
0513                     scope_module = rec->scope.attr("__name__");
0514                 }
0515             }
0516 
0517             m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
0518             if (!m_ptr) {
0519                 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
0520             }
0521         } else {
0522             /* Append at the beginning or end of the overload chain */
0523             m_ptr = rec->sibling.ptr();
0524             inc_ref();
0525             if (chain->is_method != rec->is_method) {
0526                 pybind11_fail(
0527                     "overloading a method with both static and instance methods is not supported; "
0528 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
0529                     "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more "
0530                     "details"
0531 #else
0532                     "error while attempting to bind "
0533                     + std::string(rec->is_method ? "instance" : "static") + " method "
0534                     + std::string(pybind11::str(rec->scope.attr("__name__"))) + "."
0535                     + std::string(rec->name) + signature
0536 #endif
0537                 );
0538             }
0539 
0540             if (rec->prepend) {
0541                 // Beginning of chain; we need to replace the capsule's current head-of-the-chain
0542                 // pointer with this one, then make this one point to the previous head of the
0543                 // chain.
0544                 chain_start = rec;
0545                 rec->next = chain;
0546                 auto rec_capsule
0547                     = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self);
0548                 rec_capsule.set_pointer(unique_rec.release());
0549                 guarded_strdup.release();
0550             } else {
0551                 // Or end of chain (normal behavior)
0552                 chain_start = chain;
0553                 while (chain->next) {
0554                     chain = chain->next;
0555                 }
0556                 chain->next = unique_rec.release();
0557                 guarded_strdup.release();
0558             }
0559         }
0560 
0561         std::string signatures;
0562         int index = 0;
0563         /* Create a nice pydoc rec including all signatures and
0564            docstrings of the functions in the overload chain */
0565         if (chain && options::show_function_signatures()) {
0566             // First a generic signature
0567             signatures += rec->name;
0568             signatures += "(*args, **kwargs)\n";
0569             signatures += "Overloaded function.\n\n";
0570         }
0571         // Then specific overload signatures
0572         bool first_user_def = true;
0573         for (auto *it = chain_start; it != nullptr; it = it->next) {
0574             if (options::show_function_signatures()) {
0575                 if (index > 0) {
0576                     signatures += '\n';
0577                 }
0578                 if (chain) {
0579                     signatures += std::to_string(++index) + ". ";
0580                 }
0581                 signatures += rec->name;
0582                 signatures += it->signature;
0583                 signatures += '\n';
0584             }
0585             if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) {
0586                 // If we're appending another docstring, and aren't printing function signatures,
0587                 // we need to append a newline first:
0588                 if (!options::show_function_signatures()) {
0589                     if (first_user_def) {
0590                         first_user_def = false;
0591                     } else {
0592                         signatures += '\n';
0593                     }
0594                 }
0595                 if (options::show_function_signatures()) {
0596                     signatures += '\n';
0597                 }
0598                 signatures += it->doc;
0599                 if (options::show_function_signatures()) {
0600                     signatures += '\n';
0601                 }
0602             }
0603         }
0604 
0605         /* Install docstring */
0606         auto *func = (PyCFunctionObject *) m_ptr;
0607         std::free(const_cast<char *>(func->m_ml->ml_doc));
0608         // Install docstring if it's non-empty (when at least one option is enabled)
0609         func->m_ml->ml_doc
0610             = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());
0611 
0612         if (rec->is_method) {
0613             m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
0614             if (!m_ptr) {
0615                 pybind11_fail(
0616                     "cpp_function::cpp_function(): Could not allocate instance method object");
0617             }
0618             Py_DECREF(func);
0619         }
0620     }
0621 
0622     /// When a cpp_function is GCed, release any memory allocated by pybind11
0623     static void destruct(detail::function_record *rec, bool free_strings = true) {
0624 // If on Python 3.9, check the interpreter "MICRO" (patch) version.
0625 // If this is running on 3.9.0, we have to work around a bug.
0626 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
0627         static bool is_zero = Py_GetVersion()[4] == '0';
0628 #endif
0629 
0630         while (rec) {
0631             detail::function_record *next = rec->next;
0632             if (rec->free_data) {
0633                 rec->free_data(rec);
0634             }
0635             // During initialization, these strings might not have been copied yet,
0636             // so they cannot be freed. Once the function has been created, they can.
0637             // Check `make_function_record` for more details.
0638             if (free_strings) {
0639                 std::free((char *) rec->name);
0640                 std::free((char *) rec->doc);
0641                 std::free((char *) rec->signature);
0642                 for (auto &arg : rec->args) {
0643                     std::free(const_cast<char *>(arg.name));
0644                     std::free(const_cast<char *>(arg.descr));
0645                 }
0646             }
0647             for (auto &arg : rec->args) {
0648                 arg.value.dec_ref();
0649             }
0650             if (rec->def) {
0651                 std::free(const_cast<char *>(rec->def->ml_doc));
0652 // Python 3.9.0 decref's these in the wrong order; rec->def
0653 // If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)
0654 // See https://github.com/python/cpython/pull/22670
0655 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
0656                 if (!is_zero) {
0657                     delete rec->def;
0658                 }
0659 #else
0660                 delete rec->def;
0661 #endif
0662             }
0663             delete rec;
0664             rec = next;
0665         }
0666     }
0667 
0668     /// Main dispatch logic for calls to functions bound using pybind11
0669     static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
0670         using namespace detail;
0671         assert(isinstance<capsule>(self));
0672 
0673         /* Iterator over the list of potentially admissible overloads */
0674         const function_record *overloads = reinterpret_cast<function_record *>(
0675                                   PyCapsule_GetPointer(self, get_function_record_capsule_name())),
0676                               *it = overloads;
0677         assert(overloads != nullptr);
0678 
0679         /* Need to know how many arguments + keyword arguments there are to pick the right
0680            overload */
0681         const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
0682 
0683         handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
0684                result = PYBIND11_TRY_NEXT_OVERLOAD;
0685 
0686         auto self_value_and_holder = value_and_holder();
0687         if (overloads->is_constructor) {
0688             if (!parent
0689                 || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
0690                 PyErr_SetString(
0691                     PyExc_TypeError,
0692                     "__init__(self, ...) called with invalid or missing `self` argument");
0693                 return nullptr;
0694             }
0695 
0696             auto *const tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
0697             auto *const pi = reinterpret_cast<instance *>(parent.ptr());
0698             self_value_and_holder = pi->get_value_and_holder(tinfo, true);
0699 
0700             // If this value is already registered it must mean __init__ is invoked multiple times;
0701             // we really can't support that in C++, so just ignore the second __init__.
0702             if (self_value_and_holder.instance_registered()) {
0703                 return none().release().ptr();
0704             }
0705         }
0706 
0707         try {
0708             // We do this in two passes: in the first pass, we load arguments with `convert=false`;
0709             // in the second, we allow conversion (except for arguments with an explicit
0710             // py::arg().noconvert()).  This lets us prefer calls without conversion, with
0711             // conversion as a fallback.
0712             std::vector<function_call> second_pass;
0713 
0714             // However, if there are no overloads, we can just skip the no-convert pass entirely
0715             const bool overloaded = it != nullptr && it->next != nullptr;
0716 
0717             for (; it != nullptr; it = it->next) {
0718 
0719                 /* For each overload:
0720                    1. Copy all positional arguments we were given, also checking to make sure that
0721                       named positional arguments weren't *also* specified via kwarg.
0722                    2. If we weren't given enough, try to make up the omitted ones by checking
0723                       whether they were provided by a kwarg matching the `py::arg("name")` name. If
0724                       so, use it (and remove it from kwargs); if not, see if the function binding
0725                       provided a default that we can use.
0726                    3. Ensure that either all keyword arguments were "consumed", or that the
0727                    function takes a kwargs argument to accept unconsumed kwargs.
0728                    4. Any positional arguments still left get put into a tuple (for args), and any
0729                       leftover kwargs get put into a dict.
0730                    5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
0731                       extra tuple or dict at the end of the positional arguments.
0732                    6. Call the function call dispatcher (function_record::impl)
0733 
0734                    If one of these fail, move on to the next overload and keep trying until we get
0735                    a result other than PYBIND11_TRY_NEXT_OVERLOAD.
0736                  */
0737 
0738                 const function_record &func = *it;
0739                 size_t num_args = func.nargs; // Number of positional arguments that we need
0740                 if (func.has_args) {
0741                     --num_args; // (but don't count py::args
0742                 }
0743                 if (func.has_kwargs) {
0744                     --num_args; //  or py::kwargs)
0745                 }
0746                 size_t pos_args = func.nargs_pos;
0747 
0748                 if (!func.has_args && n_args_in > pos_args) {
0749                     continue; // Too many positional arguments for this overload
0750                 }
0751 
0752                 if (n_args_in < pos_args && func.args.size() < pos_args) {
0753                     continue; // Not enough positional arguments given, and not enough defaults to
0754                               // fill in the blanks
0755                 }
0756 
0757                 function_call call(func, parent);
0758 
0759                 // Protect std::min with parentheses
0760                 size_t args_to_copy = (std::min)(pos_args, n_args_in);
0761                 size_t args_copied = 0;
0762 
0763                 // 0. Inject new-style `self` argument
0764                 if (func.is_new_style_constructor) {
0765                     // The `value` may have been preallocated by an old-style `__init__`
0766                     // if it was a preceding candidate for overload resolution.
0767                     if (self_value_and_holder) {
0768                         self_value_and_holder.type->dealloc(self_value_and_holder);
0769                     }
0770 
0771                     call.init_self = PyTuple_GET_ITEM(args_in, 0);
0772                     call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
0773                     call.args_convert.push_back(false);
0774                     ++args_copied;
0775                 }
0776 
0777                 // 1. Copy any position arguments given.
0778                 bool bad_arg = false;
0779                 for (; args_copied < args_to_copy; ++args_copied) {
0780                     const argument_record *arg_rec
0781                         = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
0782                     if (kwargs_in && arg_rec && arg_rec->name
0783                         && dict_getitemstring(kwargs_in, arg_rec->name)) {
0784                         bad_arg = true;
0785                         break;
0786                     }
0787 
0788                     handle arg(PyTuple_GET_ITEM(args_in, args_copied));
0789                     if (arg_rec && !arg_rec->none && arg.is_none()) {
0790                         bad_arg = true;
0791                         break;
0792                     }
0793                     call.args.push_back(arg);
0794                     call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
0795                 }
0796                 if (bad_arg) {
0797                     continue; // Maybe it was meant for another overload (issue #688)
0798                 }
0799 
0800                 // Keep track of how many position args we copied out in case we need to come back
0801                 // to copy the rest into a py::args argument.
0802                 size_t positional_args_copied = args_copied;
0803 
0804                 // We'll need to copy this if we steal some kwargs for defaults
0805                 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
0806 
0807                 // 1.5. Fill in any missing pos_only args from defaults if they exist
0808                 if (args_copied < func.nargs_pos_only) {
0809                     for (; args_copied < func.nargs_pos_only; ++args_copied) {
0810                         const auto &arg_rec = func.args[args_copied];
0811                         handle value;
0812 
0813                         if (arg_rec.value) {
0814                             value = arg_rec.value;
0815                         }
0816                         if (value) {
0817                             call.args.push_back(value);
0818                             call.args_convert.push_back(arg_rec.convert);
0819                         } else {
0820                             break;
0821                         }
0822                     }
0823 
0824                     if (args_copied < func.nargs_pos_only) {
0825                         continue; // Not enough defaults to fill the positional arguments
0826                     }
0827                 }
0828 
0829                 // 2. Check kwargs and, failing that, defaults that may help complete the list
0830                 if (args_copied < num_args) {
0831                     bool copied_kwargs = false;
0832 
0833                     for (; args_copied < num_args; ++args_copied) {
0834                         const auto &arg_rec = func.args[args_copied];
0835 
0836                         handle value;
0837                         if (kwargs_in && arg_rec.name) {
0838                             value = dict_getitemstring(kwargs.ptr(), arg_rec.name);
0839                         }
0840 
0841                         if (value) {
0842                             // Consume a kwargs value
0843                             if (!copied_kwargs) {
0844                                 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
0845                                 copied_kwargs = true;
0846                             }
0847                             if (PyDict_DelItemString(kwargs.ptr(), arg_rec.name) == -1) {
0848                                 throw error_already_set();
0849                             }
0850                         } else if (arg_rec.value) {
0851                             value = arg_rec.value;
0852                         }
0853 
0854                         if (!arg_rec.none && value.is_none()) {
0855                             break;
0856                         }
0857 
0858                         if (value) {
0859                             // If we're at the py::args index then first insert a stub for it to be
0860                             // replaced later
0861                             if (func.has_args && call.args.size() == func.nargs_pos) {
0862                                 call.args.push_back(none());
0863                             }
0864 
0865                             call.args.push_back(value);
0866                             call.args_convert.push_back(arg_rec.convert);
0867                         } else {
0868                             break;
0869                         }
0870                     }
0871 
0872                     if (args_copied < num_args) {
0873                         continue; // Not enough arguments, defaults, or kwargs to fill the
0874                                   // positional arguments
0875                     }
0876                 }
0877 
0878                 // 3. Check everything was consumed (unless we have a kwargs arg)
0879                 if (kwargs && !kwargs.empty() && !func.has_kwargs) {
0880                     continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
0881                 }
0882 
0883                 // 4a. If we have a py::args argument, create a new tuple with leftovers
0884                 if (func.has_args) {
0885                     tuple extra_args;
0886                     if (args_to_copy == 0) {
0887                         // We didn't copy out any position arguments from the args_in tuple, so we
0888                         // can reuse it directly without copying:
0889                         extra_args = reinterpret_borrow<tuple>(args_in);
0890                     } else if (positional_args_copied >= n_args_in) {
0891                         extra_args = tuple(0);
0892                     } else {
0893                         size_t args_size = n_args_in - positional_args_copied;
0894                         extra_args = tuple(args_size);
0895                         for (size_t i = 0; i < args_size; ++i) {
0896                             extra_args[i] = PyTuple_GET_ITEM(args_in, positional_args_copied + i);
0897                         }
0898                     }
0899                     if (call.args.size() <= func.nargs_pos) {
0900                         call.args.push_back(extra_args);
0901                     } else {
0902                         call.args[func.nargs_pos] = extra_args;
0903                     }
0904                     call.args_convert.push_back(false);
0905                     call.args_ref = std::move(extra_args);
0906                 }
0907 
0908                 // 4b. If we have a py::kwargs, pass on any remaining kwargs
0909                 if (func.has_kwargs) {
0910                     if (!kwargs.ptr()) {
0911                         kwargs = dict(); // If we didn't get one, send an empty one
0912                     }
0913                     call.args.push_back(kwargs);
0914                     call.args_convert.push_back(false);
0915                     call.kwargs_ref = std::move(kwargs);
0916                 }
0917 
0918 // 5. Put everything in a vector.  Not technically step 5, we've been building it
0919 // in `call.args` all along.
0920 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
0921                 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) {
0922                     pybind11_fail("Internal error: function call dispatcher inserted wrong number "
0923                                   "of arguments!");
0924                 }
0925 #endif
0926 
0927                 std::vector<bool> second_pass_convert;
0928                 if (overloaded) {
0929                     // We're in the first no-convert pass, so swap out the conversion flags for a
0930                     // set of all-false flags.  If the call fails, we'll swap the flags back in for
0931                     // the conversion-allowed call below.
0932                     second_pass_convert.resize(func.nargs, false);
0933                     call.args_convert.swap(second_pass_convert);
0934                 }
0935 
0936                 // 6. Call the function.
0937                 try {
0938                     loader_life_support guard{};
0939                     result = func.impl(call);
0940                 } catch (reference_cast_error &) {
0941                     result = PYBIND11_TRY_NEXT_OVERLOAD;
0942                 }
0943 
0944                 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
0945                     break;
0946                 }
0947 
0948                 if (overloaded) {
0949                     // The (overloaded) call failed; if the call has at least one argument that
0950                     // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
0951                     // then add this call to the list of second pass overloads to try.
0952                     for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
0953                         if (second_pass_convert[i]) {
0954                             // Found one: swap the converting flags back in and store the call for
0955                             // the second pass.
0956                             call.args_convert.swap(second_pass_convert);
0957                             second_pass.push_back(std::move(call));
0958                             break;
0959                         }
0960                     }
0961                 }
0962             }
0963 
0964             if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
0965                 // The no-conversion pass finished without success, try again with conversion
0966                 // allowed
0967                 for (auto &call : second_pass) {
0968                     try {
0969                         loader_life_support guard{};
0970                         result = call.func.impl(call);
0971                     } catch (reference_cast_error &) {
0972                         result = PYBIND11_TRY_NEXT_OVERLOAD;
0973                     }
0974 
0975                     if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
0976                         // The error reporting logic below expects 'it' to be valid, as it would be
0977                         // if we'd encountered this failure in the first-pass loop.
0978                         if (!result) {
0979                             it = &call.func;
0980                         }
0981                         break;
0982                     }
0983                 }
0984             }
0985         } catch (error_already_set &e) {
0986             e.restore();
0987             return nullptr;
0988 #ifdef __GLIBCXX__
0989         } catch (abi::__forced_unwind &) {
0990             throw;
0991 #endif
0992         } catch (...) {
0993             /* When an exception is caught, give each registered exception
0994                translator a chance to translate it to a Python exception. First
0995                all module-local translators will be tried in reverse order of
0996                registration. If none of the module-locale translators handle
0997                the exception (or there are no module-locale translators) then
0998                the global translators will be tried, also in reverse order of
0999                registration.
1000 
1001                A translator may choose to do one of the following:
1002 
1003                 - catch the exception and call PyErr_SetString or PyErr_SetObject
1004                   to set a standard (or custom) Python exception, or
1005                 - do nothing and let the exception fall through to the next translator, or
1006                 - delegate translation to the next translator by throwing a new type of exception.
1007              */
1008 
1009             auto &local_exception_translators
1010                 = get_local_internals().registered_exception_translators;
1011             if (detail::apply_exception_translators(local_exception_translators)) {
1012                 return nullptr;
1013             }
1014             auto &exception_translators = get_internals().registered_exception_translators;
1015             if (detail::apply_exception_translators(exception_translators)) {
1016                 return nullptr;
1017             }
1018 
1019             PyErr_SetString(PyExc_SystemError,
1020                             "Exception escaped from default exception translator!");
1021             return nullptr;
1022         }
1023 
1024         auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
1025             if (msg.find("std::") != std::string::npos) {
1026                 msg += "\n\n"
1027                        "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1028                        "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1029                        "conversions are optional and require extra headers to be included\n"
1030                        "when compiling your pybind11 module.";
1031             }
1032         };
1033 
1034         if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
1035             if (overloads->is_operator) {
1036                 return handle(Py_NotImplemented).inc_ref().ptr();
1037             }
1038 
1039             std::string msg = std::string(overloads->name) + "(): incompatible "
1040                               + std::string(overloads->is_constructor ? "constructor" : "function")
1041                               + " arguments. The following argument types are supported:\n";
1042 
1043             int ctr = 0;
1044             for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
1045                 msg += "    " + std::to_string(++ctr) + ". ";
1046 
1047                 bool wrote_sig = false;
1048                 if (overloads->is_constructor) {
1049                     // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as
1050                     // `Object(arg0, ...)`
1051                     std::string sig = it2->signature;
1052                     size_t start = sig.find('(') + 7; // skip "(self: "
1053                     if (start < sig.size()) {
1054                         // End at the , for the next argument
1055                         size_t end = sig.find(", "), next = end + 2;
1056                         size_t ret = sig.rfind(" -> ");
1057                         // Or the ), if there is no comma:
1058                         if (end >= sig.size()) {
1059                             next = end = sig.find(')');
1060                         }
1061                         if (start < end && next < sig.size()) {
1062                             msg.append(sig, start, end - start);
1063                             msg += '(';
1064                             msg.append(sig, next, ret - next);
1065                             wrote_sig = true;
1066                         }
1067                     }
1068                 }
1069                 if (!wrote_sig) {
1070                     msg += it2->signature;
1071                 }
1072 
1073                 msg += '\n';
1074             }
1075             msg += "\nInvoked with: ";
1076             auto args_ = reinterpret_borrow<tuple>(args_in);
1077             bool some_args = false;
1078             for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
1079                 if (!some_args) {
1080                     some_args = true;
1081                 } else {
1082                     msg += ", ";
1083                 }
1084                 try {
1085                     msg += pybind11::repr(args_[ti]);
1086                 } catch (const error_already_set &) {
1087                     msg += "<repr raised Error>";
1088                 }
1089             }
1090             if (kwargs_in) {
1091                 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
1092                 if (!kwargs.empty()) {
1093                     if (some_args) {
1094                         msg += "; ";
1095                     }
1096                     msg += "kwargs: ";
1097                     bool first = true;
1098                     for (auto kwarg : kwargs) {
1099                         if (first) {
1100                             first = false;
1101                         } else {
1102                             msg += ", ";
1103                         }
1104                         msg += pybind11::str("{}=").format(kwarg.first);
1105                         try {
1106                             msg += pybind11::repr(kwarg.second);
1107                         } catch (const error_already_set &) {
1108                             msg += "<repr raised Error>";
1109                         }
1110                     }
1111                 }
1112             }
1113 
1114             append_note_if_missing_header_is_suspected(msg);
1115             // Attach additional error info to the exception if supported
1116             if (PyErr_Occurred()) {
1117                 // #HelpAppreciated: unit test coverage for this branch.
1118                 raise_from(PyExc_TypeError, msg.c_str());
1119                 return nullptr;
1120             }
1121             PyErr_SetString(PyExc_TypeError, msg.c_str());
1122             return nullptr;
1123         }
1124         if (!result) {
1125             std::string msg = "Unable to convert function return value to a "
1126                               "Python type! The signature was\n\t";
1127             msg += it->signature;
1128             append_note_if_missing_header_is_suspected(msg);
1129             // Attach additional error info to the exception if supported
1130             if (PyErr_Occurred()) {
1131                 raise_from(PyExc_TypeError, msg.c_str());
1132                 return nullptr;
1133             }
1134             PyErr_SetString(PyExc_TypeError, msg.c_str());
1135             return nullptr;
1136         }
1137         if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
1138             auto *pi = reinterpret_cast<instance *>(parent.ptr());
1139             self_value_and_holder.type->init_instance(pi, nullptr);
1140         }
1141         return result.ptr();
1142     }
1143 };
1144 
1145 /// Wrapper for Python extension modules
1146 class module_ : public object {
1147 public:
1148     PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)
1149 
1150     /// Create a new top-level Python module with the given name and docstring
1151     PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead")
1152     explicit module_(const char *name, const char *doc = nullptr) {
1153         *this = create_extension_module(name, doc, new PyModuleDef());
1154     }
1155 
1156     /** \rst
1157         Create Python binding for a new function within the module scope. ``Func``
1158         can be a plain C++ function, a function pointer, or a lambda function. For
1159         details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
1160     \endrst */
1161     template <typename Func, typename... Extra>
1162     module_ &def(const char *name_, Func &&f, const Extra &...extra) {
1163         cpp_function func(std::forward<Func>(f),
1164                           name(name_),
1165                           scope(*this),
1166                           sibling(getattr(*this, name_, none())),
1167                           extra...);
1168         // NB: allow overwriting here because cpp_function sets up a chain with the intention of
1169         // overwriting (and has already checked internally that it isn't overwriting
1170         // non-functions).
1171         add_object(name_, func, true /* overwrite */);
1172         return *this;
1173     }
1174 
1175     /** \rst
1176         Create and return a new Python submodule with the given name and docstring.
1177         This also works recursively, i.e.
1178 
1179         .. code-block:: cpp
1180 
1181             py::module_ m("example", "pybind11 example plugin");
1182             py::module_ m2 = m.def_submodule("sub", "A submodule of 'example'");
1183             py::module_ m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
1184     \endrst */
1185     module_ def_submodule(const char *name, const char *doc = nullptr) {
1186         const char *this_name = PyModule_GetName(m_ptr);
1187         if (this_name == nullptr) {
1188             throw error_already_set();
1189         }
1190         std::string full_name = std::string(this_name) + '.' + name;
1191         handle submodule = PyImport_AddModule(full_name.c_str());
1192         if (!submodule) {
1193             throw error_already_set();
1194         }
1195         auto result = reinterpret_borrow<module_>(submodule);
1196         if (doc && options::show_user_defined_docstrings()) {
1197             result.attr("__doc__") = pybind11::str(doc);
1198         }
1199         attr(name) = result;
1200         return result;
1201     }
1202 
1203     /// Import and return a module or throws `error_already_set`.
1204     static module_ import(const char *name) {
1205         PyObject *obj = PyImport_ImportModule(name);
1206         if (!obj) {
1207             throw error_already_set();
1208         }
1209         return reinterpret_steal<module_>(obj);
1210     }
1211 
1212     /// Reload the module or throws `error_already_set`.
1213     void reload() {
1214         PyObject *obj = PyImport_ReloadModule(ptr());
1215         if (!obj) {
1216             throw error_already_set();
1217         }
1218         *this = reinterpret_steal<module_>(obj);
1219     }
1220 
1221     /** \rst
1222         Adds an object to the module using the given name.  Throws if an object with the given name
1223         already exists.
1224 
1225         ``overwrite`` should almost always be false: attempting to overwrite objects that pybind11
1226         has established will, in most cases, break things.
1227     \endrst */
1228     PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
1229         if (!overwrite && hasattr(*this, name)) {
1230             pybind11_fail(
1231                 "Error during initialization: multiple incompatible definitions with name \""
1232                 + std::string(name) + "\"");
1233         }
1234 
1235         PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
1236     }
1237 
1238     using module_def = PyModuleDef; // TODO: Can this be removed (it was needed only for Python 2)?
1239 
1240     /** \rst
1241         Create a new top-level module that can be used as the main module of a C extension.
1242 
1243         ``def`` should point to a statically allocated module_def.
1244     \endrst */
1245     static module_ create_extension_module(const char *name, const char *doc, module_def *def) {
1246         // module_def is PyModuleDef
1247         // Placement new (not an allocation).
1248         def = new (def)
1249             PyModuleDef{/* m_base */ PyModuleDef_HEAD_INIT,
1250                         /* m_name */ name,
1251                         /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr,
1252                         /* m_size */ -1,
1253                         /* m_methods */ nullptr,
1254                         /* m_slots */ nullptr,
1255                         /* m_traverse */ nullptr,
1256                         /* m_clear */ nullptr,
1257                         /* m_free */ nullptr};
1258         auto *m = PyModule_Create(def);
1259         if (m == nullptr) {
1260             if (PyErr_Occurred()) {
1261                 throw error_already_set();
1262             }
1263             pybind11_fail("Internal error in module_::create_extension_module()");
1264         }
1265         // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when
1266         //       returned from PyInit_...
1267         //       For Python 2, reinterpret_borrow was correct.
1268         return reinterpret_borrow<module_>(m);
1269     }
1270 };
1271 
1272 // When inside a namespace (or anywhere as long as it's not the first item on a line),
1273 // C++20 allows "module" to be used. This is provided for backward compatibility, and for
1274 // simplicity, if someone wants to use py::module for example, that is perfectly safe.
1275 using module = module_;
1276 
1277 /// \ingroup python_builtins
1278 /// Return a dictionary representing the global variables in the current execution frame,
1279 /// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
1280 inline dict globals() {
1281     PyObject *p = PyEval_GetGlobals();
1282     return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
1283 }
1284 
1285 template <typename... Args, typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>>
1286 PYBIND11_DEPRECATED("make_simple_namespace should be replaced with "
1287                     "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
1288 object make_simple_namespace(Args &&...args_) {
1289     return module_::import("types").attr("SimpleNamespace")(std::forward<Args>(args_)...);
1290 }
1291 
1292 PYBIND11_NAMESPACE_BEGIN(detail)
1293 /// Generic support for creating new Python heap types
1294 class generic_type : public object {
1295 public:
1296     PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
1297 protected:
1298     void initialize(const type_record &rec) {
1299         if (rec.scope && hasattr(rec.scope, "__dict__")
1300             && rec.scope.attr("__dict__").contains(rec.name)) {
1301             pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name)
1302                           + "\": an object with that name is already defined");
1303         }
1304 
1305         if ((rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
1306             != nullptr) {
1307             pybind11_fail("generic_type: type \"" + std::string(rec.name)
1308                           + "\" is already registered!");
1309         }
1310 
1311         m_ptr = make_new_python_type(rec);
1312 
1313         /* Register supplemental type information in C++ dict */
1314         auto *tinfo = new detail::type_info();
1315         tinfo->type = (PyTypeObject *) m_ptr;
1316         tinfo->cpptype = rec.type;
1317         tinfo->type_size = rec.type_size;
1318         tinfo->type_align = rec.type_align;
1319         tinfo->operator_new = rec.operator_new;
1320         tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
1321         tinfo->init_instance = rec.init_instance;
1322         tinfo->dealloc = rec.dealloc;
1323         tinfo->simple_type = true;
1324         tinfo->simple_ancestors = true;
1325         tinfo->default_holder = rec.default_holder;
1326         tinfo->module_local = rec.module_local;
1327 
1328         auto &internals = get_internals();
1329         auto tindex = std::type_index(*rec.type);
1330         tinfo->direct_conversions = &internals.direct_conversions[tindex];
1331         if (rec.module_local) {
1332             get_local_internals().registered_types_cpp[tindex] = tinfo;
1333         } else {
1334             internals.registered_types_cpp[tindex] = tinfo;
1335         }
1336         internals.registered_types_py[(PyTypeObject *) m_ptr] = {tinfo};
1337 
1338         if (rec.bases.size() > 1 || rec.multiple_inheritance) {
1339             mark_parents_nonsimple(tinfo->type);
1340             tinfo->simple_ancestors = false;
1341         } else if (rec.bases.size() == 1) {
1342             auto *parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
1343             assert(parent_tinfo != nullptr);
1344             bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1345             tinfo->simple_ancestors = parent_simple_ancestors;
1346             // The parent can no longer be a simple type if it has MI and has a child
1347             parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1348         }
1349 
1350         if (rec.module_local) {
1351             // Stash the local typeinfo and loader so that external modules can access it.
1352             tinfo->module_local_load = &type_caster_generic::local_load;
1353             setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
1354         }
1355     }
1356 
1357     /// Helper function which tags all parents of a type using mult. inheritance
1358     void mark_parents_nonsimple(PyTypeObject *value) {
1359         auto t = reinterpret_borrow<tuple>(value->tp_bases);
1360         for (handle h : t) {
1361             auto *tinfo2 = get_type_info((PyTypeObject *) h.ptr());
1362             if (tinfo2) {
1363                 tinfo2->simple_type = false;
1364             }
1365             mark_parents_nonsimple((PyTypeObject *) h.ptr());
1366         }
1367     }
1368 
1369     void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *),
1370                               void *get_buffer_data) {
1371         auto *type = (PyHeapTypeObject *) m_ptr;
1372         auto *tinfo = detail::get_type_info(&type->ht_type);
1373 
1374         if (!type->ht_type.tp_as_buffer) {
1375             pybind11_fail("To be able to register buffer protocol support for the type '"
1376                           + get_fully_qualified_tp_name(tinfo->type)
1377                           + "' the associated class<>(..) invocation must "
1378                             "include the pybind11::buffer_protocol() annotation!");
1379         }
1380 
1381         tinfo->get_buffer = get_buffer;
1382         tinfo->get_buffer_data = get_buffer_data;
1383     }
1384 
1385     // rec_func must be set for either fget or fset.
1386     void def_property_static_impl(const char *name,
1387                                   handle fget,
1388                                   handle fset,
1389                                   detail::function_record *rec_func) {
1390         const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);
1391         const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)
1392                              && pybind11::options::show_user_defined_docstrings();
1393         auto property = handle(
1394             (PyObject *) (is_static ? get_internals().static_property_type : &PyProperty_Type));
1395         attr(name) = property(fget.ptr() ? fget : none(),
1396                               fset.ptr() ? fset : none(),
1397                               /*deleter*/ none(),
1398                               pybind11::str(has_doc ? rec_func->doc : ""));
1399     }
1400 };
1401 
1402 /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
1403 template <typename T,
1404           typename = void_t<decltype(static_cast<void *(*) (size_t)>(T::operator new))>>
1405 void set_operator_new(type_record *r) {
1406     r->operator_new = &T::operator new;
1407 }
1408 
1409 template <typename>
1410 void set_operator_new(...) {}
1411 
1412 template <typename T, typename SFINAE = void>
1413 struct has_operator_delete : std::false_type {};
1414 template <typename T>
1415 struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
1416     : std::true_type {};
1417 template <typename T, typename SFINAE = void>
1418 struct has_operator_delete_size : std::false_type {};
1419 template <typename T>
1420 struct has_operator_delete_size<
1421     T,
1422     void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type {
1423 };
1424 /// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
1425 template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
1426 void call_operator_delete(T *p, size_t, size_t) {
1427     T::operator delete(p);
1428 }
1429 template <typename T,
1430           enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int>
1431           = 0>
1432 void call_operator_delete(T *p, size_t s, size_t) {
1433     T::operator delete(p, s);
1434 }
1435 
1436 inline void call_operator_delete(void *p, size_t s, size_t a) {
1437     (void) s;
1438     (void) a;
1439 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1440     if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1441 #    ifdef __cpp_sized_deallocation
1442         ::operator delete(p, s, std::align_val_t(a));
1443 #    else
1444         ::operator delete(p, std::align_val_t(a));
1445 #    endif
1446         return;
1447     }
1448 #endif
1449 #ifdef __cpp_sized_deallocation
1450     ::operator delete(p, s);
1451 #else
1452     ::operator delete(p);
1453 #endif
1454 }
1455 
1456 inline void add_class_method(object &cls, const char *name_, const cpp_function &cf) {
1457     cls.attr(cf.name()) = cf;
1458     if (std::strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) {
1459         cls.attr("__hash__") = none();
1460     }
1461 }
1462 
1463 PYBIND11_NAMESPACE_END(detail)
1464 
1465 /// Given a pointer to a member function, cast it to its `Derived` version.
1466 /// Forward everything else unchanged.
1467 template <typename /*Derived*/, typename F>
1468 auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
1469     return std::forward<F>(f);
1470 }
1471 
1472 template <typename Derived, typename Return, typename Class, typename... Args>
1473 auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
1474     static_assert(
1475         detail::is_accessible_base_of<Class, Derived>::value,
1476         "Cannot bind an inaccessible base class method; use a lambda definition instead");
1477     return pmf;
1478 }
1479 
1480 template <typename Derived, typename Return, typename Class, typename... Args>
1481 auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
1482     static_assert(
1483         detail::is_accessible_base_of<Class, Derived>::value,
1484         "Cannot bind an inaccessible base class method; use a lambda definition instead");
1485     return pmf;
1486 }
1487 
1488 template <typename type_, typename... options>
1489 class class_ : public detail::generic_type {
1490     template <typename T>
1491     using is_holder = detail::is_holder_type<type_, T>;
1492     template <typename T>
1493     using is_subtype = detail::is_strict_base_of<type_, T>;
1494     template <typename T>
1495     using is_base = detail::is_strict_base_of<T, type_>;
1496     // struct instead of using here to help MSVC:
1497     template <typename T>
1498     struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
1499 
1500 public:
1501     using type = type_;
1502     using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
1503     constexpr static bool has_alias = !std::is_void<type_alias>::value;
1504     using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
1505 
1506     static_assert(detail::all_of<is_valid_class_option<options>...>::value,
1507                   "Unknown/invalid class_ template parameters provided");
1508 
1509     static_assert(!has_alias || std::is_polymorphic<type>::value,
1510                   "Cannot use an alias class with a non-polymorphic type");
1511 
1512     PYBIND11_OBJECT(class_, generic_type, PyType_Check)
1513 
1514     template <typename... Extra>
1515     class_(handle scope, const char *name, const Extra &...extra) {
1516         using namespace detail;
1517 
1518         // MI can only be specified via class_ template options, not constructor parameters
1519         static_assert(
1520             none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
1521                 (constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
1522                  constexpr_sum(is_base<options>::value...) == 0 &&   // no template option bases
1523                  // no multiple_inheritance attr
1524                  none_of<std::is_same<multiple_inheritance, Extra>...>::value),
1525             "Error: multiple inheritance bases must be specified via class_ template options");
1526 
1527         type_record record;
1528         record.scope = scope;
1529         record.name = name;
1530         record.type = &typeid(type);
1531         record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
1532         record.type_align = alignof(conditional_t<has_alias, type_alias, type> &);
1533         record.holder_size = sizeof(holder_type);
1534         record.init_instance = init_instance;
1535         record.dealloc = dealloc;
1536         record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
1537 
1538         set_operator_new<type>(&record);
1539 
1540         /* Register base classes specified via template arguments to class_, if any */
1541         PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
1542 
1543         /* Process optional arguments, if any */
1544         process_attributes<Extra...>::init(extra..., &record);
1545 
1546         generic_type::initialize(record);
1547 
1548         if (has_alias) {
1549             auto &instances = record.module_local ? get_local_internals().registered_types_cpp
1550                                                   : get_internals().registered_types_cpp;
1551             instances[std::type_index(typeid(type_alias))]
1552                 = instances[std::type_index(typeid(type))];
1553         }
1554     }
1555 
1556     template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
1557     static void add_base(detail::type_record &rec) {
1558         rec.add_base(typeid(Base), [](void *src) -> void * {
1559             return static_cast<Base *>(reinterpret_cast<type *>(src));
1560         });
1561     }
1562 
1563     template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
1564     static void add_base(detail::type_record &) {}
1565 
1566     template <typename Func, typename... Extra>
1567     class_ &def(const char *name_, Func &&f, const Extra &...extra) {
1568         cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
1569                         name(name_),
1570                         is_method(*this),
1571                         sibling(getattr(*this, name_, none())),
1572                         extra...);
1573         add_class_method(*this, name_, cf);
1574         return *this;
1575     }
1576 
1577     template <typename Func, typename... Extra>
1578     class_ &def_static(const char *name_, Func &&f, const Extra &...extra) {
1579         static_assert(!std::is_member_function_pointer<Func>::value,
1580                       "def_static(...) called with a non-static member function pointer");
1581         cpp_function cf(std::forward<Func>(f),
1582                         name(name_),
1583                         scope(*this),
1584                         sibling(getattr(*this, name_, none())),
1585                         extra...);
1586         auto cf_name = cf.name();
1587         attr(std::move(cf_name)) = staticmethod(std::move(cf));
1588         return *this;
1589     }
1590 
1591     template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1592     class_ &def(const T &op, const Extra &...extra) {
1593         op.execute(*this, extra...);
1594         return *this;
1595     }
1596 
1597     template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1598     class_ &def_cast(const T &op, const Extra &...extra) {
1599         op.execute_cast(*this, extra...);
1600         return *this;
1601     }
1602 
1603     template <typename... Args, typename... Extra>
1604     class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra &...extra) {
1605         PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
1606         init.execute(*this, extra...);
1607         return *this;
1608     }
1609 
1610     template <typename... Args, typename... Extra>
1611     class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra &...extra) {
1612         PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
1613         init.execute(*this, extra...);
1614         return *this;
1615     }
1616 
1617     template <typename... Args, typename... Extra>
1618     class_ &def(detail::initimpl::factory<Args...> &&init, const Extra &...extra) {
1619         std::move(init).execute(*this, extra...);
1620         return *this;
1621     }
1622 
1623     template <typename... Args, typename... Extra>
1624     class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
1625         std::move(pf).execute(*this, extra...);
1626         return *this;
1627     }
1628 
1629     template <typename Func>
1630     class_ &def_buffer(Func &&func) {
1631         struct capture {
1632             Func func;
1633         };
1634         auto *ptr = new capture{std::forward<Func>(func)};
1635         install_buffer_funcs(
1636             [](PyObject *obj, void *ptr) -> buffer_info * {
1637                 detail::make_caster<type> caster;
1638                 if (!caster.load(obj, false)) {
1639                     return nullptr;
1640                 }
1641                 return new buffer_info(((capture *) ptr)->func(std::move(caster)));
1642             },
1643             ptr);
1644         weakref(m_ptr, cpp_function([ptr](handle wr) {
1645                     delete ptr;
1646                     wr.dec_ref();
1647                 }))
1648             .release();
1649         return *this;
1650     }
1651 
1652     template <typename Return, typename Class, typename... Args>
1653     class_ &def_buffer(Return (Class::*func)(Args...)) {
1654         return def_buffer([func](type &obj) { return (obj.*func)(); });
1655     }
1656 
1657     template <typename Return, typename Class, typename... Args>
1658     class_ &def_buffer(Return (Class::*func)(Args...) const) {
1659         return def_buffer([func](const type &obj) { return (obj.*func)(); });
1660     }
1661 
1662     template <typename C, typename D, typename... Extra>
1663     class_ &def_readwrite(const char *name, D C::*pm, const Extra &...extra) {
1664         static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
1665                       "def_readwrite() requires a class member (or base class member)");
1666         cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this)),
1667             fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
1668         def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
1669         return *this;
1670     }
1671 
1672     template <typename C, typename D, typename... Extra>
1673     class_ &def_readonly(const char *name, const D C::*pm, const Extra &...extra) {
1674         static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
1675                       "def_readonly() requires a class member (or base class member)");
1676         cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this));
1677         def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
1678         return *this;
1679     }
1680 
1681     template <typename D, typename... Extra>
1682     class_ &def_readwrite_static(const char *name, D *pm, const Extra &...extra) {
1683         cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)),
1684             fset([pm](const object &, const D &value) { *pm = value; }, scope(*this));
1685         def_property_static(name, fget, fset, return_value_policy::reference, extra...);
1686         return *this;
1687     }
1688 
1689     template <typename D, typename... Extra>
1690     class_ &def_readonly_static(const char *name, const D *pm, const Extra &...extra) {
1691         cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this));
1692         def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
1693         return *this;
1694     }
1695 
1696     /// Uses return_value_policy::reference_internal by default
1697     template <typename Getter, typename... Extra>
1698     class_ &def_property_readonly(const char *name, const Getter &fget, const Extra &...extra) {
1699         return def_property_readonly(name,
1700                                      cpp_function(method_adaptor<type>(fget)),
1701                                      return_value_policy::reference_internal,
1702                                      extra...);
1703     }
1704 
1705     /// Uses cpp_function's return_value_policy by default
1706     template <typename... Extra>
1707     class_ &
1708     def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra) {
1709         return def_property(name, fget, nullptr, extra...);
1710     }
1711 
1712     /// Uses return_value_policy::reference by default
1713     template <typename Getter, typename... Extra>
1714     class_ &
1715     def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra) {
1716         return def_property_readonly_static(
1717             name, cpp_function(fget), return_value_policy::reference, extra...);
1718     }
1719 
1720     /// Uses cpp_function's return_value_policy by default
1721     template <typename... Extra>
1722     class_ &def_property_readonly_static(const char *name,
1723                                          const cpp_function &fget,
1724                                          const Extra &...extra) {
1725         return def_property_static(name, fget, nullptr, extra...);
1726     }
1727 
1728     /// Uses return_value_policy::reference_internal by default
1729     template <typename Getter, typename Setter, typename... Extra>
1730     class_ &
1731     def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) {
1732         return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
1733     }
1734     template <typename Getter, typename... Extra>
1735     class_ &def_property(const char *name,
1736                          const Getter &fget,
1737                          const cpp_function &fset,
1738                          const Extra &...extra) {
1739         return def_property(name,
1740                             cpp_function(method_adaptor<type>(fget)),
1741                             fset,
1742                             return_value_policy::reference_internal,
1743                             extra...);
1744     }
1745 
1746     /// Uses cpp_function's return_value_policy by default
1747     template <typename... Extra>
1748     class_ &def_property(const char *name,
1749                          const cpp_function &fget,
1750                          const cpp_function &fset,
1751                          const Extra &...extra) {
1752         return def_property_static(name, fget, fset, is_method(*this), extra...);
1753     }
1754 
1755     /// Uses return_value_policy::reference by default
1756     template <typename Getter, typename... Extra>
1757     class_ &def_property_static(const char *name,
1758                                 const Getter &fget,
1759                                 const cpp_function &fset,
1760                                 const Extra &...extra) {
1761         return def_property_static(
1762             name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1763     }
1764 
1765     /// Uses cpp_function's return_value_policy by default
1766     template <typename... Extra>
1767     class_ &def_property_static(const char *name,
1768                                 const cpp_function &fget,
1769                                 const cpp_function &fset,
1770                                 const Extra &...extra) {
1771         static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
1772                       "Argument annotations are not allowed for properties");
1773         auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1774         auto *rec_active = rec_fget;
1775         if (rec_fget) {
1776             char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific
1777                                                documentation string */
1778             detail::process_attributes<Extra...>::init(extra..., rec_fget);
1779             if (rec_fget->doc && rec_fget->doc != doc_prev) {
1780                 std::free(doc_prev);
1781                 rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc);
1782             }
1783         }
1784         if (rec_fset) {
1785             char *doc_prev = rec_fset->doc;
1786             detail::process_attributes<Extra...>::init(extra..., rec_fset);
1787             if (rec_fset->doc && rec_fset->doc != doc_prev) {
1788                 std::free(doc_prev);
1789                 rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc);
1790             }
1791             if (!rec_active) {
1792                 rec_active = rec_fset;
1793             }
1794         }
1795         def_property_static_impl(name, fget, fset, rec_active);
1796         return *this;
1797     }
1798 
1799 private:
1800     /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1801     template <typename T>
1802     static void init_holder(detail::instance *inst,
1803                             detail::value_and_holder &v_h,
1804                             const holder_type * /* unused */,
1805                             const std::enable_shared_from_this<T> * /* dummy */) {
1806 
1807         auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1808             detail::try_get_shared_from_this(v_h.value_ptr<type>()));
1809         if (sh) {
1810             new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
1811             v_h.set_holder_constructed();
1812         }
1813 
1814         if (!v_h.holder_constructed() && inst->owned) {
1815             new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1816             v_h.set_holder_constructed();
1817         }
1818     }
1819 
1820     static void init_holder_from_existing(const detail::value_and_holder &v_h,
1821                                           const holder_type *holder_ptr,
1822                                           std::true_type /*is_copy_constructible*/) {
1823         new (std::addressof(v_h.holder<holder_type>()))
1824             holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1825     }
1826 
1827     static void init_holder_from_existing(const detail::value_and_holder &v_h,
1828                                           const holder_type *holder_ptr,
1829                                           std::false_type /*is_copy_constructible*/) {
1830         new (std::addressof(v_h.holder<holder_type>()))
1831             holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1832     }
1833 
1834     /// Initialize holder object, variant 2: try to construct from existing holder object, if
1835     /// possible
1836     static void init_holder(detail::instance *inst,
1837                             detail::value_and_holder &v_h,
1838                             const holder_type *holder_ptr,
1839                             const void * /* dummy -- not enable_shared_from_this<T>) */) {
1840         if (holder_ptr) {
1841             init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1842             v_h.set_holder_constructed();
1843         } else if (detail::always_construct_holder<holder_type>::value || inst->owned) {
1844             new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1845             v_h.set_holder_constructed();
1846         }
1847     }
1848 
1849     /// Performs instance initialization including constructing a holder and registering the known
1850     /// instance.  Should be called as soon as the `type` value_ptr is set for an instance.  Takes
1851     /// an optional pointer to an existing holder to use; if not specified and the instance is
1852     /// `.owned`, a new holder will be constructed to manage the value pointer.
1853     static void init_instance(detail::instance *inst, const void *holder_ptr) {
1854         auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
1855         if (!v_h.instance_registered()) {
1856             register_instance(inst, v_h.value_ptr(), v_h.type);
1857             v_h.set_instance_registered();
1858         }
1859         init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
1860     }
1861 
1862     /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
1863     static void dealloc(detail::value_and_holder &v_h) {
1864         // We could be deallocating because we are cleaning up after a Python exception.
1865         // If so, the Python error indicator will be set. We need to clear that before
1866         // running the destructor, in case the destructor code calls more Python.
1867         // If we don't, the Python API will exit with an exception, and pybind11 will
1868         // throw error_already_set from the C++ destructor which is forbidden and triggers
1869         // std::terminate().
1870         error_scope scope;
1871         if (v_h.holder_constructed()) {
1872             v_h.holder<holder_type>().~holder_type();
1873             v_h.set_holder_constructed(false);
1874         } else {
1875             detail::call_operator_delete(
1876                 v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align);
1877         }
1878         v_h.value_ptr() = nullptr;
1879     }
1880 
1881     static detail::function_record *get_function_record(handle h) {
1882         h = detail::get_function(h);
1883         if (!h) {
1884             return nullptr;
1885         }
1886 
1887         handle func_self = PyCFunction_GET_SELF(h.ptr());
1888         if (!func_self) {
1889             throw error_already_set();
1890         }
1891         if (!isinstance<capsule>(func_self)) {
1892             return nullptr;
1893         }
1894         auto cap = reinterpret_borrow<capsule>(func_self);
1895         if (!detail::is_function_record_capsule(cap)) {
1896             return nullptr;
1897         }
1898         return cap.get_pointer<detail::function_record>();
1899     }
1900 };
1901 
1902 /// Binds an existing constructor taking arguments Args...
1903 template <typename... Args>
1904 detail::initimpl::constructor<Args...> init() {
1905     return {};
1906 }
1907 /// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
1908 /// when not inheriting on the Python side).
1909 template <typename... Args>
1910 detail::initimpl::alias_constructor<Args...> init_alias() {
1911     return {};
1912 }
1913 
1914 /// Binds a factory function as a constructor
1915 template <typename Func, typename Ret = detail::initimpl::factory<Func>>
1916 Ret init(Func &&f) {
1917     return {std::forward<Func>(f)};
1918 }
1919 
1920 /// Dual-argument factory function: the first function is called when no alias is needed, the
1921 /// second when an alias is needed (i.e. due to python-side inheritance).  Arguments must be
1922 /// identical.
1923 template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1924 Ret init(CFunc &&c, AFunc &&a) {
1925     return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1926 }
1927 
1928 /// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
1929 /// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
1930 template <typename GetState, typename SetState>
1931 detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
1932     return {std::forward<GetState>(g), std::forward<SetState>(s)};
1933 }
1934 
1935 PYBIND11_NAMESPACE_BEGIN(detail)
1936 
1937 inline str enum_name(handle arg) {
1938     dict entries = arg.get_type().attr("__entries");
1939     for (auto kv : entries) {
1940         if (handle(kv.second[int_(0)]).equal(arg)) {
1941             return pybind11::str(kv.first);
1942         }
1943     }
1944     return "???";
1945 }
1946 
1947 struct enum_base {
1948     enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) {}
1949 
1950     PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
1951         m_base.attr("__entries") = dict();
1952         auto property = handle((PyObject *) &PyProperty_Type);
1953         auto static_property = handle((PyObject *) get_internals().static_property_type);
1954 
1955         m_base.attr("__repr__") = cpp_function(
1956             [](const object &arg) -> str {
1957                 handle type = type::handle_of(arg);
1958                 object type_name = type.attr("__name__");
1959                 return pybind11::str("<{}.{}: {}>")
1960                     .format(std::move(type_name), enum_name(arg), int_(arg));
1961             },
1962             name("__repr__"),
1963             is_method(m_base));
1964 
1965         m_base.attr("name") = property(cpp_function(&enum_name, name("name"), is_method(m_base)));
1966 
1967         m_base.attr("__str__") = cpp_function(
1968             [](handle arg) -> str {
1969                 object type_name = type::handle_of(arg).attr("__name__");
1970                 return pybind11::str("{}.{}").format(std::move(type_name), enum_name(arg));
1971             },
1972             name("name"),
1973             is_method(m_base));
1974 
1975         if (options::show_enum_members_docstring()) {
1976             m_base.attr("__doc__") = static_property(
1977                 cpp_function(
1978                     [](handle arg) -> std::string {
1979                         std::string docstring;
1980                         dict entries = arg.attr("__entries");
1981                         if (((PyTypeObject *) arg.ptr())->tp_doc) {
1982                             docstring += std::string(
1983                                 reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);
1984                             docstring += "\n\n";
1985                         }
1986                         docstring += "Members:";
1987                         for (auto kv : entries) {
1988                             auto key = std::string(pybind11::str(kv.first));
1989                             auto comment = kv.second[int_(1)];
1990                             docstring += "\n\n  ";
1991                             docstring += key;
1992                             if (!comment.is_none()) {
1993                                 docstring += " : ";
1994                                 docstring += pybind11::str(comment).cast<std::string>();
1995                             }
1996                         }
1997                         return docstring;
1998                     },
1999                     name("__doc__")),
2000                 none(),
2001                 none(),
2002                 "");
2003         }
2004 
2005         m_base.attr("__members__") = static_property(cpp_function(
2006                                                          [](handle arg) -> dict {
2007                                                              dict entries = arg.attr("__entries"),
2008                                                                   m;
2009                                                              for (auto kv : entries) {
2010                                                                  m[kv.first] = kv.second[int_(0)];
2011                                                              }
2012                                                              return m;
2013                                                          },
2014                                                          name("__members__")),
2015                                                      none(),
2016                                                      none(),
2017                                                      "");
2018 
2019 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)                                        \
2020     m_base.attr(op) = cpp_function(                                                               \
2021         [](const object &a, const object &b) {                                                    \
2022             if (!type::handle_of(a).is(type::handle_of(b)))                                       \
2023                 strict_behavior; /* NOLINT(bugprone-macro-parentheses) */                         \
2024             return expr;                                                                          \
2025         },                                                                                        \
2026         name(op),                                                                                 \
2027         is_method(m_base),                                                                        \
2028         arg("other"))
2029 
2030 #define PYBIND11_ENUM_OP_CONV(op, expr)                                                           \
2031     m_base.attr(op) = cpp_function(                                                               \
2032         [](const object &a_, const object &b_) {                                                  \
2033             int_ a(a_), b(b_);                                                                    \
2034             return expr;                                                                          \
2035         },                                                                                        \
2036         name(op),                                                                                 \
2037         is_method(m_base),                                                                        \
2038         arg("other"))
2039 
2040 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr)                                                       \
2041     m_base.attr(op) = cpp_function(                                                               \
2042         [](const object &a_, const object &b) {                                                   \
2043             int_ a(a_);                                                                           \
2044             return expr;                                                                          \
2045         },                                                                                        \
2046         name(op),                                                                                 \
2047         is_method(m_base),                                                                        \
2048         arg("other"))
2049 
2050         if (is_convertible) {
2051             PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
2052             PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
2053 
2054             if (is_arithmetic) {
2055                 PYBIND11_ENUM_OP_CONV("__lt__", a < b);
2056                 PYBIND11_ENUM_OP_CONV("__gt__", a > b);
2057                 PYBIND11_ENUM_OP_CONV("__le__", a <= b);
2058                 PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
2059                 PYBIND11_ENUM_OP_CONV("__and__", a & b);
2060                 PYBIND11_ENUM_OP_CONV("__rand__", a & b);
2061                 PYBIND11_ENUM_OP_CONV("__or__", a | b);
2062                 PYBIND11_ENUM_OP_CONV("__ror__", a | b);
2063                 PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
2064                 PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
2065                 m_base.attr("__invert__")
2066                     = cpp_function([](const object &arg) { return ~(int_(arg)); },
2067                                    name("__invert__"),
2068                                    is_method(m_base));
2069             }
2070         } else {
2071             PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
2072             PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
2073 
2074             if (is_arithmetic) {
2075 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
2076                 PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
2077                 PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
2078                 PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
2079                 PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
2080 #undef PYBIND11_THROW
2081             }
2082         }
2083 
2084 #undef PYBIND11_ENUM_OP_CONV_LHS
2085 #undef PYBIND11_ENUM_OP_CONV
2086 #undef PYBIND11_ENUM_OP_STRICT
2087 
2088         m_base.attr("__getstate__") = cpp_function(
2089             [](const object &arg) { return int_(arg); }, name("__getstate__"), is_method(m_base));
2090 
2091         m_base.attr("__hash__") = cpp_function(
2092             [](const object &arg) { return int_(arg); }, name("__hash__"), is_method(m_base));
2093     }
2094 
2095     PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc = nullptr) {
2096         dict entries = m_base.attr("__entries");
2097         str name(name_);
2098         if (entries.contains(name)) {
2099             std::string type_name = (std::string) str(m_base.attr("__name__"));
2100             throw value_error(std::move(type_name) + ": element \"" + std::string(name_)
2101                               + "\" already exists!");
2102         }
2103 
2104         entries[name] = pybind11::make_tuple(value, doc);
2105         m_base.attr(std::move(name)) = std::move(value);
2106     }
2107 
2108     PYBIND11_NOINLINE void export_values() {
2109         dict entries = m_base.attr("__entries");
2110         for (auto kv : entries) {
2111             m_parent.attr(kv.first) = kv.second[int_(0)];
2112         }
2113     }
2114 
2115     handle m_base;
2116     handle m_parent;
2117 };
2118 
2119 template <bool is_signed, size_t length>
2120 struct equivalent_integer {};
2121 template <>
2122 struct equivalent_integer<true, 1> {
2123     using type = int8_t;
2124 };
2125 template <>
2126 struct equivalent_integer<false, 1> {
2127     using type = uint8_t;
2128 };
2129 template <>
2130 struct equivalent_integer<true, 2> {
2131     using type = int16_t;
2132 };
2133 template <>
2134 struct equivalent_integer<false, 2> {
2135     using type = uint16_t;
2136 };
2137 template <>
2138 struct equivalent_integer<true, 4> {
2139     using type = int32_t;
2140 };
2141 template <>
2142 struct equivalent_integer<false, 4> {
2143     using type = uint32_t;
2144 };
2145 template <>
2146 struct equivalent_integer<true, 8> {
2147     using type = int64_t;
2148 };
2149 template <>
2150 struct equivalent_integer<false, 8> {
2151     using type = uint64_t;
2152 };
2153 
2154 template <typename IntLike>
2155 using equivalent_integer_t =
2156     typename equivalent_integer<std::is_signed<IntLike>::value, sizeof(IntLike)>::type;
2157 
2158 PYBIND11_NAMESPACE_END(detail)
2159 
2160 /// Binds C++ enumerations and enumeration classes to Python
2161 template <typename Type>
2162 class enum_ : public class_<Type> {
2163 public:
2164     using Base = class_<Type>;
2165     using Base::attr;
2166     using Base::def;
2167     using Base::def_property_readonly;
2168     using Base::def_property_readonly_static;
2169     using Underlying = typename std::underlying_type<Type>::type;
2170     // Scalar is the integer representation of underlying type
2171     using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2172                                                         std::is_same<Underlying, bool>>::value,
2173                                          detail::equivalent_integer_t<Underlying>,
2174                                          Underlying>;
2175 
2176     template <typename... Extra>
2177     enum_(const handle &scope, const char *name, const Extra &...extra)
2178         : class_<Type>(scope, name, extra...), m_base(*this, scope) {
2179         constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
2180         constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
2181         m_base.init(is_arithmetic, is_convertible);
2182 
2183         def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
2184         def_property_readonly("value", [](Type value) { return (Scalar) value; });
2185         def("__int__", [](Type value) { return (Scalar) value; });
2186         def("__index__", [](Type value) { return (Scalar) value; });
2187         attr("__setstate__") = cpp_function(
2188             [](detail::value_and_holder &v_h, Scalar arg) {
2189                 detail::initimpl::setstate<Base>(
2190                     v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type);
2191             },
2192             detail::is_new_style_constructor(),
2193             pybind11::name("__setstate__"),
2194             is_method(*this),
2195             arg("state"));
2196     }
2197 
2198     /// Export enumeration entries into the parent scope
2199     enum_ &export_values() {
2200         m_base.export_values();
2201         return *this;
2202     }
2203 
2204     /// Add an enumeration entry
2205     enum_ &value(char const *name, Type value, const char *doc = nullptr) {
2206         m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
2207         return *this;
2208     }
2209 
2210 private:
2211     detail::enum_base m_base;
2212 };
2213 
2214 PYBIND11_NAMESPACE_BEGIN(detail)
2215 
2216 PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient) {
2217     if (!nurse || !patient) {
2218         pybind11_fail("Could not activate keep_alive!");
2219     }
2220 
2221     if (patient.is_none() || nurse.is_none()) {
2222         return; /* Nothing to keep alive or nothing to be kept alive by */
2223     }
2224 
2225     auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
2226     if (!tinfo.empty()) {
2227         /* It's a pybind-registered type, so we can store the patient in the
2228          * internal list. */
2229         add_patient(nurse.ptr(), patient.ptr());
2230     } else {
2231         /* Fall back to clever approach based on weak references taken from
2232          * Boost.Python. This is not used for pybind-registered types because
2233          * the objects can be destroyed out-of-order in a GC pass. */
2234         cpp_function disable_lifesupport([patient](handle weakref) {
2235             patient.dec_ref();
2236             weakref.dec_ref();
2237         });
2238 
2239         weakref wr(nurse, disable_lifesupport);
2240 
2241         patient.inc_ref(); /* reference patient and leak the weak reference */
2242         (void) wr.release();
2243     }
2244 }
2245 
2246 PYBIND11_NOINLINE void
2247 keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
2248     auto get_arg = [&](size_t n) {
2249         if (n == 0) {
2250             return ret;
2251         }
2252         if (n == 1 && call.init_self) {
2253             return call.init_self;
2254         }
2255         if (n <= call.args.size()) {
2256             return call.args[n - 1];
2257         }
2258         return handle();
2259     };
2260 
2261     keep_alive_impl(get_arg(Nurse), get_arg(Patient));
2262 }
2263 
2264 inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
2265 all_type_info_get_cache(PyTypeObject *type) {
2266     auto res = get_internals()
2267                    .registered_types_py
2268 #ifdef __cpp_lib_unordered_map_try_emplace
2269                    .try_emplace(type);
2270 #else
2271                    .emplace(type, std::vector<detail::type_info *>());
2272 #endif
2273     if (res.second) {
2274         // New cache entry created; set up a weak reference to automatically remove it if the type
2275         // gets destroyed:
2276         weakref((PyObject *) type, cpp_function([type](handle wr) {
2277                     get_internals().registered_types_py.erase(type);
2278 
2279                     // TODO consolidate the erasure code in pybind11_meta_dealloc() in class.h
2280                     auto &cache = get_internals().inactive_override_cache;
2281                     for (auto it = cache.begin(), last = cache.end(); it != last;) {
2282                         if (it->first == reinterpret_cast<PyObject *>(type)) {
2283                             it = cache.erase(it);
2284                         } else {
2285                             ++it;
2286                         }
2287                     }
2288 
2289                     wr.dec_ref();
2290                 }))
2291             .release();
2292     }
2293 
2294     return res;
2295 }
2296 
2297 /* There are a large number of apparently unused template arguments because
2298  * each combination requires a separate py::class_ registration.
2299  */
2300 template <typename Access,
2301           return_value_policy Policy,
2302           typename Iterator,
2303           typename Sentinel,
2304           typename ValueType,
2305           typename... Extra>
2306 struct iterator_state {
2307     Iterator it;
2308     Sentinel end;
2309     bool first_or_done;
2310 };
2311 
2312 // Note: these helpers take the iterator by non-const reference because some
2313 // iterators in the wild can't be dereferenced when const. The & after Iterator
2314 // is required for MSVC < 16.9. SFINAE cannot be reused for result_type due to
2315 // bugs in ICC, NVCC, and PGI compilers. See PR #3293.
2316 template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
2317 struct iterator_access {
2318     using result_type = decltype(*std::declval<Iterator &>());
2319     // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
2320     result_type operator()(Iterator &it) const { return *it; }
2321 };
2322 
2323 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).first)>
2324 class iterator_key_access {
2325 private:
2326     using pair_type = decltype(*std::declval<Iterator &>());
2327 
2328 public:
2329     /* If either the pair itself or the element of the pair is a reference, we
2330      * want to return a reference, otherwise a value. When the decltype
2331      * expression is parenthesized it is based on the value category of the
2332      * expression; otherwise it is the declared type of the pair member.
2333      * The use of declval<pair_type> in the second branch rather than directly
2334      * using *std::declval<Iterator &>() is a workaround for nvcc
2335      * (it's not used in the first branch because going via decltype and back
2336      * through declval does not perfectly preserve references).
2337      */
2338     using result_type
2339         = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
2340                         decltype(((*std::declval<Iterator &>()).first)),
2341                         decltype(std::declval<pair_type>().first)>;
2342     result_type operator()(Iterator &it) const { return (*it).first; }
2343 };
2344 
2345 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
2346 class iterator_value_access {
2347 private:
2348     using pair_type = decltype(*std::declval<Iterator &>());
2349 
2350 public:
2351     using result_type
2352         = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
2353                         decltype(((*std::declval<Iterator &>()).second)),
2354                         decltype(std::declval<pair_type>().second)>;
2355     result_type operator()(Iterator &it) const { return (*it).second; }
2356 };
2357 
2358 template <typename Access,
2359           return_value_policy Policy,
2360           typename Iterator,
2361           typename Sentinel,
2362           typename ValueType,
2363           typename... Extra>
2364 iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra) {
2365     using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
2366     // TODO: state captures only the types of Extra, not the values
2367 
2368     if (!detail::get_type_info(typeid(state), false)) {
2369         class_<state>(handle(), "iterator", pybind11::module_local())
2370             .def("__iter__", [](state &s) -> state & { return s; })
2371             .def(
2372                 "__next__",
2373                 [](state &s) -> ValueType {
2374                     if (!s.first_or_done) {
2375                         ++s.it;
2376                     } else {
2377                         s.first_or_done = false;
2378                     }
2379                     if (s.it == s.end) {
2380                         s.first_or_done = true;
2381                         throw stop_iteration();
2382                     }
2383                     return Access()(s.it);
2384                     // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
2385                 },
2386                 std::forward<Extra>(extra)...,
2387                 Policy);
2388     }
2389 
2390     return cast(state{first, last, true});
2391 }
2392 
2393 PYBIND11_NAMESPACE_END(detail)
2394 
2395 /// Makes a python iterator from a first and past-the-end C++ InputIterator.
2396 template <return_value_policy Policy = return_value_policy::reference_internal,
2397           typename Iterator,
2398           typename Sentinel,
2399           typename ValueType = typename detail::iterator_access<Iterator>::result_type,
2400           typename... Extra>
2401 iterator make_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2402     return detail::make_iterator_impl<detail::iterator_access<Iterator>,
2403                                       Policy,
2404                                       Iterator,
2405                                       Sentinel,
2406                                       ValueType,
2407                                       Extra...>(first, last, std::forward<Extra>(extra)...);
2408 }
2409 
2410 /// Makes a python iterator over the keys (`.first`) of a iterator over pairs from a
2411 /// first and past-the-end InputIterator.
2412 template <return_value_policy Policy = return_value_policy::reference_internal,
2413           typename Iterator,
2414           typename Sentinel,
2415           typename KeyType = typename detail::iterator_key_access<Iterator>::result_type,
2416           typename... Extra>
2417 iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2418     return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
2419                                       Policy,
2420                                       Iterator,
2421                                       Sentinel,
2422                                       KeyType,
2423                                       Extra...>(first, last, std::forward<Extra>(extra)...);
2424 }
2425 
2426 /// Makes a python iterator over the values (`.second`) of a iterator over pairs from a
2427 /// first and past-the-end InputIterator.
2428 template <return_value_policy Policy = return_value_policy::reference_internal,
2429           typename Iterator,
2430           typename Sentinel,
2431           typename ValueType = typename detail::iterator_value_access<Iterator>::result_type,
2432           typename... Extra>
2433 iterator make_value_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2434     return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
2435                                       Policy,
2436                                       Iterator,
2437                                       Sentinel,
2438                                       ValueType,
2439                                       Extra...>(first, last, std::forward<Extra>(extra)...);
2440 }
2441 
2442 /// Makes an iterator over values of an stl container or other container supporting
2443 /// `std::begin()`/`std::end()`
2444 template <return_value_policy Policy = return_value_policy::reference_internal,
2445           typename Type,
2446           typename... Extra>
2447 iterator make_iterator(Type &value, Extra &&...extra) {
2448     return make_iterator<Policy>(
2449         std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2450 }
2451 
2452 /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
2453 /// `std::begin()`/`std::end()`
2454 template <return_value_policy Policy = return_value_policy::reference_internal,
2455           typename Type,
2456           typename... Extra>
2457 iterator make_key_iterator(Type &value, Extra &&...extra) {
2458     return make_key_iterator<Policy>(
2459         std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2460 }
2461 
2462 /// Makes an iterator over the values (`.second`) of a stl map-like container supporting
2463 /// `std::begin()`/`std::end()`
2464 template <return_value_policy Policy = return_value_policy::reference_internal,
2465           typename Type,
2466           typename... Extra>
2467 iterator make_value_iterator(Type &value, Extra &&...extra) {
2468     return make_value_iterator<Policy>(
2469         std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2470 }
2471 
2472 template <typename InputType, typename OutputType>
2473 void implicitly_convertible() {
2474     struct set_flag {
2475         bool &flag;
2476         explicit set_flag(bool &flag_) : flag(flag_) { flag_ = true; }
2477         ~set_flag() { flag = false; }
2478     };
2479     auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
2480         static bool currently_used = false;
2481         if (currently_used) { // implicit conversions are non-reentrant
2482             return nullptr;
2483         }
2484         set_flag flag_helper(currently_used);
2485         if (!detail::make_caster<InputType>().load(obj, false)) {
2486             return nullptr;
2487         }
2488         tuple args(1);
2489         args[0] = obj;
2490         PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
2491         if (result == nullptr) {
2492             PyErr_Clear();
2493         }
2494         return result;
2495     };
2496 
2497     if (auto *tinfo = detail::get_type_info(typeid(OutputType))) {
2498         tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
2499     } else {
2500         pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
2501     }
2502 }
2503 
2504 inline void register_exception_translator(ExceptionTranslator &&translator) {
2505     detail::get_internals().registered_exception_translators.push_front(
2506         std::forward<ExceptionTranslator>(translator));
2507 }
2508 
2509 /**
2510  * Add a new module-local exception translator. Locally registered functions
2511  * will be tried before any globally registered exception translators, which
2512  * will only be invoked if the module-local handlers do not deal with
2513  * the exception.
2514  */
2515 inline void register_local_exception_translator(ExceptionTranslator &&translator) {
2516     detail::get_local_internals().registered_exception_translators.push_front(
2517         std::forward<ExceptionTranslator>(translator));
2518 }
2519 
2520 /**
2521  * Wrapper to generate a new Python exception type.
2522  *
2523  * This should only be used with PyErr_SetString for now.
2524  * It is not (yet) possible to use as a py::base.
2525  * Template type argument is reserved for future use.
2526  */
2527 template <typename type>
2528 class exception : public object {
2529 public:
2530     exception() = default;
2531     exception(handle scope, const char *name, handle base = PyExc_Exception) {
2532         std::string full_name
2533             = scope.attr("__name__").cast<std::string>() + std::string(".") + name;
2534         m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), nullptr);
2535         if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name)) {
2536             pybind11_fail("Error during initialization: multiple incompatible "
2537                           "definitions with name \""
2538                           + std::string(name) + "\"");
2539         }
2540         scope.attr(name) = *this;
2541     }
2542 
2543     // Sets the current python exception to this exception object with the given message
2544     void operator()(const char *message) { PyErr_SetString(m_ptr, message); }
2545 };
2546 
2547 PYBIND11_NAMESPACE_BEGIN(detail)
2548 // Returns a reference to a function-local static exception object used in the simple
2549 // register_exception approach below.  (It would be simpler to have the static local variable
2550 // directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
2551 template <typename CppException>
2552 exception<CppException> &get_exception_object() {
2553     static exception<CppException> ex;
2554     return ex;
2555 }
2556 
2557 // Helper function for register_exception and register_local_exception
2558 template <typename CppException>
2559 exception<CppException> &
2560 register_exception_impl(handle scope, const char *name, handle base, bool isLocal) {
2561     auto &ex = detail::get_exception_object<CppException>();
2562     if (!ex) {
2563         ex = exception<CppException>(scope, name, base);
2564     }
2565 
2566     auto register_func
2567         = isLocal ? &register_local_exception_translator : &register_exception_translator;
2568 
2569     register_func([](std::exception_ptr p) {
2570         if (!p) {
2571             return;
2572         }
2573         try {
2574             std::rethrow_exception(p);
2575         } catch (const CppException &e) {
2576             detail::get_exception_object<CppException>()(e.what());
2577         }
2578     });
2579     return ex;
2580 }
2581 
2582 PYBIND11_NAMESPACE_END(detail)
2583 
2584 /**
2585  * Registers a Python exception in `m` of the given `name` and installs a translator to
2586  * translate the C++ exception to the created Python exception using the what() method.
2587  * This is intended for simple exception translations; for more complex translation, register the
2588  * exception object and translator directly.
2589  */
2590 template <typename CppException>
2591 exception<CppException> &
2592 register_exception(handle scope, const char *name, handle base = PyExc_Exception) {
2593     return detail::register_exception_impl<CppException>(scope, name, base, false /* isLocal */);
2594 }
2595 
2596 /**
2597  * Registers a Python exception in `m` of the given `name` and installs a translator to
2598  * translate the C++ exception to the created Python exception using the what() method.
2599  * This translator will only be used for exceptions that are thrown in this module and will be
2600  * tried before global exception translators, including those registered with register_exception.
2601  * This is intended for simple exception translations; for more complex translation, register the
2602  * exception object and translator directly.
2603  */
2604 template <typename CppException>
2605 exception<CppException> &
2606 register_local_exception(handle scope, const char *name, handle base = PyExc_Exception) {
2607     return detail::register_exception_impl<CppException>(scope, name, base, true /* isLocal */);
2608 }
2609 
2610 PYBIND11_NAMESPACE_BEGIN(detail)
2611 PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) {
2612     auto strings = tuple(args.size());
2613     for (size_t i = 0; i < args.size(); ++i) {
2614         strings[i] = str(args[i]);
2615     }
2616     auto sep = kwargs.contains("sep") ? kwargs["sep"] : str(" ");
2617     auto line = sep.attr("join")(std::move(strings));
2618 
2619     object file;
2620     if (kwargs.contains("file")) {
2621         file = kwargs["file"].cast<object>();
2622     } else {
2623         try {
2624             file = module_::import("sys").attr("stdout");
2625         } catch (const error_already_set &) {
2626             /* If print() is called from code that is executed as
2627                part of garbage collection during interpreter shutdown,
2628                importing 'sys' can fail. Give up rather than crashing the
2629                interpreter in this case. */
2630             return;
2631         }
2632     }
2633 
2634     auto write = file.attr("write");
2635     write(std::move(line));
2636     write(kwargs.contains("end") ? kwargs["end"] : str("\n"));
2637 
2638     if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) {
2639         file.attr("flush")();
2640     }
2641 }
2642 PYBIND11_NAMESPACE_END(detail)
2643 
2644 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
2645 void print(Args &&...args) {
2646     auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
2647     detail::print(c.args(), c.kwargs());
2648 }
2649 
2650 inline void
2651 error_already_set::m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr) {
2652     gil_scoped_acquire gil;
2653     error_scope scope;
2654     delete raw_ptr;
2655 }
2656 
2657 inline const char *error_already_set::what() const noexcept {
2658     gil_scoped_acquire gil;
2659     error_scope scope;
2660     return m_fetched_error->error_string().c_str();
2661 }
2662 
2663 PYBIND11_NAMESPACE_BEGIN(detail)
2664 
2665 inline function
2666 get_type_override(const void *this_ptr, const type_info *this_type, const char *name) {
2667     handle self = get_object_handle(this_ptr, this_type);
2668     if (!self) {
2669         return function();
2670     }
2671     handle type = type::handle_of(self);
2672     auto key = std::make_pair(type.ptr(), name);
2673 
2674     /* Cache functions that aren't overridden in Python to avoid
2675        many costly Python dictionary lookups below */
2676     auto &cache = get_internals().inactive_override_cache;
2677     if (cache.find(key) != cache.end()) {
2678         return function();
2679     }
2680 
2681     function override = getattr(self, name, function());
2682     if (override.is_cpp_function()) {
2683         cache.insert(std::move(key));
2684         return function();
2685     }
2686 
2687     /* Don't call dispatch code if invoked from overridden function.
2688        Unfortunately this doesn't work on PyPy. */
2689 #if !defined(PYPY_VERSION)
2690 #    if PY_VERSION_HEX >= 0x03090000
2691     PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
2692     if (frame != nullptr) {
2693         PyCodeObject *f_code = PyFrame_GetCode(frame);
2694         // f_code is guaranteed to not be NULL
2695         if ((std::string) str(f_code->co_name) == name && f_code->co_argcount > 0) {
2696             PyObject *locals = PyEval_GetLocals();
2697             if (locals != nullptr) {
2698                 PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code, "co_varnames");
2699                 PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
2700                 Py_DECREF(co_varnames);
2701                 PyObject *self_caller = dict_getitem(locals, self_arg);
2702                 if (self_caller == self.ptr()) {
2703                     Py_DECREF(f_code);
2704                     Py_DECREF(frame);
2705                     return function();
2706                 }
2707             }
2708         }
2709         Py_DECREF(f_code);
2710         Py_DECREF(frame);
2711     }
2712 #    else
2713     PyFrameObject *frame = PyThreadState_Get()->frame;
2714     if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name
2715         && frame->f_code->co_argcount > 0) {
2716         PyFrame_FastToLocals(frame);
2717         PyObject *self_caller
2718             = dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2719         if (self_caller == self.ptr()) {
2720             return function();
2721         }
2722     }
2723 #    endif
2724 
2725 #else
2726     /* PyPy currently doesn't provide a detailed cpyext emulation of
2727        frame objects, so we have to emulate this using Python. This
2728        is going to be slow..*/
2729     dict d;
2730     d["self"] = self;
2731     d["name"] = pybind11::str(name);
2732     PyObject *result
2733         = PyRun_String("import inspect\n"
2734                        "frame = inspect.currentframe()\n"
2735                        "if frame is not None:\n"
2736                        "    frame = frame.f_back\n"
2737                        "    if frame is not None and str(frame.f_code.co_name) == name and "
2738                        "frame.f_code.co_argcount > 0:\n"
2739                        "        self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2740                        "        if self_caller == self:\n"
2741                        "            self = None\n",
2742                        Py_file_input,
2743                        d.ptr(),
2744                        d.ptr());
2745     if (result == nullptr)
2746         throw error_already_set();
2747     Py_DECREF(result);
2748     if (d["self"].is_none())
2749         return function();
2750 #endif
2751 
2752     return override;
2753 }
2754 PYBIND11_NAMESPACE_END(detail)
2755 
2756 /** \rst
2757   Try to retrieve a python method by the provided name from the instance pointed to by the
2758   this_ptr.
2759 
2760   :this_ptr: The pointer to the object the overridden method should be retrieved for. This should
2761              be the first non-trampoline class encountered in the inheritance chain.
2762   :name: The name of the overridden Python method to retrieve.
2763   :return: The Python method by this name from the object or an empty function wrapper.
2764  \endrst */
2765 template <class T>
2766 function get_override(const T *this_ptr, const char *name) {
2767     auto *tinfo = detail::get_type_info(typeid(T));
2768     return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
2769 }
2770 
2771 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...)                                        \
2772     do {                                                                                          \
2773         pybind11::gil_scoped_acquire gil;                                                         \
2774         pybind11::function override                                                               \
2775             = pybind11::get_override(static_cast<const cname *>(this), name);                     \
2776         if (override) {                                                                           \
2777             auto o = override(__VA_ARGS__);                                                       \
2778             if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) {           \
2779                 static pybind11::detail::override_caster_t<ret_type> caster;                      \
2780                 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster);                \
2781             }                                                                                     \
2782             return pybind11::detail::cast_safe<ret_type>(std::move(o));                           \
2783         }                                                                                         \
2784     } while (false)
2785 
2786 /** \rst
2787     Macro to populate the virtual method in the trampoline class. This macro tries to look up a
2788     method named 'fn' from the Python side, deals with the :ref:`gil` and necessary argument
2789     conversions to call this method and return the appropriate type.
2790     See :ref:`overriding_virtuals` for more information. This macro should be used when the method
2791     name in C is not the same as the method name in Python. For example with `__str__`.
2792 
2793     .. code-block:: cpp
2794 
2795       std::string toString() override {
2796         PYBIND11_OVERRIDE_NAME(
2797             std::string, // Return type (ret_type)
2798             Animal,      // Parent class (cname)
2799             "__str__",   // Name of method in Python (name)
2800             toString,    // Name of function in C++ (fn)
2801         );
2802       }
2803 \endrst */
2804 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...)                                    \
2805     do {                                                                                          \
2806         PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2807         return cname::fn(__VA_ARGS__);                                                            \
2808     } while (false)
2809 
2810 /** \rst
2811     Macro for pure virtual functions, this function is identical to
2812     :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it throws if no override can be found.
2813 \endrst */
2814 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...)                               \
2815     do {                                                                                          \
2816         PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2817         pybind11::pybind11_fail(                                                                  \
2818             "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\"");   \
2819     } while (false)
2820 
2821 /** \rst
2822     Macro to populate the virtual method in the trampoline class. This macro tries to look up the
2823     method from the Python side, deals with the :ref:`gil` and necessary argument conversions to
2824     call this method and return the appropriate type. This macro should be used if the method name
2825     in C and in Python are identical.
2826     See :ref:`overriding_virtuals` for more information.
2827 
2828     .. code-block:: cpp
2829 
2830       class PyAnimal : public Animal {
2831       public:
2832           // Inherit the constructors
2833           using Animal::Animal;
2834 
2835           // Trampoline (need one for each virtual function)
2836           std::string go(int n_times) override {
2837               PYBIND11_OVERRIDE_PURE(
2838                   std::string, // Return type (ret_type)
2839                   Animal,      // Parent class (cname)
2840                   go,          // Name of function in C++ (must match Python name) (fn)
2841                   n_times      // Argument(s) (...)
2842               );
2843           }
2844       };
2845 \endrst */
2846 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...)                                               \
2847     PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2848 
2849 /** \rst
2850     Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`,
2851     except that it throws if no override can be found.
2852 \endrst */
2853 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...)                                          \
2854     PYBIND11_OVERRIDE_PURE_NAME(                                                                  \
2855         PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2856 
2857 // Deprecated versions
2858 
2859 PYBIND11_DEPRECATED("get_type_overload has been deprecated")
2860 inline function
2861 get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
2862     return detail::get_type_override(this_ptr, this_type, name);
2863 }
2864 
2865 template <class T>
2866 inline function get_overload(const T *this_ptr, const char *name) {
2867     return get_override(this_ptr, name);
2868 }
2869 
2870 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...)                                         \
2871     PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
2872 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...)                                    \
2873     PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
2874 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...)                               \
2875     PYBIND11_OVERRIDE_PURE_NAME(                                                                  \
2876         PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
2877 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...)                                               \
2878     PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
2879 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...)                                          \
2880     PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
2881 
2882 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)