]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - tidl/tidl-api.git/blob - tidl_api/pybind11/include/pybind11/pybind11.h
Adding pybind11 v2.2.4 to repo
[tidl/tidl-api.git] / tidl_api / pybind11 / include / pybind11 / pybind11.h
1 /*
2     pybind11/pybind11.h: Main header file of the C++11 python
3     binding generator library
5     Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
7     All rights reserved. Use of this source code is governed by a
8     BSD-style license that can be found in the LICENSE file.
9 */
11 #pragma once
13 #if defined(_MSC_VER)
14 #  pragma warning(push)
15 #  pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
16 #  pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
17 #  pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
18 #  pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
19 #  pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
20 #  pragma warning(disable: 4702) // warning C4702: unreachable code
21 #  pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
22 #elif defined(__INTEL_COMPILER)
23 #  pragma warning(push)
24 #  pragma warning(disable: 68)    // integer conversion resulted in a change of sign
25 #  pragma warning(disable: 186)   // pointless comparison of unsigned integer with zero
26 #  pragma warning(disable: 878)   // incompatible exception specifications
27 #  pragma warning(disable: 1334)  // the "template" keyword used for syntactic disambiguation may only be used within a template
28 #  pragma warning(disable: 1682)  // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem)
29 #  pragma warning(disable: 1875)  // offsetof applied to non-POD (Plain Old Data) types is nonstandard
30 #  pragma warning(disable: 2196)  // warning #2196: routine is both "inline" and "noinline"
31 #elif defined(__GNUG__) && !defined(__clang__)
32 #  pragma GCC diagnostic push
33 #  pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
34 #  pragma GCC diagnostic ignored "-Wunused-but-set-variable"
35 #  pragma GCC diagnostic ignored "-Wmissing-field-initializers"
36 #  pragma GCC diagnostic ignored "-Wstrict-aliasing"
37 #  pragma GCC diagnostic ignored "-Wattributes"
38 #  if __GNUC__ >= 7
39 #    pragma GCC diagnostic ignored "-Wnoexcept-type"
40 #  endif
41 #endif
43 #include "attr.h"
44 #include "options.h"
45 #include "detail/class.h"
46 #include "detail/init.h"
48 NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
50 /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
51 class cpp_function : public function {
52 public:
53     cpp_function() { }
55     /// Construct a cpp_function from a vanilla function pointer
56     template <typename Return, typename... Args, typename... Extra>
57     cpp_function(Return (*f)(Args...), const Extra&... extra) {
58         initialize(f, f, extra...);
59     }
61     /// Construct a cpp_function from a lambda function (possibly with internal state)
62     template <typename Func, typename... Extra,
63               typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
64     cpp_function(Func &&f, const Extra&... extra) {
65         initialize(std::forward<Func>(f),
66                    (detail::function_signature_t<Func> *) nullptr, extra...);
67     }
69     /// Construct a cpp_function from a class method (non-const)
70     template <typename Return, typename Class, typename... Arg, typename... Extra>
71     cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
72         initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
73                    (Return (*) (Class *, Arg...)) nullptr, extra...);
74     }
76     /// Construct a cpp_function from a class method (const)
77     template <typename Return, typename Class, typename... Arg, typename... Extra>
78     cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
79         initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
80                    (Return (*)(const Class *, Arg ...)) nullptr, extra...);
81     }
83     /// Return the function name
84     object name() const { return attr("__name__"); }
86 protected:
87     /// Space optimization: don't inline this frequently instantiated fragment
88     PYBIND11_NOINLINE detail::function_record *make_function_record() {
89         return new detail::function_record();
90     }
92     /// Special internal constructor for functors, lambda functions, etc.
93     template <typename Func, typename Return, typename... Args, typename... Extra>
94     void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
95         using namespace detail;
97         struct capture { remove_reference_t<Func> f; };
99         /* Store the function including any extra state it might have (e.g. a lambda capture object) */
100         auto rec = make_function_record();
102         /* Store the capture object directly in the function record if there is enough space */
103         if (sizeof(capture) <= sizeof(rec->data)) {
104             /* Without these pragmas, GCC warns that there might not be
105                enough space to use the placement new operator. However, the
106                'if' statement above ensures that this is the case. */
107 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
108 #  pragma GCC diagnostic push
109 #  pragma GCC diagnostic ignored "-Wplacement-new"
110 #endif
111             new ((capture *) &rec->data) capture { std::forward<Func>(f) };
112 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
113 #  pragma GCC diagnostic pop
114 #endif
115             if (!std::is_trivially_destructible<Func>::value)
116                 rec->free_data = [](function_record *r) { ((capture *) &r->data)->~capture(); };
117         } else {
118             rec->data[0] = new capture { std::forward<Func>(f) };
119             rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
120         }
122         /* Type casters for the function arguments and return value */
123         using cast_in = argument_loader<Args...>;
124         using cast_out = make_caster<
125             conditional_t<std::is_void<Return>::value, void_type, Return>
126         >;
128         static_assert(expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
129                       "The number of argument annotations does not match the number of function arguments");
131         /* Dispatch code which converts function arguments and performs the actual function call */
132         rec->impl = [](function_call &call) -> handle {
133             cast_in args_converter;
135             /* Try to cast the function arguments into the C++ domain */
136             if (!args_converter.load_args(call))
137                 return PYBIND11_TRY_NEXT_OVERLOAD;
139             /* Invoke call policy pre-call hook */
140             process_attributes<Extra...>::precall(call);
142             /* Get a pointer to the capture object */
143             auto data = (sizeof(capture) <= sizeof(call.func.data)
144                          ? &call.func.data : call.func.data[0]);
145             capture *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
147             /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
148             return_value_policy policy = return_value_policy_override<Return>::policy(call.func.policy);
150             /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
151             using Guard = extract_guard_t<Extra...>;
153             /* Perform the function call */
154             handle result = cast_out::cast(
155                 std::move(args_converter).template call<Return, Guard>(cap->f), policy, call.parent);
157             /* Invoke call policy post-call hook */
158             process_attributes<Extra...>::postcall(call, result);
160             return result;
161         };
163         /* Process any user-provided function attributes */
164         process_attributes<Extra...>::init(extra..., rec);
166         /* Generate a readable signature describing the function's arguments and return value types */
167         PYBIND11_DESCR signature = _("(") + cast_in::arg_names() + _(") -> ") + cast_out::name();
169         /* Register the function with Python from generic (non-templated) code */
170         initialize_generic(rec, signature.text(), signature.types(), sizeof...(Args));
172         if (cast_in::has_args) rec->has_args = true;
173         if (cast_in::has_kwargs) rec->has_kwargs = true;
175         /* Stash some additional information used by an important optimization in 'functional.h' */
176         using FunctionType = Return (*)(Args...);
177         constexpr bool is_function_ptr =
178             std::is_convertible<Func, FunctionType>::value &&
179             sizeof(capture) == sizeof(void *);
180         if (is_function_ptr) {
181             rec->is_stateless = true;
182             rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
183         }
184     }
186     /// Register a function call with Python (generic non-templated code goes here)
187     void initialize_generic(detail::function_record *rec, const char *text,
188                             const std::type_info *const *types, size_t args) {
190         /* Create copies of all referenced C-style strings */
191         rec->name = strdup(rec->name ? rec->name : "");
192         if (rec->doc) rec->doc = strdup(rec->doc);
193         for (auto &a: rec->args) {
194             if (a.name)
195                 a.name = strdup(a.name);
196             if (a.descr)
197                 a.descr = strdup(a.descr);
198             else if (a.value)
199                 a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
200         }
202         rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
204 #if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
205         if (rec->is_constructor && !rec->is_new_style_constructor) {
206             const auto class_name = std::string(((PyTypeObject *) rec->scope.ptr())->tp_name);
207             const auto func_name = std::string(rec->name);
208             PyErr_WarnEx(
209                 PyExc_FutureWarning,
210                 ("pybind11-bound class '" + class_name + "' is using an old-style "
211                  "placement-new '" + func_name + "' which has been deprecated. See "
212                  "the upgrade guide in pybind11's docs. This message is only visible "
213                  "when compiled in debug mode.").c_str(), 0
214             );
215         }
216 #endif
218         /* Generate a proper function signature */
219         std::string signature;
220         size_t type_depth = 0, char_index = 0, type_index = 0, arg_index = 0;
221         while (true) {
222             char c = text[char_index++];
223             if (c == '\0')
224                 break;
226             if (c == '{') {
227                 // Write arg name for everything except *args, **kwargs and return type.
228                 if (type_depth == 0 && text[char_index] != '*' && arg_index < args) {
229                     if (!rec->args.empty() && rec->args[arg_index].name) {
230                         signature += rec->args[arg_index].name;
231                     } else if (arg_index == 0 && rec->is_method) {
232                         signature += "self";
233                     } else {
234                         signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
235                     }
236                     signature += ": ";
237                 }
238                 ++type_depth;
239             } else if (c == '}') {
240                 --type_depth;
241                 if (type_depth == 0) {
242                     if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
243                         signature += "=";
244                         signature += rec->args[arg_index].descr;
245                     }
246                     arg_index++;
247                 }
248             } else if (c == '%') {
249                 const std::type_info *t = types[type_index++];
250                 if (!t)
251                     pybind11_fail("Internal error while parsing type signature (1)");
252                 if (auto tinfo = detail::get_type_info(*t)) {
253                     handle th((PyObject *) tinfo->type);
254                     signature +=
255                         th.attr("__module__").cast<std::string>() + "." +
256                         th.attr("__qualname__").cast<std::string>(); // Python 3.3+, but we backport it to earlier versions
257                 } else if (rec->is_new_style_constructor && arg_index == 0) {
258                     // A new-style `__init__` takes `self` as `value_and_holder`.
259                     // Rewrite it to the proper class type.
260                     signature +=
261                         rec->scope.attr("__module__").cast<std::string>() + "." +
262                         rec->scope.attr("__qualname__").cast<std::string>();
263                 } else {
264                     std::string tname(t->name());
265                     detail::clean_type_id(tname);
266                     signature += tname;
267                 }
268             } else {
269                 signature += c;
270             }
271         }
272         if (type_depth != 0 || types[type_index] != nullptr)
273             pybind11_fail("Internal error while parsing type signature (2)");
275         #if !defined(PYBIND11_CONSTEXPR_DESCR)
276             delete[] types;
277             delete[] text;
278         #endif
280 #if PY_MAJOR_VERSION < 3
281         if (strcmp(rec->name, "__next__") == 0) {
282             std::free(rec->name);
283             rec->name = strdup("next");
284         } else if (strcmp(rec->name, "__bool__") == 0) {
285             std::free(rec->name);
286             rec->name = strdup("__nonzero__");
287         }
288 #endif
289         rec->signature = strdup(signature.c_str());
290         rec->args.shrink_to_fit();
291         rec->nargs = (std::uint16_t) args;
293         if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr()))
294             rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
296         detail::function_record *chain = nullptr, *chain_start = rec;
297         if (rec->sibling) {
298             if (PyCFunction_Check(rec->sibling.ptr())) {
299                 auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
300                 chain = (detail::function_record *) rec_capsule;
301                 /* Never append a method to an overload chain of a parent class;
302                    instead, hide the parent's overloads in this case */
303                 if (!chain->scope.is(rec->scope))
304                     chain = nullptr;
305             }
306             // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
307             else if (!rec->sibling.is_none() && rec->name[0] != '_')
308                 pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
309                         "\" with a function of the same name");
310         }
312         if (!chain) {
313             /* No existing overload was found, create a new function object */
314             rec->def = new PyMethodDef();
315             std::memset(rec->def, 0, sizeof(PyMethodDef));
316             rec->def->ml_name = rec->name;
317             rec->def->ml_meth = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(*dispatcher));
318             rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
320             capsule rec_capsule(rec, [](void *ptr) {
321                 destruct((detail::function_record *) ptr);
322             });
324             object scope_module;
325             if (rec->scope) {
326                 if (hasattr(rec->scope, "__module__")) {
327                     scope_module = rec->scope.attr("__module__");
328                 } else if (hasattr(rec->scope, "__name__")) {
329                     scope_module = rec->scope.attr("__name__");
330                 }
331             }
333             m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
334             if (!m_ptr)
335                 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
336         } else {
337             /* Append at the end of the overload chain */
338             m_ptr = rec->sibling.ptr();
339             inc_ref();
340             chain_start = chain;
341             if (chain->is_method != rec->is_method)
342                 pybind11_fail("overloading a method with both static and instance methods is not supported; "
343                     #if defined(NDEBUG)
344                         "compile in debug mode for more details"
345                     #else
346                         "error while attempting to bind " + std::string(rec->is_method ? "instance" : "static") + " method " +
347                         std::string(pybind11::str(rec->scope.attr("__name__"))) + "." + std::string(rec->name) + signature
348                     #endif
349                 );
350             while (chain->next)
351                 chain = chain->next;
352             chain->next = rec;
353         }
355         std::string signatures;
356         int index = 0;
357         /* Create a nice pydoc rec including all signatures and
358            docstrings of the functions in the overload chain */
359         if (chain && options::show_function_signatures()) {
360             // First a generic signature
361             signatures += rec->name;
362             signatures += "(*args, **kwargs)\n";
363             signatures += "Overloaded function.\n\n";
364         }
365         // Then specific overload signatures
366         bool first_user_def = true;
367         for (auto it = chain_start; it != nullptr; it = it->next) {
368             if (options::show_function_signatures()) {
369                 if (index > 0) signatures += "\n";
370                 if (chain)
371                     signatures += std::to_string(++index) + ". ";
372                 signatures += rec->name;
373                 signatures += it->signature;
374                 signatures += "\n";
375             }
376             if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
377                 // If we're appending another docstring, and aren't printing function signatures, we
378                 // need to append a newline first:
379                 if (!options::show_function_signatures()) {
380                     if (first_user_def) first_user_def = false;
381                     else signatures += "\n";
382                 }
383                 if (options::show_function_signatures()) signatures += "\n";
384                 signatures += it->doc;
385                 if (options::show_function_signatures()) signatures += "\n";
386             }
387         }
389         /* Install docstring */
390         PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
391         if (func->m_ml->ml_doc)
392             std::free(const_cast<char *>(func->m_ml->ml_doc));
393         func->m_ml->ml_doc = strdup(signatures.c_str());
395         if (rec->is_method) {
396             m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
397             if (!m_ptr)
398                 pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
399             Py_DECREF(func);
400         }
401     }
403     /// When a cpp_function is GCed, release any memory allocated by pybind11
404     static void destruct(detail::function_record *rec) {
405         while (rec) {
406             detail::function_record *next = rec->next;
407             if (rec->free_data)
408                 rec->free_data(rec);
409             std::free((char *) rec->name);
410             std::free((char *) rec->doc);
411             std::free((char *) rec->signature);
412             for (auto &arg: rec->args) {
413                 std::free(const_cast<char *>(arg.name));
414                 std::free(const_cast<char *>(arg.descr));
415                 arg.value.dec_ref();
416             }
417             if (rec->def) {
418                 std::free(const_cast<char *>(rec->def->ml_doc));
419                 delete rec->def;
420             }
421             delete rec;
422             rec = next;
423         }
424     }
426     /// Main dispatch logic for calls to functions bound using pybind11
427     static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
428         using namespace detail;
430         /* Iterator over the list of potentially admissible overloads */
431         function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
432                         *it = overloads;
434         /* Need to know how many arguments + keyword arguments there are to pick the right overload */
435         const size_t n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
437         handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
438                result = PYBIND11_TRY_NEXT_OVERLOAD;
440         auto self_value_and_holder = value_and_holder();
441         if (overloads->is_constructor) {
442             const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
443             const auto pi = reinterpret_cast<instance *>(parent.ptr());
444             self_value_and_holder = pi->get_value_and_holder(tinfo, false);
446             if (!self_value_and_holder.type || !self_value_and_holder.inst) {
447                 PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid `self` argument");
448                 return nullptr;
449             }
451             // If this value is already registered it must mean __init__ is invoked multiple times;
452             // we really can't support that in C++, so just ignore the second __init__.
453             if (self_value_and_holder.instance_registered())
454                 return none().release().ptr();
455         }
457         try {
458             // We do this in two passes: in the first pass, we load arguments with `convert=false`;
459             // in the second, we allow conversion (except for arguments with an explicit
460             // py::arg().noconvert()).  This lets us prefer calls without conversion, with
461             // conversion as a fallback.
462             std::vector<function_call> second_pass;
464             // However, if there are no overloads, we can just skip the no-convert pass entirely
465             const bool overloaded = it != nullptr && it->next != nullptr;
467             for (; it != nullptr; it = it->next) {
469                 /* For each overload:
470                    1. Copy all positional arguments we were given, also checking to make sure that
471                       named positional arguments weren't *also* specified via kwarg.
472                    2. If we weren't given enough, try to make up the omitted ones by checking
473                       whether they were provided by a kwarg matching the `py::arg("name")` name.  If
474                       so, use it (and remove it from kwargs; if not, see if the function binding
475                       provided a default that we can use.
476                    3. Ensure that either all keyword arguments were "consumed", or that the function
477                       takes a kwargs argument to accept unconsumed kwargs.
478                    4. Any positional arguments still left get put into a tuple (for args), and any
479                       leftover kwargs get put into a dict.
480                    5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
481                       extra tuple or dict at the end of the positional arguments.
482                    6. Call the function call dispatcher (function_record::impl)
484                    If one of these fail, move on to the next overload and keep trying until we get a
485                    result other than PYBIND11_TRY_NEXT_OVERLOAD.
486                  */
488                 function_record &func = *it;
489                 size_t pos_args = func.nargs;    // Number of positional arguments that we need
490                 if (func.has_args) --pos_args;   // (but don't count py::args
491                 if (func.has_kwargs) --pos_args; //  or py::kwargs)
493                 if (!func.has_args && n_args_in > pos_args)
494                     continue; // Too many arguments for this overload
496                 if (n_args_in < pos_args && func.args.size() < pos_args)
497                     continue; // Not enough arguments given, and not enough defaults to fill in the blanks
499                 function_call call(func, parent);
501                 size_t args_to_copy = std::min(pos_args, n_args_in);
502                 size_t args_copied = 0;
504                 // 0. Inject new-style `self` argument
505                 if (func.is_new_style_constructor) {
506                     // The `value` may have been preallocated by an old-style `__init__`
507                     // if it was a preceding candidate for overload resolution.
508                     if (self_value_and_holder)
509                         self_value_and_holder.type->dealloc(self_value_and_holder);
511                     call.init_self = PyTuple_GET_ITEM(args_in, 0);
512                     call.args.push_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
513                     call.args_convert.push_back(false);
514                     ++args_copied;
515                 }
517                 // 1. Copy any position arguments given.
518                 bool bad_arg = false;
519                 for (; args_copied < args_to_copy; ++args_copied) {
520                     argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
521                     if (kwargs_in && arg_rec && arg_rec->name && PyDict_GetItemString(kwargs_in, arg_rec->name)) {
522                         bad_arg = true;
523                         break;
524                     }
526                     handle arg(PyTuple_GET_ITEM(args_in, args_copied));
527                     if (arg_rec && !arg_rec->none && arg.is_none()) {
528                         bad_arg = true;
529                         break;
530                     }
531                     call.args.push_back(arg);
532                     call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
533                 }
534                 if (bad_arg)
535                     continue; // Maybe it was meant for another overload (issue #688)
537                 // We'll need to copy this if we steal some kwargs for defaults
538                 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
540                 // 2. Check kwargs and, failing that, defaults that may help complete the list
541                 if (args_copied < pos_args) {
542                     bool copied_kwargs = false;
544                     for (; args_copied < pos_args; ++args_copied) {
545                         const auto &arg = func.args[args_copied];
547                         handle value;
548                         if (kwargs_in && arg.name)
549                             value = PyDict_GetItemString(kwargs.ptr(), arg.name);
551                         if (value) {
552                             // Consume a kwargs value
553                             if (!copied_kwargs) {
554                                 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
555                                 copied_kwargs = true;
556                             }
557                             PyDict_DelItemString(kwargs.ptr(), arg.name);
558                         } else if (arg.value) {
559                             value = arg.value;
560                         }
562                         if (value) {
563                             call.args.push_back(value);
564                             call.args_convert.push_back(arg.convert);
565                         }
566                         else
567                             break;
568                     }
570                     if (args_copied < pos_args)
571                         continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments
572                 }
574                 // 3. Check everything was consumed (unless we have a kwargs arg)
575                 if (kwargs && kwargs.size() > 0 && !func.has_kwargs)
576                     continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
578                 // 4a. If we have a py::args argument, create a new tuple with leftovers
579                 if (func.has_args) {
580                     tuple extra_args;
581                     if (args_to_copy == 0) {
582                         // We didn't copy out any position arguments from the args_in tuple, so we
583                         // can reuse it directly without copying:
584                         extra_args = reinterpret_borrow<tuple>(args_in);
585                     } else if (args_copied >= n_args_in) {
586                         extra_args = tuple(0);
587                     } else {
588                         size_t args_size = n_args_in - args_copied;
589                         extra_args = tuple(args_size);
590                         for (size_t i = 0; i < args_size; ++i) {
591                             extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i);
592                         }
593                     }
594                     call.args.push_back(extra_args);
595                     call.args_convert.push_back(false);
596                     call.args_ref = std::move(extra_args);
597                 }
599                 // 4b. If we have a py::kwargs, pass on any remaining kwargs
600                 if (func.has_kwargs) {
601                     if (!kwargs.ptr())
602                         kwargs = dict(); // If we didn't get one, send an empty one
603                     call.args.push_back(kwargs);
604                     call.args_convert.push_back(false);
605                     call.kwargs_ref = std::move(kwargs);
606                 }
608                 // 5. Put everything in a vector.  Not technically step 5, we've been building it
609                 // in `call.args` all along.
610                 #if !defined(NDEBUG)
611                 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
612                     pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
613                 #endif
615                 std::vector<bool> second_pass_convert;
616                 if (overloaded) {
617                     // We're in the first no-convert pass, so swap out the conversion flags for a
618                     // set of all-false flags.  If the call fails, we'll swap the flags back in for
619                     // the conversion-allowed call below.
620                     second_pass_convert.resize(func.nargs, false);
621                     call.args_convert.swap(second_pass_convert);
622                 }
624                 // 6. Call the function.
625                 try {
626                     loader_life_support guard{};
627                     result = func.impl(call);
628                 } catch (reference_cast_error &) {
629                     result = PYBIND11_TRY_NEXT_OVERLOAD;
630                 }
632                 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
633                     break;
635                 if (overloaded) {
636                     // The (overloaded) call failed; if the call has at least one argument that
637                     // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
638                     // then add this call to the list of second pass overloads to try.
639                     for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
640                         if (second_pass_convert[i]) {
641                             // Found one: swap the converting flags back in and store the call for
642                             // the second pass.
643                             call.args_convert.swap(second_pass_convert);
644                             second_pass.push_back(std::move(call));
645                             break;
646                         }
647                     }
648                 }
649             }
651             if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
652                 // The no-conversion pass finished without success, try again with conversion allowed
653                 for (auto &call : second_pass) {
654                     try {
655                         loader_life_support guard{};
656                         result = call.func.impl(call);
657                     } catch (reference_cast_error &) {
658                         result = PYBIND11_TRY_NEXT_OVERLOAD;
659                     }
661                     if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
662                         break;
663                 }
664             }
665         } catch (error_already_set &e) {
666             e.restore();
667             return nullptr;
668         } catch (...) {
669             /* When an exception is caught, give each registered exception
670                translator a chance to translate it to a Python exception
671                in reverse order of registration.
673                A translator may choose to do one of the following:
675                 - catch the exception and call PyErr_SetString or PyErr_SetObject
676                   to set a standard (or custom) Python exception, or
677                 - do nothing and let the exception fall through to the next translator, or
678                 - delegate translation to the next translator by throwing a new type of exception. */
680             auto last_exception = std::current_exception();
681             auto &registered_exception_translators = get_internals().registered_exception_translators;
682             for (auto& translator : registered_exception_translators) {
683                 try {
684                     translator(last_exception);
685                 } catch (...) {
686                     last_exception = std::current_exception();
687                     continue;
688                 }
689                 return nullptr;
690             }
691             PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
692             return nullptr;
693         }
695         auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
696             if (msg.find("std::") != std::string::npos) {
697                 msg += "\n\n"
698                        "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
699                        "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
700                        "conversions are optional and require extra headers to be included\n"
701                        "when compiling your pybind11 module.";
702             }
703         };
705         if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
706             if (overloads->is_operator)
707                 return handle(Py_NotImplemented).inc_ref().ptr();
709             std::string msg = std::string(overloads->name) + "(): incompatible " +
710                 std::string(overloads->is_constructor ? "constructor" : "function") +
711                 " arguments. The following argument types are supported:\n";
713             int ctr = 0;
714             for (function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
715                 msg += "    "+ std::to_string(++ctr) + ". ";
717                 bool wrote_sig = false;
718                 if (overloads->is_constructor) {
719                     // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
720                     std::string sig = it2->signature;
721                     size_t start = sig.find('(') + 7; // skip "(self: "
722                     if (start < sig.size()) {
723                         // End at the , for the next argument
724                         size_t end = sig.find(", "), next = end + 2;
725                         size_t ret = sig.rfind(" -> ");
726                         // Or the ), if there is no comma:
727                         if (end >= sig.size()) next = end = sig.find(')');
728                         if (start < end && next < sig.size()) {
729                             msg.append(sig, start, end - start);
730                             msg += '(';
731                             msg.append(sig, next, ret - next);
732                             wrote_sig = true;
733                         }
734                     }
735                 }
736                 if (!wrote_sig) msg += it2->signature;
738                 msg += "\n";
739             }
740             msg += "\nInvoked with: ";
741             auto args_ = reinterpret_borrow<tuple>(args_in);
742             bool some_args = false;
743             for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
744                 if (!some_args) some_args = true;
745                 else msg += ", ";
746                 msg += pybind11::repr(args_[ti]);
747             }
748             if (kwargs_in) {
749                 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
750                 if (kwargs.size() > 0) {
751                     if (some_args) msg += "; ";
752                     msg += "kwargs: ";
753                     bool first = true;
754                     for (auto kwarg : kwargs) {
755                         if (first) first = false;
756                         else msg += ", ";
757                         msg += pybind11::str("{}={!r}").format(kwarg.first, kwarg.second);
758                     }
759                 }
760             }
762             append_note_if_missing_header_is_suspected(msg);
763             PyErr_SetString(PyExc_TypeError, msg.c_str());
764             return nullptr;
765         } else if (!result) {
766             std::string msg = "Unable to convert function return value to a "
767                               "Python type! The signature was\n\t";
768             msg += it->signature;
769             append_note_if_missing_header_is_suspected(msg);
770             PyErr_SetString(PyExc_TypeError, msg.c_str());
771             return nullptr;
772         } else {
773             if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
774                 auto *pi = reinterpret_cast<instance *>(parent.ptr());
775                 self_value_and_holder.type->init_instance(pi, nullptr);
776             }
777             return result.ptr();
778         }
779     }
780 };
782 /// Wrapper for Python extension modules
783 class module : public object {
784 public:
785     PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
787     /// Create a new top-level Python module with the given name and docstring
788     explicit module(const char *name, const char *doc = nullptr) {
789         if (!options::show_user_defined_docstrings()) doc = nullptr;
790 #if PY_MAJOR_VERSION >= 3
791         PyModuleDef *def = new PyModuleDef();
792         std::memset(def, 0, sizeof(PyModuleDef));
793         def->m_name = name;
794         def->m_doc = doc;
795         def->m_size = -1;
796         Py_INCREF(def);
797         m_ptr = PyModule_Create(def);
798 #else
799         m_ptr = Py_InitModule3(name, nullptr, doc);
800 #endif
801         if (m_ptr == nullptr)
802             pybind11_fail("Internal error in module::module()");
803         inc_ref();
804     }
806     /** \rst
807         Create Python binding for a new function within the module scope. ``Func``
808         can be a plain C++ function, a function pointer, or a lambda function. For
809         details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
810     \endrst */
811     template <typename Func, typename... Extra>
812     module &def(const char *name_, Func &&f, const Extra& ... extra) {
813         cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
814                           sibling(getattr(*this, name_, none())), extra...);
815         // NB: allow overwriting here because cpp_function sets up a chain with the intention of
816         // overwriting (and has already checked internally that it isn't overwriting non-functions).
817         add_object(name_, func, true /* overwrite */);
818         return *this;
819     }
821     /** \rst
822         Create and return a new Python submodule with the given name and docstring.
823         This also works recursively, i.e.
825         .. code-block:: cpp
827             py::module m("example", "pybind11 example plugin");
828             py::module m2 = m.def_submodule("sub", "A submodule of 'example'");
829             py::module m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
830     \endrst */
831     module def_submodule(const char *name, const char *doc = nullptr) {
832         std::string full_name = std::string(PyModule_GetName(m_ptr))
833             + std::string(".") + std::string(name);
834         auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
835         if (doc && options::show_user_defined_docstrings())
836             result.attr("__doc__") = pybind11::str(doc);
837         attr(name) = result;
838         return result;
839     }
841     /// Import and return a module or throws `error_already_set`.
842     static module import(const char *name) {
843         PyObject *obj = PyImport_ImportModule(name);
844         if (!obj)
845             throw error_already_set();
846         return reinterpret_steal<module>(obj);
847     }
849     /// Reload the module or throws `error_already_set`.
850     void reload() {
851         PyObject *obj = PyImport_ReloadModule(ptr());
852         if (!obj)
853             throw error_already_set();
854         *this = reinterpret_steal<module>(obj);
855     }
857     // Adds an object to the module using the given name.  Throws if an object with the given name
858     // already exists.
859     //
860     // overwrite should almost always be false: attempting to overwrite objects that pybind11 has
861     // established will, in most cases, break things.
862     PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
863         if (!overwrite && hasattr(*this, name))
864             pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
865                     std::string(name) + "\"");
867         PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
868     }
869 };
871 /// \ingroup python_builtins
872 /// Return a dictionary representing the global variables in the current execution frame,
873 /// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
874 inline dict globals() {
875     PyObject *p = PyEval_GetGlobals();
876     return reinterpret_borrow<dict>(p ? p : module::import("__main__").attr("__dict__").ptr());
879 NAMESPACE_BEGIN(detail)
880 /// Generic support for creating new Python heap types
881 class generic_type : public object {
882     template <typename...> friend class class_;
883 public:
884     PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
885 protected:
886     void initialize(const type_record &rec) {
887         if (rec.scope && hasattr(rec.scope, rec.name))
888             pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
889                           "\": an object with that name is already defined");
891         if (rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
892             pybind11_fail("generic_type: type \"" + std::string(rec.name) +
893                           "\" is already registered!");
895         m_ptr = make_new_python_type(rec);
897         /* Register supplemental type information in C++ dict */
898         auto *tinfo = new detail::type_info();
899         tinfo->type = (PyTypeObject *) m_ptr;
900         tinfo->cpptype = rec.type;
901         tinfo->type_size = rec.type_size;
902         tinfo->operator_new = rec.operator_new;
903         tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
904         tinfo->init_instance = rec.init_instance;
905         tinfo->dealloc = rec.dealloc;
906         tinfo->simple_type = true;
907         tinfo->simple_ancestors = true;
908         tinfo->default_holder = rec.default_holder;
909         tinfo->module_local = rec.module_local;
911         auto &internals = get_internals();
912         auto tindex = std::type_index(*rec.type);
913         tinfo->direct_conversions = &internals.direct_conversions[tindex];
914         if (rec.module_local)
915             registered_local_types_cpp()[tindex] = tinfo;
916         else
917             internals.registered_types_cpp[tindex] = tinfo;
918         internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo };
920         if (rec.bases.size() > 1 || rec.multiple_inheritance) {
921             mark_parents_nonsimple(tinfo->type);
922             tinfo->simple_ancestors = false;
923         }
924         else if (rec.bases.size() == 1) {
925             auto parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
926             tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
927         }
929         if (rec.module_local) {
930             // Stash the local typeinfo and loader so that external modules can access it.
931             tinfo->module_local_load = &type_caster_generic::local_load;
932             setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
933         }
934     }
936     /// Helper function which tags all parents of a type using mult. inheritance
937     void mark_parents_nonsimple(PyTypeObject *value) {
938         auto t = reinterpret_borrow<tuple>(value->tp_bases);
939         for (handle h : t) {
940             auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
941             if (tinfo2)
942                 tinfo2->simple_type = false;
943             mark_parents_nonsimple((PyTypeObject *) h.ptr());
944         }
945     }
947     void install_buffer_funcs(
948             buffer_info *(*get_buffer)(PyObject *, void *),
949             void *get_buffer_data) {
950         PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
951         auto tinfo = detail::get_type_info(&type->ht_type);
953         if (!type->ht_type.tp_as_buffer)
954             pybind11_fail(
955                 "To be able to register buffer protocol support for the type '" +
956                 std::string(tinfo->type->tp_name) +
957                 "' the associated class<>(..) invocation must "
958                 "include the pybind11::buffer_protocol() annotation!");
960         tinfo->get_buffer = get_buffer;
961         tinfo->get_buffer_data = get_buffer_data;
962     }
964     void def_property_static_impl(const char *name,
965                                   handle fget, handle fset,
966                                   detail::function_record *rec_fget) {
967         const auto is_static = !(rec_fget->is_method && rec_fget->scope);
968         const auto has_doc = rec_fget->doc && pybind11::options::show_user_defined_docstrings();
970         auto property = handle((PyObject *) (is_static ? get_internals().static_property_type
971                                                        : &PyProperty_Type));
972         attr(name) = property(fget.ptr() ? fget : none(),
973                               fset.ptr() ? fset : none(),
974                               /*deleter*/none(),
975                               pybind11::str(has_doc ? rec_fget->doc : ""));
976     }
977 };
979 /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
980 template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator new))>>
981 void set_operator_new(type_record *r) { r->operator_new = &T::operator new; }
983 template <typename> void set_operator_new(...) { }
985 template <typename T, typename SFINAE = void> struct has_operator_delete : std::false_type { };
986 template <typename T> struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
987     : std::true_type { };
988 template <typename T, typename SFINAE = void> struct has_operator_delete_size : std::false_type { };
989 template <typename T> struct has_operator_delete_size<T, void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>>
990     : std::true_type { };
991 /// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
992 template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
993 void call_operator_delete(T *p, size_t) { T::operator delete(p); }
994 template <typename T, enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> = 0>
995 void call_operator_delete(T *p, size_t s) { T::operator delete(p, s); }
997 inline void call_operator_delete(void *p, size_t) { ::operator delete(p); }
999 NAMESPACE_END(detail)
1001 /// Given a pointer to a member function, cast it to its `Derived` version.
1002 /// Forward everything else unchanged.
1003 template <typename /*Derived*/, typename F>
1004 auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) { return std::forward<F>(f); }
1006 template <typename Derived, typename Return, typename Class, typename... Args>
1007 auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) { return pmf; }
1009 template <typename Derived, typename Return, typename Class, typename... Args>
1010 auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const { return pmf; }
1012 template <typename type_, typename... options>
1013 class class_ : public detail::generic_type {
1014     template <typename T> using is_holder = detail::is_holder_type<type_, T>;
1015     template <typename T> using is_subtype = detail::is_strict_base_of<type_, T>;
1016     template <typename T> using is_base = detail::is_strict_base_of<T, type_>;
1017     // struct instead of using here to help MSVC:
1018     template <typename T> struct is_valid_class_option :
1019         detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
1021 public:
1022     using type = type_;
1023     using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
1024     constexpr static bool has_alias = !std::is_void<type_alias>::value;
1025     using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
1027     static_assert(detail::all_of<is_valid_class_option<options>...>::value,
1028             "Unknown/invalid class_ template parameters provided");
1030     static_assert(!has_alias || std::is_polymorphic<type>::value,
1031             "Cannot use an alias class with a non-polymorphic type");
1033     PYBIND11_OBJECT(class_, generic_type, PyType_Check)
1035     template <typename... Extra>
1036     class_(handle scope, const char *name, const Extra &... extra) {
1037         using namespace detail;
1039         // MI can only be specified via class_ template options, not constructor parameters
1040         static_assert(
1041             none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
1042             (   constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
1043                 constexpr_sum(is_base<options>::value...)   == 0 && // no template option bases
1044                 none_of<std::is_same<multiple_inheritance, Extra>...>::value), // no multiple_inheritance attr
1045             "Error: multiple inheritance bases must be specified via class_ template options");
1047         type_record record;
1048         record.scope = scope;
1049         record.name = name;
1050         record.type = &typeid(type);
1051         record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
1052         record.holder_size = sizeof(holder_type);
1053         record.init_instance = init_instance;
1054         record.dealloc = dealloc;
1055         record.default_holder = std::is_same<holder_type, std::unique_ptr<type>>::value;
1057         set_operator_new<type>(&record);
1059         /* Register base classes specified via template arguments to class_, if any */
1060         PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
1062         /* Process optional arguments, if any */
1063         process_attributes<Extra...>::init(extra..., &record);
1065         generic_type::initialize(record);
1067         if (has_alias) {
1068             auto &instances = record.module_local ? registered_local_types_cpp() : get_internals().registered_types_cpp;
1069             instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
1070         }
1071     }
1073     template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
1074     static void add_base(detail::type_record &rec) {
1075         rec.add_base(typeid(Base), [](void *src) -> void * {
1076             return static_cast<Base *>(reinterpret_cast<type *>(src));
1077         });
1078     }
1080     template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
1081     static void add_base(detail::type_record &) { }
1083     template <typename Func, typename... Extra>
1084     class_ &def(const char *name_, Func&& f, const Extra&... extra) {
1085         cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), name(name_), is_method(*this),
1086                         sibling(getattr(*this, name_, none())), extra...);
1087         attr(cf.name()) = cf;
1088         return *this;
1089     }
1091     template <typename Func, typename... Extra> class_ &
1092     def_static(const char *name_, Func &&f, const Extra&... extra) {
1093         static_assert(!std::is_member_function_pointer<Func>::value,
1094                 "def_static(...) called with a non-static member function pointer");
1095         cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
1096                         sibling(getattr(*this, name_, none())), extra...);
1097         attr(cf.name()) = cf;
1098         return *this;
1099     }
1101     template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
1102     class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
1103         op.execute(*this, extra...);
1104         return *this;
1105     }
1107     template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
1108     class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
1109         op.execute_cast(*this, extra...);
1110         return *this;
1111     }
1113     template <typename... Args, typename... Extra>
1114     class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra&... extra) {
1115         init.execute(*this, extra...);
1116         return *this;
1117     }
1119     template <typename... Args, typename... Extra>
1120     class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra&... extra) {
1121         init.execute(*this, extra...);
1122         return *this;
1123     }
1125     template <typename... Args, typename... Extra>
1126     class_ &def(detail::initimpl::factory<Args...> &&init, const Extra&... extra) {
1127         std::move(init).execute(*this, extra...);
1128         return *this;
1129     }
1131     template <typename... Args, typename... Extra>
1132     class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
1133         std::move(pf).execute(*this, extra...);
1134         return *this;
1135     }
1137     template <typename Func> class_& def_buffer(Func &&func) {
1138         struct capture { Func func; };
1139         capture *ptr = new capture { std::forward<Func>(func) };
1140         install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
1141             detail::make_caster<type> caster;
1142             if (!caster.load(obj, false))
1143                 return nullptr;
1144             return new buffer_info(((capture *) ptr)->func(caster));
1145         }, ptr);
1146         return *this;
1147     }
1149     template <typename Return, typename Class, typename... Args>
1150     class_ &def_buffer(Return (Class::*func)(Args...)) {
1151         return def_buffer([func] (type &obj) { return (obj.*func)(); });
1152     }
1154     template <typename Return, typename Class, typename... Args>
1155     class_ &def_buffer(Return (Class::*func)(Args...) const) {
1156         return def_buffer([func] (const type &obj) { return (obj.*func)(); });
1157     }
1159     template <typename C, typename D, typename... Extra>
1160     class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
1161         static_assert(std::is_base_of<C, type>::value, "def_readwrite() requires a class member (or base class member)");
1162         cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this)),
1163                      fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
1164         def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
1165         return *this;
1166     }
1168     template <typename C, typename D, typename... Extra>
1169     class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
1170         static_assert(std::is_base_of<C, type>::value, "def_readonly() requires a class member (or base class member)");
1171         cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this));
1172         def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
1173         return *this;
1174     }
1176     template <typename D, typename... Extra>
1177     class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
1178         cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
1179                      fset([pm](object, const D &value) { *pm = value; }, scope(*this));
1180         def_property_static(name, fget, fset, return_value_policy::reference, extra...);
1181         return *this;
1182     }
1184     template <typename D, typename... Extra>
1185     class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
1186         cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
1187         def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
1188         return *this;
1189     }
1191     /// Uses return_value_policy::reference_internal by default
1192     template <typename Getter, typename... Extra>
1193     class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
1194         return def_property_readonly(name, cpp_function(method_adaptor<type>(fget)),
1195                                      return_value_policy::reference_internal, extra...);
1196     }
1198     /// Uses cpp_function's return_value_policy by default
1199     template <typename... Extra>
1200     class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
1201         return def_property(name, fget, cpp_function(), extra...);
1202     }
1204     /// Uses return_value_policy::reference by default
1205     template <typename Getter, typename... Extra>
1206     class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
1207         return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...);
1208     }
1210     /// Uses cpp_function's return_value_policy by default
1211     template <typename... Extra>
1212     class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
1213         return def_property_static(name, fget, cpp_function(), extra...);
1214     }
1216     /// Uses return_value_policy::reference_internal by default
1217     template <typename Getter, typename Setter, typename... Extra>
1218     class_ &def_property(const char *name, const Getter &fget, const Setter &fset, const Extra& ...extra) {
1219         return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
1220     }
1221     template <typename Getter, typename... Extra>
1222     class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1223         return def_property(name, cpp_function(method_adaptor<type>(fget)), fset,
1224                             return_value_policy::reference_internal, extra...);
1225     }
1227     /// Uses cpp_function's return_value_policy by default
1228     template <typename... Extra>
1229     class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1230         return def_property_static(name, fget, fset, is_method(*this), extra...);
1231     }
1233     /// Uses return_value_policy::reference by default
1234     template <typename Getter, typename... Extra>
1235     class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1236         return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1237     }
1239     /// Uses cpp_function's return_value_policy by default
1240     template <typename... Extra>
1241     class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1242         auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1243         char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
1244         detail::process_attributes<Extra...>::init(extra..., rec_fget);
1245         if (rec_fget->doc && rec_fget->doc != doc_prev) {
1246             free(doc_prev);
1247             rec_fget->doc = strdup(rec_fget->doc);
1248         }
1249         if (rec_fset) {
1250             doc_prev = rec_fset->doc;
1251             detail::process_attributes<Extra...>::init(extra..., rec_fset);
1252             if (rec_fset->doc && rec_fset->doc != doc_prev) {
1253                 free(doc_prev);
1254                 rec_fset->doc = strdup(rec_fset->doc);
1255             }
1256         }
1257         def_property_static_impl(name, fget, fset, rec_fget);
1258         return *this;
1259     }
1261 private:
1262     /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1263     template <typename T>
1264     static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1265             const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
1266         try {
1267             auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1268                     v_h.value_ptr<type>()->shared_from_this());
1269             if (sh) {
1270                 new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
1271                 v_h.set_holder_constructed();
1272             }
1273         } catch (const std::bad_weak_ptr &) {}
1275         if (!v_h.holder_constructed() && inst->owned) {
1276             new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1277             v_h.set_holder_constructed();
1278         }
1279     }
1281     static void init_holder_from_existing(const detail::value_and_holder &v_h,
1282             const holder_type *holder_ptr, std::true_type /*is_copy_constructible*/) {
1283         new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1284     }
1286     static void init_holder_from_existing(const detail::value_and_holder &v_h,
1287             const holder_type *holder_ptr, std::false_type /*is_copy_constructible*/) {
1288         new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1289     }
1291     /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
1292     static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1293             const holder_type *holder_ptr, const void * /* dummy -- not enable_shared_from_this<T>) */) {
1294         if (holder_ptr) {
1295             init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1296             v_h.set_holder_constructed();
1297         } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
1298             new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1299             v_h.set_holder_constructed();
1300         }
1301     }
1303     /// Performs instance initialization including constructing a holder and registering the known
1304     /// instance.  Should be called as soon as the `type` value_ptr is set for an instance.  Takes an
1305     /// optional pointer to an existing holder to use; if not specified and the instance is
1306     /// `.owned`, a new holder will be constructed to manage the value pointer.
1307     static void init_instance(detail::instance *inst, const void *holder_ptr) {
1308         auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
1309         if (!v_h.instance_registered()) {
1310             register_instance(inst, v_h.value_ptr(), v_h.type);
1311             v_h.set_instance_registered();
1312         }
1313         init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
1314     }
1316     /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
1317     static void dealloc(detail::value_and_holder &v_h) {
1318         if (v_h.holder_constructed()) {
1319             v_h.holder<holder_type>().~holder_type();
1320             v_h.set_holder_constructed(false);
1321         }
1322         else {
1323             detail::call_operator_delete(v_h.value_ptr<type>(), v_h.type->type_size);
1324         }
1325         v_h.value_ptr() = nullptr;
1326     }
1328     static detail::function_record *get_function_record(handle h) {
1329         h = detail::get_function(h);
1330         return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
1331                  : nullptr;
1332     }
1333 };
1335 /// Binds an existing constructor taking arguments Args...
1336 template <typename... Args> detail::initimpl::constructor<Args...> init() { return {}; }
1337 /// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
1338 /// when not inheriting on the Python side).
1339 template <typename... Args> detail::initimpl::alias_constructor<Args...> init_alias() { return {}; }
1341 /// Binds a factory function as a constructor
1342 template <typename Func, typename Ret = detail::initimpl::factory<Func>>
1343 Ret init(Func &&f) { return {std::forward<Func>(f)}; }
1345 /// Dual-argument factory function: the first function is called when no alias is needed, the second
1346 /// when an alias is needed (i.e. due to python-side inheritance).  Arguments must be identical.
1347 template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1348 Ret init(CFunc &&c, AFunc &&a) {
1349     return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1352 /// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
1353 /// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
1354 template <typename GetState, typename SetState>
1355 detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
1356     return {std::forward<GetState>(g), std::forward<SetState>(s)};
1359 /// Binds C++ enumerations and enumeration classes to Python
1360 template <typename Type> class enum_ : public class_<Type> {
1361 public:
1362     using class_<Type>::def;
1363     using class_<Type>::def_property_readonly_static;
1364     using Scalar = typename std::underlying_type<Type>::type;
1366     template <typename... Extra>
1367     enum_(const handle &scope, const char *name, const Extra&... extra)
1368       : class_<Type>(scope, name, extra...), m_entries(), m_parent(scope) {
1370         constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
1372         auto m_entries_ptr = m_entries.inc_ref().ptr();
1373         def("__repr__", [name, m_entries_ptr](Type value) -> pybind11::str {
1374             for (const auto &kv : reinterpret_borrow<dict>(m_entries_ptr)) {
1375                 if (pybind11::cast<Type>(kv.second) == value)
1376                     return pybind11::str("{}.{}").format(name, kv.first);
1377             }
1378             return pybind11::str("{}.???").format(name);
1379         });
1380         def_property_readonly_static("__members__", [m_entries_ptr](object /* self */) {
1381             dict m;
1382             for (const auto &kv : reinterpret_borrow<dict>(m_entries_ptr))
1383                 m[kv.first] = kv.second;
1384             return m;
1385         }, return_value_policy::copy);
1386         def(init([](Scalar i) { return static_cast<Type>(i); }));
1387         def("__int__", [](Type value) { return (Scalar) value; });
1388         #if PY_MAJOR_VERSION < 3
1389             def("__long__", [](Type value) { return (Scalar) value; });
1390         #endif
1391         def("__eq__", [](const Type &value, Type *value2) { return value2 && value == *value2; });
1392         def("__ne__", [](const Type &value, Type *value2) { return !value2 || value != *value2; });
1393         if (is_arithmetic) {
1394             def("__lt__", [](const Type &value, Type *value2) { return value2 && value < *value2; });
1395             def("__gt__", [](const Type &value, Type *value2) { return value2 && value > *value2; });
1396             def("__le__", [](const Type &value, Type *value2) { return value2 && value <= *value2; });
1397             def("__ge__", [](const Type &value, Type *value2) { return value2 && value >= *value2; });
1398         }
1399         if (std::is_convertible<Type, Scalar>::value) {
1400             // Don't provide comparison with the underlying type if the enum isn't convertible,
1401             // i.e. if Type is a scoped enum, mirroring the C++ behaviour.  (NB: we explicitly
1402             // convert Type to Scalar below anyway because this needs to compile).
1403             def("__eq__", [](const Type &value, Scalar value2) { return (Scalar) value == value2; });
1404             def("__ne__", [](const Type &value, Scalar value2) { return (Scalar) value != value2; });
1405             if (is_arithmetic) {
1406                 def("__lt__", [](const Type &value, Scalar value2) { return (Scalar) value < value2; });
1407                 def("__gt__", [](const Type &value, Scalar value2) { return (Scalar) value > value2; });
1408                 def("__le__", [](const Type &value, Scalar value2) { return (Scalar) value <= value2; });
1409                 def("__ge__", [](const Type &value, Scalar value2) { return (Scalar) value >= value2; });
1410                 def("__invert__", [](const Type &value) { return ~((Scalar) value); });
1411                 def("__and__", [](const Type &value, Scalar value2) { return (Scalar) value & value2; });
1412                 def("__or__", [](const Type &value, Scalar value2) { return (Scalar) value | value2; });
1413                 def("__xor__", [](const Type &value, Scalar value2) { return (Scalar) value ^ value2; });
1414                 def("__rand__", [](const Type &value, Scalar value2) { return (Scalar) value & value2; });
1415                 def("__ror__", [](const Type &value, Scalar value2) { return (Scalar) value | value2; });
1416                 def("__rxor__", [](const Type &value, Scalar value2) { return (Scalar) value ^ value2; });
1417                 def("__and__", [](const Type &value, const Type &value2) { return (Scalar) value & (Scalar) value2; });
1418                 def("__or__", [](const Type &value, const Type &value2) { return (Scalar) value | (Scalar) value2; });
1419                 def("__xor__", [](const Type &value, const Type &value2) { return (Scalar) value ^ (Scalar) value2; });
1420             }
1421         }
1422         def("__hash__", [](const Type &value) { return (Scalar) value; });
1423         // Pickling and unpickling -- needed for use with the 'multiprocessing' module
1424         def(pickle([](const Type &value) { return pybind11::make_tuple((Scalar) value); },
1425                    [](tuple t) { return static_cast<Type>(t[0].cast<Scalar>()); }));
1426     }
1428     /// Export enumeration entries into the parent scope
1429     enum_& export_values() {
1430         for (const auto &kv : m_entries)
1431             m_parent.attr(kv.first) = kv.second;
1432         return *this;
1433     }
1435     /// Add an enumeration entry
1436     enum_& value(char const* name, Type value) {
1437         auto v = pybind11::cast(value, return_value_policy::copy);
1438         this->attr(name) = v;
1439         m_entries[pybind11::str(name)] = v;
1440         return *this;
1441     }
1443 private:
1444     dict m_entries;
1445     handle m_parent;
1446 };
1448 NAMESPACE_BEGIN(detail)
1451 inline void keep_alive_impl(handle nurse, handle patient) {
1452     if (!nurse || !patient)
1453         pybind11_fail("Could not activate keep_alive!");
1455     if (patient.is_none() || nurse.is_none())
1456         return; /* Nothing to keep alive or nothing to be kept alive by */
1458     auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
1459     if (!tinfo.empty()) {
1460         /* It's a pybind-registered type, so we can store the patient in the
1461          * internal list. */
1462         add_patient(nurse.ptr(), patient.ptr());
1463     }
1464     else {
1465         /* Fall back to clever approach based on weak references taken from
1466          * Boost.Python. This is not used for pybind-registered types because
1467          * the objects can be destroyed out-of-order in a GC pass. */
1468         cpp_function disable_lifesupport(
1469             [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
1471         weakref wr(nurse, disable_lifesupport);
1473         patient.inc_ref(); /* reference patient and leak the weak reference */
1474         (void) wr.release();
1475     }
1478 PYBIND11_NOINLINE inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
1479     auto get_arg = [&](size_t n) {
1480         if (n == 0)
1481             return ret;
1482         else if (n == 1 && call.init_self)
1483             return call.init_self;
1484         else if (n <= call.args.size())
1485             return call.args[n - 1];
1486         return handle();
1487     };
1489     keep_alive_impl(get_arg(Nurse), get_arg(Patient));
1492 inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type) {
1493     auto res = get_internals().registered_types_py
1494 #ifdef __cpp_lib_unordered_map_try_emplace
1495         .try_emplace(type);
1496 #else
1497         .emplace(type, std::vector<detail::type_info *>());
1498 #endif
1499     if (res.second) {
1500         // New cache entry created; set up a weak reference to automatically remove it if the type
1501         // gets destroyed:
1502         weakref((PyObject *) type, cpp_function([type](handle wr) {
1503             get_internals().registered_types_py.erase(type);
1504             wr.dec_ref();
1505         })).release();
1506     }
1508     return res;
1511 template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
1512 struct iterator_state {
1513     Iterator it;
1514     Sentinel end;
1515     bool first_or_done;
1516 };
1518 NAMESPACE_END(detail)
1520 /// Makes a python iterator from a first and past-the-end C++ InputIterator.
1521 template <return_value_policy Policy = return_value_policy::reference_internal,
1522           typename Iterator,
1523           typename Sentinel,
1524           typename ValueType = decltype(*std::declval<Iterator>()),
1525           typename... Extra>
1526 iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1527     typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
1529     if (!detail::get_type_info(typeid(state), false)) {
1530         class_<state>(handle(), "iterator", pybind11::module_local())
1531             .def("__iter__", [](state &s) -> state& { return s; })
1532             .def("__next__", [](state &s) -> ValueType {
1533                 if (!s.first_or_done)
1534                     ++s.it;
1535                 else
1536                     s.first_or_done = false;
1537                 if (s.it == s.end) {
1538                     s.first_or_done = true;
1539                     throw stop_iteration();
1540                 }
1541                 return *s.it;
1542             }, std::forward<Extra>(extra)..., Policy);
1543     }
1545     return cast(state{first, last, true});
1548 /// Makes an python iterator over the keys (`.first`) of a iterator over pairs from a
1549 /// first and past-the-end InputIterator.
1550 template <return_value_policy Policy = return_value_policy::reference_internal,
1551           typename Iterator,
1552           typename Sentinel,
1553           typename KeyType = decltype((*std::declval<Iterator>()).first),
1554           typename... Extra>
1555 iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1556     typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
1558     if (!detail::get_type_info(typeid(state), false)) {
1559         class_<state>(handle(), "iterator", pybind11::module_local())
1560             .def("__iter__", [](state &s) -> state& { return s; })
1561             .def("__next__", [](state &s) -> KeyType {
1562                 if (!s.first_or_done)
1563                     ++s.it;
1564                 else
1565                     s.first_or_done = false;
1566                 if (s.it == s.end) {
1567                     s.first_or_done = true;
1568                     throw stop_iteration();
1569                 }
1570                 return (*s.it).first;
1571             }, std::forward<Extra>(extra)..., Policy);
1572     }
1574     return cast(state{first, last, true});
1577 /// Makes an iterator over values of an stl container or other container supporting
1578 /// `std::begin()`/`std::end()`
1579 template <return_value_policy Policy = return_value_policy::reference_internal,
1580           typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
1581     return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
1584 /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
1585 /// `std::begin()`/`std::end()`
1586 template <return_value_policy Policy = return_value_policy::reference_internal,
1587           typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
1588     return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
1591 template <typename InputType, typename OutputType> void implicitly_convertible() {
1592     struct set_flag {
1593         bool &flag;
1594         set_flag(bool &flag) : flag(flag) { flag = true; }
1595         ~set_flag() { flag = false; }
1596     };
1597     auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
1598         static bool currently_used = false;
1599         if (currently_used) // implicit conversions are non-reentrant
1600             return nullptr;
1601         set_flag flag_helper(currently_used);
1602         if (!detail::make_caster<InputType>().load(obj, false))
1603             return nullptr;
1604         tuple args(1);
1605         args[0] = obj;
1606         PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1607         if (result == nullptr)
1608             PyErr_Clear();
1609         return result;
1610     };
1612     if (auto tinfo = detail::get_type_info(typeid(OutputType)))
1613         tinfo->implicit_conversions.push_back(implicit_caster);
1614     else
1615         pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
1618 template <typename ExceptionTranslator>
1619 void register_exception_translator(ExceptionTranslator&& translator) {
1620     detail::get_internals().registered_exception_translators.push_front(
1621         std::forward<ExceptionTranslator>(translator));
1624 /**
1625  * Wrapper to generate a new Python exception type.
1626  *
1627  * This should only be used with PyErr_SetString for now.
1628  * It is not (yet) possible to use as a py::base.
1629  * Template type argument is reserved for future use.
1630  */
1631 template <typename type>
1632 class exception : public object {
1633 public:
1634     exception() = default;
1635     exception(handle scope, const char *name, PyObject *base = PyExc_Exception) {
1636         std::string full_name = scope.attr("__name__").cast<std::string>() +
1637                                 std::string(".") + name;
1638         m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base, NULL);
1639         if (hasattr(scope, name))
1640             pybind11_fail("Error during initialization: multiple incompatible "
1641                           "definitions with name \"" + std::string(name) + "\"");
1642         scope.attr(name) = *this;
1643     }
1645     // Sets the current python exception to this exception object with the given message
1646     void operator()(const char *message) {
1647         PyErr_SetString(m_ptr, message);
1648     }
1649 };
1651 NAMESPACE_BEGIN(detail)
1652 // Returns a reference to a function-local static exception object used in the simple
1653 // register_exception approach below.  (It would be simpler to have the static local variable
1654 // directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
1655 template <typename CppException>
1656 exception<CppException> &get_exception_object() { static exception<CppException> ex; return ex; }
1657 NAMESPACE_END(detail)
1659 /**
1660  * Registers a Python exception in `m` of the given `name` and installs an exception translator to
1661  * translate the C++ exception to the created Python exception using the exceptions what() method.
1662  * This is intended for simple exception translations; for more complex translation, register the
1663  * exception object and translator directly.
1664  */
1665 template <typename CppException>
1666 exception<CppException> &register_exception(handle scope,
1667                                             const char *name,
1668                                             PyObject *base = PyExc_Exception) {
1669     auto &ex = detail::get_exception_object<CppException>();
1670     if (!ex) ex = exception<CppException>(scope, name, base);
1672     register_exception_translator([](std::exception_ptr p) {
1673         if (!p) return;
1674         try {
1675             std::rethrow_exception(p);
1676         } catch (const CppException &e) {
1677             detail::get_exception_object<CppException>()(e.what());
1678         }
1679     });
1680     return ex;
1683 NAMESPACE_BEGIN(detail)
1684 PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
1685     auto strings = tuple(args.size());
1686     for (size_t i = 0; i < args.size(); ++i) {
1687         strings[i] = str(args[i]);
1688     }
1689     auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
1690     auto line = sep.attr("join")(strings);
1692     object file;
1693     if (kwargs.contains("file")) {
1694         file = kwargs["file"].cast<object>();
1695     } else {
1696         try {
1697             file = module::import("sys").attr("stdout");
1698         } catch (const error_already_set &) {
1699             /* If print() is called from code that is executed as
1700                part of garbage collection during interpreter shutdown,
1701                importing 'sys' can fail. Give up rather than crashing the
1702                interpreter in this case. */
1703             return;
1704         }
1705     }
1707     auto write = file.attr("write");
1708     write(line);
1709     write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
1711     if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
1712         file.attr("flush")();
1714 NAMESPACE_END(detail)
1716 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1717 void print(Args &&...args) {
1718     auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
1719     detail::print(c.args(), c.kwargs());
1722 #if defined(WITH_THREAD) && !defined(PYPY_VERSION)
1724 /* The functions below essentially reproduce the PyGILState_* API using a RAII
1725  * pattern, but there are a few important differences:
1726  *
1727  * 1. When acquiring the GIL from an non-main thread during the finalization
1728  *    phase, the GILState API blindly terminates the calling thread, which
1729  *    is often not what is wanted. This API does not do this.
1730  *
1731  * 2. The gil_scoped_release function can optionally cut the relationship
1732  *    of a PyThreadState and its associated thread, which allows moving it to
1733  *    another thread (this is a fairly rare/advanced use case).
1734  *
1735  * 3. The reference count of an acquired thread state can be controlled. This
1736  *    can be handy to prevent cases where callbacks issued from an external
1737  *    thread would otherwise constantly construct and destroy thread state data
1738  *    structures.
1739  *
1740  * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
1741  * example which uses features 2 and 3 to migrate the Python thread of
1742  * execution to another thread (to run the event loop on the original thread,
1743  * in this case).
1744  */
1746 class gil_scoped_acquire {
1747 public:
1748     PYBIND11_NOINLINE gil_scoped_acquire() {
1749         auto const &internals = detail::get_internals();
1750         tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
1752         if (!tstate) {
1753             tstate = PyThreadState_New(internals.istate);
1754             #if !defined(NDEBUG)
1755                 if (!tstate)
1756                     pybind11_fail("scoped_acquire: could not create thread state!");
1757             #endif
1758             tstate->gilstate_counter = 0;
1759             PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
1760         } else {
1761             release = detail::get_thread_state_unchecked() != tstate;
1762         }
1764         if (release) {
1765             /* Work around an annoying assertion in PyThreadState_Swap */
1766             #if defined(Py_DEBUG)
1767                 PyInterpreterState *interp = tstate->interp;
1768                 tstate->interp = nullptr;
1769             #endif
1770             PyEval_AcquireThread(tstate);
1771             #if defined(Py_DEBUG)
1772                 tstate->interp = interp;
1773             #endif
1774         }
1776         inc_ref();
1777     }
1779     void inc_ref() {
1780         ++tstate->gilstate_counter;
1781     }
1783     PYBIND11_NOINLINE void dec_ref() {
1784         --tstate->gilstate_counter;
1785         #if !defined(NDEBUG)
1786             if (detail::get_thread_state_unchecked() != tstate)
1787                 pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
1788             if (tstate->gilstate_counter < 0)
1789                 pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
1790         #endif
1791         if (tstate->gilstate_counter == 0) {
1792             #if !defined(NDEBUG)
1793                 if (!release)
1794                     pybind11_fail("scoped_acquire::dec_ref(): internal error!");
1795             #endif
1796             PyThreadState_Clear(tstate);
1797             PyThreadState_DeleteCurrent();
1798             PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
1799             release = false;
1800         }
1801     }
1803     PYBIND11_NOINLINE ~gil_scoped_acquire() {
1804         dec_ref();
1805         if (release)
1806            PyEval_SaveThread();
1807     }
1808 private:
1809     PyThreadState *tstate = nullptr;
1810     bool release = true;
1811 };
1813 class gil_scoped_release {
1814 public:
1815     explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
1816         // `get_internals()` must be called here unconditionally in order to initialize
1817         // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
1818         // initialization race could occur as multiple threads try `gil_scoped_acquire`.
1819         const auto &internals = detail::get_internals();
1820         tstate = PyEval_SaveThread();
1821         if (disassoc) {
1822             auto key = internals.tstate;
1823             PYBIND11_TLS_DELETE_VALUE(key);
1824         }
1825     }
1826     ~gil_scoped_release() {
1827         if (!tstate)
1828             return;
1829         PyEval_RestoreThread(tstate);
1830         if (disassoc) {
1831             auto key = detail::get_internals().tstate;
1832             PYBIND11_TLS_REPLACE_VALUE(key, tstate);
1833         }
1834     }
1835 private:
1836     PyThreadState *tstate;
1837     bool disassoc;
1838 };
1839 #elif defined(PYPY_VERSION)
1840 class gil_scoped_acquire {
1841     PyGILState_STATE state;
1842 public:
1843     gil_scoped_acquire() { state = PyGILState_Ensure(); }
1844     ~gil_scoped_acquire() { PyGILState_Release(state); }
1845 };
1847 class gil_scoped_release {
1848     PyThreadState *state;
1849 public:
1850     gil_scoped_release() { state = PyEval_SaveThread(); }
1851     ~gil_scoped_release() { PyEval_RestoreThread(state); }
1852 };
1853 #else
1854 class gil_scoped_acquire { };
1855 class gil_scoped_release { };
1856 #endif
1858 error_already_set::~error_already_set() {
1859     if (type) {
1860         error_scope scope;
1861         gil_scoped_acquire gil;
1862         type.release().dec_ref();
1863         value.release().dec_ref();
1864         trace.release().dec_ref();
1865     }
1868 inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name)  {
1869     handle self = detail::get_object_handle(this_ptr, this_type);
1870     if (!self)
1871         return function();
1872     handle type = self.get_type();
1873     auto key = std::make_pair(type.ptr(), name);
1875     /* Cache functions that aren't overloaded in Python to avoid
1876        many costly Python dictionary lookups below */
1877     auto &cache = detail::get_internals().inactive_overload_cache;
1878     if (cache.find(key) != cache.end())
1879         return function();
1881     function overload = getattr(self, name, function());
1882     if (overload.is_cpp_function()) {
1883         cache.insert(key);
1884         return function();
1885     }
1887     /* Don't call dispatch code if invoked from overridden function.
1888        Unfortunately this doesn't work on PyPy. */
1889 #if !defined(PYPY_VERSION)
1890     PyFrameObject *frame = PyThreadState_Get()->frame;
1891     if (frame && (std::string) str(frame->f_code->co_name) == name &&
1892         frame->f_code->co_argcount > 0) {
1893         PyFrame_FastToLocals(frame);
1894         PyObject *self_caller = PyDict_GetItem(
1895             frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
1896         if (self_caller == self.ptr())
1897             return function();
1898     }
1899 #else
1900     /* PyPy currently doesn't provide a detailed cpyext emulation of
1901        frame objects, so we have to emulate this using Python. This
1902        is going to be slow..*/
1903     dict d; d["self"] = self; d["name"] = pybind11::str(name);
1904     PyObject *result = PyRun_String(
1905         "import inspect\n"
1906         "frame = inspect.currentframe()\n"
1907         "if frame is not None:\n"
1908         "    frame = frame.f_back\n"
1909         "    if frame is not None and str(frame.f_code.co_name) == name and "
1910         "frame.f_code.co_argcount > 0:\n"
1911         "        self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
1912         "        if self_caller == self:\n"
1913         "            self = None\n",
1914         Py_file_input, d.ptr(), d.ptr());
1915     if (result == nullptr)
1916         throw error_already_set();
1917     if (d["self"].is_none())
1918         return function();
1919     Py_DECREF(result);
1920 #endif
1922     return overload;
1925 template <class T> function get_overload(const T *this_ptr, const char *name) {
1926     auto tinfo = detail::get_type_info(typeid(T));
1927     return tinfo ? get_type_overload(this_ptr, tinfo, name) : function();
1930 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
1931         pybind11::gil_scoped_acquire gil; \
1932         pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
1933         if (overload) { \
1934             auto o = overload(__VA_ARGS__); \
1935             if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
1936                 static pybind11::detail::overload_caster_t<ret_type> caster; \
1937                 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
1938             } \
1939             else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
1940         } \
1941     }
1943 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
1944     PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
1945     return cname::fn(__VA_ARGS__)
1947 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
1948     PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
1949     pybind11::pybind11_fail("Tried to call pure virtual function \"" #cname "::" name "\"");
1951 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
1952     PYBIND11_OVERLOAD_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
1954 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
1955     PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
1957 NAMESPACE_END(PYBIND11_NAMESPACE)
1959 #if defined(_MSC_VER)
1960 #  pragma warning(pop)
1961 #elif defined(__INTEL_COMPILER)
1962 /* Leave ignored warnings on */
1963 #elif defined(__GNUG__) && !defined(__clang__)
1964 #  pragma GCC diagnostic pop
1965 #endif