pybind11.h
Go to the documentation of this file.
1 /*
2  pybind11/pybind11.h: Main header file of the C++11 python
3  binding generator library
4 
5  Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6 
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 */
10 
11 #pragma once
12 
13 #include "detail/class.h"
14 #include "detail/init.h"
15 #include "attr.h"
16 #include "gil.h"
17 #include "options.h"
18 
19 #include <cstdlib>
20 #include <cstring>
21 #include <memory>
22 #include <new>
23 #include <string>
24 #include <utility>
25 #include <vector>
26 
27 #if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914))
28 # define PYBIND11_STD_LAUNDER std::launder
29 # define PYBIND11_HAS_STD_LAUNDER 1
30 #else
31 # define PYBIND11_STD_LAUNDER
32 # define PYBIND11_HAS_STD_LAUNDER 0
33 #endif
34 #if defined(__GNUG__) && !defined(__clang__)
35 # include <cxxabi.h>
36 #endif
37 
39 
40 /* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning
41  This warning is about ABI compatibility, not code health.
42  It is only actually needed in a couple places, but apparently GCC 7 "generates this warning if
43  and only if the first template instantiation ... involves noexcept" [stackoverflow], therefore
44  it could get triggered from seemingly random places, depending on user code.
45  No other GCC version generates this warning.
46  */
47 #if defined(__GNUC__) && __GNUC__ == 7
48 PYBIND11_WARNING_DISABLE_GCC("-Wnoexcept-type")
49 #endif
50 
52 
54 
55 // Apply all the extensions translators from a list
56 // Return true if one of the translators completed without raising an exception
57 // itself. Return of false indicates that if there are other translators
58 // available, they should be tried.
59 inline bool apply_exception_translators(std::forward_list<ExceptionTranslator> &translators) {
60  auto last_exception = std::current_exception();
61 
62  for (auto &translator : translators) {
63  try {
64  translator(last_exception);
65  return true;
66  } catch (...) {
67  last_exception = std::current_exception();
68  }
69  }
70  return false;
71 }
72 
73 #if defined(_MSC_VER)
74 # define PYBIND11_COMPAT_STRDUP _strdup
75 #else
76 # define PYBIND11_COMPAT_STRDUP strdup
77 #endif
78 
80 
81 class cpp_function : public function {
83 public:
84  cpp_function() = default;
85  // NOLINTNEXTLINE(google-explicit-constructor)
86  cpp_function(std::nullptr_t) {}
87  cpp_function(std::nullptr_t, const is_setter &) {}
88 
90  template <typename Return, typename... Args, typename... Extra>
91  // NOLINTNEXTLINE(google-explicit-constructor)
92  cpp_function(Return (*f)(Args...), const Extra &...extra) {
93  initialize(f, f, extra...);
94  }
95 
97  template <typename Func,
98  typename... Extra,
100  // NOLINTNEXTLINE(google-explicit-constructor)
101  cpp_function(Func &&f, const Extra &...extra) {
102  initialize(
103  std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...);
104  }
105 
107  template <typename Return, typename Class, typename... Arg, typename... Extra>
108  // NOLINTNEXTLINE(google-explicit-constructor)
109  cpp_function(Return (Class::*f)(Arg...), const Extra &...extra) {
110  initialize(
111  [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
112  (Return(*)(Class *, Arg...)) nullptr,
113  extra...);
114  }
115 
119  template <typename Return, typename Class, typename... Arg, typename... Extra>
120  // NOLINTNEXTLINE(google-explicit-constructor)
121  cpp_function(Return (Class::*f)(Arg...) &, const Extra &...extra) {
122  initialize(
123  [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
124  (Return(*)(Class *, Arg...)) nullptr,
125  extra...);
126  }
127 
129  template <typename Return, typename Class, typename... Arg, typename... Extra>
130  // NOLINTNEXTLINE(google-explicit-constructor)
131  cpp_function(Return (Class::*f)(Arg...) const, const Extra &...extra) {
132  initialize([f](const Class *c,
133  Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
134  (Return(*)(const Class *, Arg...)) nullptr,
135  extra...);
136  }
137 
141  template <typename Return, typename Class, typename... Arg, typename... Extra>
142  // NOLINTNEXTLINE(google-explicit-constructor)
143  cpp_function(Return (Class::*f)(Arg...) const &, const Extra &...extra) {
144  initialize([f](const Class *c,
145  Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
146  (Return(*)(const Class *, Arg...)) nullptr,
147  extra...);
148  }
149 
151  object name() const { return attr("__name__"); }
152 
153 protected:
155  // `destruct(function_record, false)`: `initialize_generic` copies strings and
156  // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`.
157  void operator()(detail::function_record *rec) { destruct(rec, false); }
158  };
160  = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
161 
164  return unique_function_record(new detail::function_record());
165  }
166 
168  template <typename Func, typename Return, typename... Args, typename... Extra>
169  void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) {
170  using namespace detail;
171  struct capture {
173  };
174 
175  /* Store the function including any extra state it might have (e.g. a lambda capture
176  * object) */
177  // The unique_ptr makes sure nothing is leaked in case of an exception.
178  auto unique_rec = make_function_record();
179  auto *rec = unique_rec.get();
180 
181  /* Store the capture object directly in the function record if there is enough space */
182  if (sizeof(capture) <= sizeof(rec->data)) {
183  /* Without these pragmas, GCC warns that there might not be
184  enough space to use the placement new operator. However, the
185  'if' statement above ensures that this is the case. */
186  PYBIND11_WARNING_PUSH
187 
188 #if defined(__GNUG__) && __GNUC__ >= 6
189  PYBIND11_WARNING_DISABLE_GCC("-Wplacement-new")
190 #endif
191 
192  new ((capture *) &rec->data) capture{std::forward<Func>(f)};
193 
194 #if !PYBIND11_HAS_STD_LAUNDER
195  PYBIND11_WARNING_DISABLE_GCC("-Wstrict-aliasing")
196 #endif
197 
198  // UB without std::launder, but without breaking ABI and/or
199  // a significant refactoring it's "impossible" to solve.
201  rec->free_data = [](function_record *r) {
202  auto data = PYBIND11_STD_LAUNDER((capture *) &r->data);
203  (void) data;
204  data->~capture();
205  };
206  }
208  } else {
209  rec->data[0] = new capture{std::forward<Func>(f)};
210  rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
211  }
212 
213  /* Type casters for the function arguments and return value */
214  using cast_in = argument_loader<Args...>;
215  using cast_out
217 
218  static_assert(
219  expected_num_args<Extra...>(
220  sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
221  "The number of argument annotations does not match the number of function arguments");
222 
223  /* Dispatch code which converts function arguments and performs the actual function call */
224  rec->impl = [](function_call &call) -> handle {
225  cast_in args_converter;
226 
227  /* Try to cast the function arguments into the C++ domain */
228  if (!args_converter.load_args(call)) {
230  }
231 
232  /* Invoke call policy pre-call hook */
234 
235  /* Get a pointer to the capture object */
236  const auto *data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data
237  : call.func.data[0]);
238  auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
239 
240  /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
241  return_value_policy policy
243 
244  /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
245  using Guard = extract_guard_t<Extra...>;
246 
247  /* Perform the function call */
248  handle result;
249  if (call.func.is_setter) {
250  (void) std::move(args_converter).template call<Return, Guard>(cap->f);
251  result = none().release();
252  } else {
254  std::move(args_converter).template call<Return, Guard>(cap->f),
255  policy,
256  call.parent);
257  }
258 
259  /* Invoke call policy post-call hook */
261 
262  return result;
263  };
264 
265  rec->nargs_pos = cast_in::args_pos >= 0
266  ? static_cast<std::uint16_t>(cast_in::args_pos)
267  : sizeof...(Args) - cast_in::has_kwargs; // Will get reduced more if
268  // we have a kw_only
269  rec->has_args = cast_in::args_pos >= 0;
270  rec->has_kwargs = cast_in::has_kwargs;
271 
272  /* Process any user-provided function attributes */
273  process_attributes<Extra...>::init(extra..., rec);
274 
275  {
276  constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
277  has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
278  has_arg_annotations = any_of<is_keyword<Extra>...>::value;
279  static_assert(has_arg_annotations || !has_kw_only_args,
280  "py::kw_only requires the use of argument annotations");
281  static_assert(has_arg_annotations || !has_pos_only_args,
282  "py::pos_only requires the use of argument annotations (for docstrings "
283  "and aligning the annotations to the argument)");
284 
285  static_assert(constexpr_sum(is_kw_only<Extra>::value...) <= 1,
286  "py::kw_only may be specified only once");
287  static_assert(constexpr_sum(is_pos_only<Extra>::value...) <= 1,
288  "py::pos_only may be specified only once");
289  constexpr auto kw_only_pos = constexpr_first<is_kw_only, Extra...>();
290  constexpr auto pos_only_pos = constexpr_first<is_pos_only, Extra...>();
291  static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
292  "py::pos_only must come before py::kw_only");
293  }
294 
295  /* Generate a readable signature describing the function's arguments and return
296  value types */
297  static constexpr auto signature
298  = const_name("(") + cast_in::arg_names + const_name(") -> ") + cast_out::name;
299  PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
300 
301  /* Register the function with Python from generic (non-templated) code */
302  // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid.
303  initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));
304 
305  /* Stash some additional information used by an important optimization in 'functional.h' */
306  using FunctionType = Return (*)(Args...);
307  constexpr bool is_function_ptr
308  = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *);
309  if (is_function_ptr) {
310  rec->is_stateless = true;
311  rec->data[1]
312  = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
313  }
314  }
315 
316  // Utility class that keeps track of all duplicated strings, and cleans them up in its
317  // destructor, unless they are released. Basically a RAII-solution to deal with exceptions
318  // along the way.
319  class strdup_guard {
320  public:
321  strdup_guard() = default;
322  strdup_guard(const strdup_guard &) = delete;
323  strdup_guard &operator=(const strdup_guard &) = delete;
324 
326  for (auto *s : strings) {
327  std::free(s);
328  }
329  }
330  char *operator()(const char *s) {
331  auto *t = PYBIND11_COMPAT_STRDUP(s);
332  strings.push_back(t);
333  return t;
334  }
335  void release() { strings.clear(); }
336 
337  private:
338  std::vector<char *> strings;
339  };
340 
343  const char *text,
344  const std::type_info *const *types,
345  size_t args) {
346  // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr,
347  // we do not want this to destruct the pointer. `initialize` (the caller) still relies on
348  // the pointee being alive after this call. Only move out if a `capsule` is going to keep
349  // it alive.
350  auto *rec = unique_rec.get();
351 
352  // Keep track of strdup'ed strings, and clean them up as long as the function's capsule
353  // has not taken ownership yet (when `unique_rec.release()` is called).
354  // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the
355  // strings are only referenced before strdup'ing. So only *after* the following block could
356  // `destruct` safely be called, but even then, `repr` could still throw in the middle of
357  // copying all strings.
358  strdup_guard guarded_strdup;
359 
360  /* Create copies of all referenced C-style strings */
361  rec->name = guarded_strdup(rec->name ? rec->name : "");
362  if (rec->doc) {
363  rec->doc = guarded_strdup(rec->doc);
364  }
365  for (auto &a : rec->args) {
366  if (a.name) {
367  a.name = guarded_strdup(a.name);
368  }
369  if (a.descr) {
370  a.descr = guarded_strdup(a.descr);
371  } else if (a.value) {
372  a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());
373  }
374  }
375 
376  rec->is_constructor = (std::strcmp(rec->name, "__init__") == 0)
377  || (std::strcmp(rec->name, "__setstate__") == 0);
378 
379 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
380  if (rec->is_constructor && !rec->is_new_style_constructor) {
381  const auto class_name
382  = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
383  const auto func_name = std::string(rec->name);
384  PyErr_WarnEx(PyExc_FutureWarning,
385  ("pybind11-bound class '" + class_name
386  + "' is using an old-style "
387  "placement-new '"
388  + func_name
389  + "' which has been deprecated. See "
390  "the upgrade guide in pybind11's docs. This message is only visible "
391  "when compiled in debug mode.")
392  .c_str(),
393  0);
394  }
395 #endif
396 
397  /* Generate a proper function signature */
398  std::string signature;
399  size_t type_index = 0, arg_index = 0;
400  bool is_starred = false;
401  for (const auto *pc = text; *pc != '\0'; ++pc) {
402  const auto c = *pc;
403 
404  if (c == '{') {
405  // Write arg name for everything except *args and **kwargs.
406  is_starred = *(pc + 1) == '*';
407  if (is_starred) {
408  continue;
409  }
410  // Separator for keyword-only arguments, placed before the kw
411  // arguments start (unless we are already putting an *args)
412  if (!rec->has_args && arg_index == rec->nargs_pos) {
413  signature += "*, ";
414  }
415  if (arg_index < rec->args.size() && rec->args[arg_index].name) {
416  signature += rec->args[arg_index].name;
417  } else if (arg_index == 0 && rec->is_method) {
418  signature += "self";
419  } else {
420  signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
421  }
422  signature += ": ";
423  } else if (c == '}') {
424  // Write default value if available.
425  if (!is_starred && arg_index < rec->args.size() && rec->args[arg_index].descr) {
426  signature += " = ";
427  signature += rec->args[arg_index].descr;
428  }
429  // Separator for positional-only arguments (placed after the
430  // argument, rather than before like *
431  if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
432  signature += ", /";
433  }
434  if (!is_starred) {
435  arg_index++;
436  }
437  } else if (c == '%') {
438  const std::type_info *t = types[type_index++];
439  if (!t) {
440  pybind11_fail("Internal error while parsing type signature (1)");
441  }
442  if (auto *tinfo = detail::get_type_info(*t)) {
443  handle th((PyObject *) tinfo->type);
444  signature += th.attr("__module__").cast<std::string>() + "."
445  + th.attr("__qualname__").cast<std::string>();
446  } else if (rec->is_new_style_constructor && arg_index == 0) {
447  // A new-style `__init__` takes `self` as `value_and_holder`.
448  // Rewrite it to the proper class type.
449  signature += rec->scope.attr("__module__").cast<std::string>() + "."
450  + rec->scope.attr("__qualname__").cast<std::string>();
451  } else {
452  std::string tname(t->name());
453  detail::clean_type_id(tname);
454  signature += tname;
455  }
456  } else {
457  signature += c;
458  }
459  }
460 
461  if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] != nullptr) {
462  pybind11_fail("Internal error while parsing type signature (2)");
463  }
464 
465  rec->signature = guarded_strdup(signature.c_str());
466  rec->args.shrink_to_fit();
467  rec->nargs = (std::uint16_t) args;
468 
469  if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) {
470  rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
471  }
472 
473  detail::function_record *chain = nullptr, *chain_start = rec;
474  if (rec->sibling) {
475  if (PyCFunction_Check(rec->sibling.ptr())) {
476  auto *self = PyCFunction_GET_SELF(rec->sibling.ptr());
477  if (!isinstance<capsule>(self)) {
478  chain = nullptr;
479  } else {
480  auto rec_capsule = reinterpret_borrow<capsule>(self);
481  if (detail::is_function_record_capsule(rec_capsule)) {
482  chain = rec_capsule.get_pointer<detail::function_record>();
483  /* Never append a method to an overload chain of a parent class;
484  instead, hide the parent's overloads in this case */
485  if (!chain->scope.is(rec->scope)) {
486  chain = nullptr;
487  }
488  } else {
489  chain = nullptr;
490  }
491  }
492  }
493  // Don't trigger for things like the default __init__, which are wrapper_descriptors
494  // that we are intentionally replacing
495  else if (!rec->sibling.is_none() && rec->name[0] != '_') {
496  pybind11_fail("Cannot overload existing non-function object \""
497  + std::string(rec->name) + "\" with a function of the same name");
498  }
499  }
500 
501  if (!chain) {
502  /* No existing overload was found, create a new function object */
503  rec->def = new PyMethodDef();
504  std::memset(rec->def, 0, sizeof(PyMethodDef));
505  rec->def->ml_name = rec->name;
506  rec->def->ml_meth
507  = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher));
508  rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
509 
510  capsule rec_capsule(unique_rec.release(),
512  [](void *ptr) { destruct((detail::function_record *) ptr); });
513  guarded_strdup.release();
514 
515  object scope_module;
516  if (rec->scope) {
517  if (hasattr(rec->scope, "__module__")) {
518  scope_module = rec->scope.attr("__module__");
519  } else if (hasattr(rec->scope, "__name__")) {
520  scope_module = rec->scope.attr("__name__");
521  }
522  }
523 
524  m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
525  if (!m_ptr) {
526  pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
527  }
528  } else {
529  /* Append at the beginning or end of the overload chain */
530  m_ptr = rec->sibling.ptr();
531  inc_ref();
532  if (chain->is_method != rec->is_method) {
534  "overloading a method with both static and instance methods is not supported; "
536  "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more "
537  "details"
538 #else
539  "error while attempting to bind "
540  + std::string(rec->is_method ? "instance" : "static") + " method "
541  + std::string(pybind11::str(rec->scope.attr("__name__"))) + "."
542  + std::string(rec->name) + signature
543 #endif
544  );
545  }
546 
547  if (rec->prepend) {
548  // Beginning of chain; we need to replace the capsule's current head-of-the-chain
549  // pointer with this one, then make this one point to the previous head of the
550  // chain.
551  chain_start = rec;
552  rec->next = chain;
553  auto rec_capsule
554  = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self);
555  rec_capsule.set_pointer(unique_rec.release());
556  guarded_strdup.release();
557  } else {
558  // Or end of chain (normal behavior)
559  chain_start = chain;
560  while (chain->next) {
561  chain = chain->next;
562  }
563  chain->next = unique_rec.release();
564  guarded_strdup.release();
565  }
566  }
567 
568  std::string signatures;
569  int index = 0;
570  /* Create a nice pydoc rec including all signatures and
571  docstrings of the functions in the overload chain */
572  if (chain && options::show_function_signatures()) {
573  // First a generic signature
574  signatures += rec->name;
575  signatures += "(*args, **kwargs)\n";
576  signatures += "Overloaded function.\n\n";
577  }
578  // Then specific overload signatures
579  bool first_user_def = true;
580  for (auto *it = chain_start; it != nullptr; it = it->next) {
582  if (index > 0) {
583  signatures += '\n';
584  }
585  if (chain) {
586  signatures += std::to_string(++index) + ". ";
587  }
588  signatures += rec->name;
589  signatures += it->signature;
590  signatures += '\n';
591  }
592  if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) {
593  // If we're appending another docstring, and aren't printing function signatures,
594  // we need to append a newline first:
596  if (first_user_def) {
597  first_user_def = false;
598  } else {
599  signatures += '\n';
600  }
601  }
603  signatures += '\n';
604  }
605  signatures += it->doc;
607  signatures += '\n';
608  }
609  }
610  }
611 
612  /* Install docstring */
613  auto *func = (PyCFunctionObject *) m_ptr;
614  std::free(const_cast<char *>(func->m_ml->ml_doc));
615  // Install docstring if it's non-empty (when at least one option is enabled)
616  func->m_ml->ml_doc
617  = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());
618 
619  if (rec->is_method) {
620  m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
621  if (!m_ptr) {
623  "cpp_function::cpp_function(): Could not allocate instance method object");
624  }
625  Py_DECREF(func);
626  }
627  }
628 
630  static void destruct(detail::function_record *rec, bool free_strings = true) {
631 // If on Python 3.9, check the interpreter "MICRO" (patch) version.
632 // If this is running on 3.9.0, we have to work around a bug.
633 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
634  static bool is_zero = Py_GetVersion()[4] == '0';
635 #endif
636 
637  while (rec) {
638  detail::function_record *next = rec->next;
639  if (rec->free_data) {
640  rec->free_data(rec);
641  }
642  // During initialization, these strings might not have been copied yet,
643  // so they cannot be freed. Once the function has been created, they can.
644  // Check `make_function_record` for more details.
645  if (free_strings) {
646  std::free((char *) rec->name);
647  std::free((char *) rec->doc);
648  std::free((char *) rec->signature);
649  for (auto &arg : rec->args) {
650  std::free(const_cast<char *>(arg.name));
651  std::free(const_cast<char *>(arg.descr));
652  }
653  }
654  for (auto &arg : rec->args) {
655  arg.value.dec_ref();
656  }
657  if (rec->def) {
658  std::free(const_cast<char *>(rec->def->ml_doc));
659 // Python 3.9.0 decref's these in the wrong order; rec->def
660 // If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)
661 // See https://github.com/python/cpython/pull/22670
662 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
663  if (!is_zero) {
664  delete rec->def;
665  }
666 #else
667  delete rec->def;
668 #endif
669  }
670  delete rec;
671  rec = next;
672  }
673  }
674 
676  static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
677  using namespace detail;
678  assert(isinstance<capsule>(self));
679 
680  /* Iterator over the list of potentially admissible overloads */
681  const function_record *overloads = reinterpret_cast<function_record *>(
682  PyCapsule_GetPointer(self, get_function_record_capsule_name())),
683  *it = overloads;
684  assert(overloads != nullptr);
685 
686  /* Need to know how many arguments + keyword arguments there are to pick the right
687  overload */
688  const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
689 
690  handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
692 
693  auto self_value_and_holder = value_and_holder();
694  if (overloads->is_constructor) {
695  if (!parent
696  || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
697  PyErr_SetString(
698  PyExc_TypeError,
699  "__init__(self, ...) called with invalid or missing `self` argument");
700  return nullptr;
701  }
702 
703  auto *const tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
704  auto *const pi = reinterpret_cast<instance *>(parent.ptr());
705  self_value_and_holder = pi->get_value_and_holder(tinfo, true);
706 
707  // If this value is already registered it must mean __init__ is invoked multiple times;
708  // we really can't support that in C++, so just ignore the second __init__.
709  if (self_value_and_holder.instance_registered()) {
710  return none().release().ptr();
711  }
712  }
713 
714  try {
715  // We do this in two passes: in the first pass, we load arguments with `convert=false`;
716  // in the second, we allow conversion (except for arguments with an explicit
717  // py::arg().noconvert()). This lets us prefer calls without conversion, with
718  // conversion as a fallback.
719  std::vector<function_call> second_pass;
720 
721  // However, if there are no overloads, we can just skip the no-convert pass entirely
722  const bool overloaded = it != nullptr && it->next != nullptr;
723 
724  for (; it != nullptr; it = it->next) {
725 
726  /* For each overload:
727  1. Copy all positional arguments we were given, also checking to make sure that
728  named positional arguments weren't *also* specified via kwarg.
729  2. If we weren't given enough, try to make up the omitted ones by checking
730  whether they were provided by a kwarg matching the `py::arg("name")` name. If
731  so, use it (and remove it from kwargs); if not, see if the function binding
732  provided a default that we can use.
733  3. Ensure that either all keyword arguments were "consumed", or that the
734  function takes a kwargs argument to accept unconsumed kwargs.
735  4. Any positional arguments still left get put into a tuple (for args), and any
736  leftover kwargs get put into a dict.
737  5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
738  extra tuple or dict at the end of the positional arguments.
739  6. Call the function call dispatcher (function_record::impl)
740 
741  If one of these fail, move on to the next overload and keep trying until we get
742  a result other than PYBIND11_TRY_NEXT_OVERLOAD.
743  */
744 
745  const function_record &func = *it;
746  size_t num_args = func.nargs; // Number of positional arguments that we need
747  if (func.has_args) {
748  --num_args; // (but don't count py::args
749  }
750  if (func.has_kwargs) {
751  --num_args; // or py::kwargs)
752  }
753  size_t pos_args = func.nargs_pos;
754 
755  if (!func.has_args && n_args_in > pos_args) {
756  continue; // Too many positional arguments for this overload
757  }
758 
759  if (n_args_in < pos_args && func.args.size() < pos_args) {
760  continue; // Not enough positional arguments given, and not enough defaults to
761  // fill in the blanks
762  }
763 
764  function_call call(func, parent);
765 
766  // Protect std::min with parentheses
767  size_t args_to_copy = (std::min)(pos_args, n_args_in);
768  size_t args_copied = 0;
769 
770  // 0. Inject new-style `self` argument
771  if (func.is_new_style_constructor) {
772  // The `value` may have been preallocated by an old-style `__init__`
773  // if it was a preceding candidate for overload resolution.
774  if (self_value_and_holder) {
775  self_value_and_holder.type->dealloc(self_value_and_holder);
776  }
777 
778  call.init_self = PyTuple_GET_ITEM(args_in, 0);
779  call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
780  call.args_convert.push_back(false);
781  ++args_copied;
782  }
783 
784  // 1. Copy any position arguments given.
785  bool bad_arg = false;
786  for (; args_copied < args_to_copy; ++args_copied) {
787  const argument_record *arg_rec
788  = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
789  if (kwargs_in && arg_rec && arg_rec->name
790  && dict_getitemstring(kwargs_in, arg_rec->name)) {
791  bad_arg = true;
792  break;
793  }
794 
795  handle arg(PyTuple_GET_ITEM(args_in, args_copied));
796  if (arg_rec && !arg_rec->none && arg.is_none()) {
797  bad_arg = true;
798  break;
799  }
800  call.args.push_back(arg);
801  call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
802  }
803  if (bad_arg) {
804  continue; // Maybe it was meant for another overload (issue #688)
805  }
806 
807  // Keep track of how many position args we copied out in case we need to come back
808  // to copy the rest into a py::args argument.
809  size_t positional_args_copied = args_copied;
810 
811  // We'll need to copy this if we steal some kwargs for defaults
812  dict kwargs = reinterpret_borrow<dict>(kwargs_in);
813 
814  // 1.5. Fill in any missing pos_only args from defaults if they exist
815  if (args_copied < func.nargs_pos_only) {
816  for (; args_copied < func.nargs_pos_only; ++args_copied) {
817  const auto &arg_rec = func.args[args_copied];
818  handle value;
819 
820  if (arg_rec.value) {
821  value = arg_rec.value;
822  }
823  if (value) {
824  call.args.push_back(value);
825  call.args_convert.push_back(arg_rec.convert);
826  } else {
827  break;
828  }
829  }
830 
831  if (args_copied < func.nargs_pos_only) {
832  continue; // Not enough defaults to fill the positional arguments
833  }
834  }
835 
836  // 2. Check kwargs and, failing that, defaults that may help complete the list
837  if (args_copied < num_args) {
838  bool copied_kwargs = false;
839 
840  for (; args_copied < num_args; ++args_copied) {
841  const auto &arg_rec = func.args[args_copied];
842 
843  handle value;
844  if (kwargs_in && arg_rec.name) {
845  value = dict_getitemstring(kwargs.ptr(), arg_rec.name);
846  }
847 
848  if (value) {
849  // Consume a kwargs value
850  if (!copied_kwargs) {
851  kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
852  copied_kwargs = true;
853  }
854  if (PyDict_DelItemString(kwargs.ptr(), arg_rec.name) == -1) {
855  throw error_already_set();
856  }
857  } else if (arg_rec.value) {
858  value = arg_rec.value;
859  }
860 
861  if (!arg_rec.none && value.is_none()) {
862  break;
863  }
864 
865  if (value) {
866  // If we're at the py::args index then first insert a stub for it to be
867  // replaced later
868  if (func.has_args && call.args.size() == func.nargs_pos) {
869  call.args.push_back(none());
870  }
871 
872  call.args.push_back(value);
873  call.args_convert.push_back(arg_rec.convert);
874  } else {
875  break;
876  }
877  }
878 
879  if (args_copied < num_args) {
880  continue; // Not enough arguments, defaults, or kwargs to fill the
881  // positional arguments
882  }
883  }
884 
885  // 3. Check everything was consumed (unless we have a kwargs arg)
886  if (kwargs && !kwargs.empty() && !func.has_kwargs) {
887  continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
888  }
889 
890  // 4a. If we have a py::args argument, create a new tuple with leftovers
891  if (func.has_args) {
892  tuple extra_args;
893  if (args_to_copy == 0) {
894  // We didn't copy out any position arguments from the args_in tuple, so we
895  // can reuse it directly without copying:
896  extra_args = reinterpret_borrow<tuple>(args_in);
897  } else if (positional_args_copied >= n_args_in) {
898  extra_args = tuple(0);
899  } else {
900  size_t args_size = n_args_in - positional_args_copied;
901  extra_args = tuple(args_size);
902  for (size_t i = 0; i < args_size; ++i) {
903  extra_args[i] = PyTuple_GET_ITEM(args_in, positional_args_copied + i);
904  }
905  }
906  if (call.args.size() <= func.nargs_pos) {
907  call.args.push_back(extra_args);
908  } else {
909  call.args[func.nargs_pos] = extra_args;
910  }
911  call.args_convert.push_back(false);
912  call.args_ref = std::move(extra_args);
913  }
914 
915  // 4b. If we have a py::kwargs, pass on any remaining kwargs
916  if (func.has_kwargs) {
917  if (!kwargs.ptr()) {
918  kwargs = dict(); // If we didn't get one, send an empty one
919  }
920  call.args.push_back(kwargs);
921  call.args_convert.push_back(false);
922  call.kwargs_ref = std::move(kwargs);
923  }
924 
925 // 5. Put everything in a vector. Not technically step 5, we've been building it
926 // in `call.args` all along.
927 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
928  if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) {
929  pybind11_fail("Internal error: function call dispatcher inserted wrong number "
930  "of arguments!");
931  }
932 #endif
933 
934  std::vector<bool> second_pass_convert;
935  if (overloaded) {
936  // We're in the first no-convert pass, so swap out the conversion flags for a
937  // set of all-false flags. If the call fails, we'll swap the flags back in for
938  // the conversion-allowed call below.
939  second_pass_convert.resize(func.nargs, false);
940  call.args_convert.swap(second_pass_convert);
941  }
942 
943  // 6. Call the function.
944  try {
945  loader_life_support guard{};
946  result = func.impl(call);
947  } catch (reference_cast_error &) {
949  }
950 
951  if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
952  break;
953  }
954 
955  if (overloaded) {
956  // The (overloaded) call failed; if the call has at least one argument that
957  // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
958  // then add this call to the list of second pass overloads to try.
959  for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
960  if (second_pass_convert[i]) {
961  // Found one: swap the converting flags back in and store the call for
962  // the second pass.
963  call.args_convert.swap(second_pass_convert);
964  second_pass.push_back(std::move(call));
965  break;
966  }
967  }
968  }
969  }
970 
971  if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
972  // The no-conversion pass finished without success, try again with conversion
973  // allowed
974  for (auto &call : second_pass) {
975  try {
976  loader_life_support guard{};
977  result = call.func.impl(call);
978  } catch (reference_cast_error &) {
980  }
981 
982  if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
983  // The error reporting logic below expects 'it' to be valid, as it would be
984  // if we'd encountered this failure in the first-pass loop.
985  if (!result) {
986  it = &call.func;
987  }
988  break;
989  }
990  }
991  }
992  } catch (error_already_set &e) {
993  e.restore();
994  return nullptr;
995 #ifdef __GLIBCXX__
996  } catch (abi::__forced_unwind &) {
997  throw;
998 #endif
999  } catch (...) {
1000  /* When an exception is caught, give each registered exception
1001  translator a chance to translate it to a Python exception. First
1002  all module-local translators will be tried in reverse order of
1003  registration. If none of the module-locale translators handle
1004  the exception (or there are no module-locale translators) then
1005  the global translators will be tried, also in reverse order of
1006  registration.
1007 
1008  A translator may choose to do one of the following:
1009 
1010  - catch the exception and call PyErr_SetString or PyErr_SetObject
1011  to set a standard (or custom) Python exception, or
1012  - do nothing and let the exception fall through to the next translator, or
1013  - delegate translation to the next translator by throwing a new type of exception.
1014  */
1015 
1016  auto &local_exception_translators
1018  if (detail::apply_exception_translators(local_exception_translators)) {
1019  return nullptr;
1020  }
1021  auto &exception_translators = get_internals().registered_exception_translators;
1022  if (detail::apply_exception_translators(exception_translators)) {
1023  return nullptr;
1024  }
1025 
1026  PyErr_SetString(PyExc_SystemError,
1027  "Exception escaped from default exception translator!");
1028  return nullptr;
1029  }
1030 
1031  auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
1032  if (msg.find("std::") != std::string::npos) {
1033  msg += "\n\n"
1034  "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1035  "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1036  "conversions are optional and require extra headers to be included\n"
1037  "when compiling your pybind11 module.";
1038  }
1039  };
1040 
1041  if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
1042  if (overloads->is_operator) {
1043  return handle(Py_NotImplemented).inc_ref().ptr();
1044  }
1045 
1046  std::string msg = std::string(overloads->name) + "(): incompatible "
1047  + std::string(overloads->is_constructor ? "constructor" : "function")
1048  + " arguments. The following argument types are supported:\n";
1049 
1050  int ctr = 0;
1051  for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
1052  msg += " " + std::to_string(++ctr) + ". ";
1053 
1054  bool wrote_sig = false;
1055  if (overloads->is_constructor) {
1056  // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as
1057  // `Object(arg0, ...)`
1058  std::string sig = it2->signature;
1059  size_t start = sig.find('(') + 7; // skip "(self: "
1060  if (start < sig.size()) {
1061  // End at the , for the next argument
1062  size_t end = sig.find(", "), next = end + 2;
1063  size_t ret = sig.rfind(" -> ");
1064  // Or the ), if there is no comma:
1065  if (end >= sig.size()) {
1066  next = end = sig.find(')');
1067  }
1068  if (start < end && next < sig.size()) {
1069  msg.append(sig, start, end - start);
1070  msg += '(';
1071  msg.append(sig, next, ret - next);
1072  wrote_sig = true;
1073  }
1074  }
1075  }
1076  if (!wrote_sig) {
1077  msg += it2->signature;
1078  }
1079 
1080  msg += '\n';
1081  }
1082  msg += "\nInvoked with: ";
1083  auto args_ = reinterpret_borrow<tuple>(args_in);
1084  bool some_args = false;
1085  for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
1086  if (!some_args) {
1087  some_args = true;
1088  } else {
1089  msg += ", ";
1090  }
1091  try {
1092  msg += pybind11::repr(args_[ti]);
1093  } catch (const error_already_set &) {
1094  msg += "<repr raised Error>";
1095  }
1096  }
1097  if (kwargs_in) {
1098  auto kwargs = reinterpret_borrow<dict>(kwargs_in);
1099  if (!kwargs.empty()) {
1100  if (some_args) {
1101  msg += "; ";
1102  }
1103  msg += "kwargs: ";
1104  bool first = true;
1105  for (auto kwarg : kwargs) {
1106  if (first) {
1107  first = false;
1108  } else {
1109  msg += ", ";
1110  }
1111  msg += pybind11::str("{}=").format(kwarg.first);
1112  try {
1113  msg += pybind11::repr(kwarg.second);
1114  } catch (const error_already_set &) {
1115  msg += "<repr raised Error>";
1116  }
1117  }
1118  }
1119  }
1120 
1121  append_note_if_missing_header_is_suspected(msg);
1122  // Attach additional error info to the exception if supported
1123  if (PyErr_Occurred()) {
1124  // #HelpAppreciated: unit test coverage for this branch.
1125  raise_from(PyExc_TypeError, msg.c_str());
1126  return nullptr;
1127  }
1128  PyErr_SetString(PyExc_TypeError, msg.c_str());
1129  return nullptr;
1130  }
1131  if (!result) {
1132  std::string msg = "Unable to convert function return value to a "
1133  "Python type! The signature was\n\t";
1134  msg += it->signature;
1135  append_note_if_missing_header_is_suspected(msg);
1136  // Attach additional error info to the exception if supported
1137  if (PyErr_Occurred()) {
1138  raise_from(PyExc_TypeError, msg.c_str());
1139  return nullptr;
1140  }
1141  PyErr_SetString(PyExc_TypeError, msg.c_str());
1142  return nullptr;
1143  }
1144  if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
1145  auto *pi = reinterpret_cast<instance *>(parent.ptr());
1146  self_value_and_holder.type->init_instance(pi, nullptr);
1147  }
1148  return result.ptr();
1149  }
1150 };
1151 
1153 class module_ : public object {
1154 public:
1155  PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)
1156 
1157 
1158  PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead")
1159  explicit module_(const char *name, const char *doc = nullptr) {
1160  *this = create_extension_module(name, doc, new PyModuleDef());
1161  }
1162 
1168  template <typename Func, typename... Extra>
1169  module_ &def(const char *name_, Func &&f, const Extra &...extra) {
1170  cpp_function func(std::forward<Func>(f),
1171  name(name_),
1172  scope(*this),
1173  sibling(getattr(*this, name_, none())),
1174  extra...);
1175  // NB: allow overwriting here because cpp_function sets up a chain with the intention of
1176  // overwriting (and has already checked internally that it isn't overwriting
1177  // non-functions).
1178  add_object(name_, func, true /* overwrite */);
1179  return *this;
1180  }
1181 
1192  module_ def_submodule(const char *name, const char *doc = nullptr) {
1193  const char *this_name = PyModule_GetName(m_ptr);
1194  if (this_name == nullptr) {
1195  throw error_already_set();
1196  }
1197  std::string full_name = std::string(this_name) + '.' + name;
1198  handle submodule = PyImport_AddModule(full_name.c_str());
1199  if (!submodule) {
1200  throw error_already_set();
1201  }
1202  auto result = reinterpret_borrow<module_>(submodule);
1204  result.attr("__doc__") = pybind11::str(doc);
1205  }
1206  attr(name) = result;
1207  return result;
1208  }
1209 
1211  static module_ import(const char *name) {
1212  PyObject *obj = PyImport_ImportModule(name);
1213  if (!obj) {
1214  throw error_already_set();
1215  }
1216  return reinterpret_steal<module_>(obj);
1217  }
1218 
1220  void reload() {
1221  PyObject *obj = PyImport_ReloadModule(ptr());
1222  if (!obj) {
1223  throw error_already_set();
1224  }
1225  *this = reinterpret_steal<module_>(obj);
1226  }
1227 
1235  PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
1236  if (!overwrite && hasattr(*this, name)) {
1237  pybind11_fail(
1238  "Error during initialization: multiple incompatible definitions with name \""
1239  + std::string(name) + "\"");
1240  }
1241 
1242  PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
1243  }
1244 
1245  using module_def = PyModuleDef; // TODO: Can this be removed (it was needed only for Python 2)?
1246 
1252  static module_ create_extension_module(const char *name, const char *doc, module_def *def) {
1253  // module_def is PyModuleDef
1254  // Placement new (not an allocation).
1255  def = new (def)
1256  PyModuleDef{/* m_base */ PyModuleDef_HEAD_INIT,
1257  /* m_name */ name,
1258  /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr,
1259  /* m_size */ -1,
1260  /* m_methods */ nullptr,
1261  /* m_slots */ nullptr,
1262  /* m_traverse */ nullptr,
1263  /* m_clear */ nullptr,
1264  /* m_free */ nullptr};
1265  auto *m = PyModule_Create(def);
1266  if (m == nullptr) {
1267  if (PyErr_Occurred()) {
1268  throw error_already_set();
1269  }
1270  pybind11_fail("Internal error in module_::create_extension_module()");
1271  }
1272  // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when
1273  // returned from PyInit_...
1274  // For Python 2, reinterpret_borrow was correct.
1275  return reinterpret_borrow<module_>(m);
1276  }
1277 };
1278 
1279 // When inside a namespace (or anywhere as long as it's not the first item on a line),
1280 // C++20 allows "module" to be used. This is provided for backward compatibility, and for
1281 // simplicity, if someone wants to use py::module for example, that is perfectly safe.
1282 using module = module_;
1283 
1287 inline dict globals() {
1288  PyObject *p = PyEval_GetGlobals();
1289  return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
1290 }
1291 
1292 template <typename... Args, typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>>
1293 PYBIND11_DEPRECATED("make_simple_namespace should be replaced with "
1294  "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
1295 object make_simple_namespace(Args &&...args_) {
1296  return module_::import("types").attr("SimpleNamespace")(std::forward<Args>(args_)...);
1297 }
1298 
1301 class generic_type : public object {
1302 public:
1303  PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
1304 protected:
1305  void initialize(const type_record &rec) {
1306  if (rec.scope && hasattr(rec.scope, "__dict__")
1307  && rec.scope.attr("__dict__").contains(rec.name)) {
1308  pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name)
1309  + "\": an object with that name is already defined");
1310  }
1311 
1313  != nullptr) {
1314  pybind11_fail("generic_type: type \"" + std::string(rec.name)
1315  + "\" is already registered!");
1316  }
1317 
1318  m_ptr = make_new_python_type(rec);
1319 
1320  /* Register supplemental type information in C++ dict */
1321  auto *tinfo = new detail::type_info();
1322  tinfo->type = (PyTypeObject *) m_ptr;
1323  tinfo->cpptype = rec.type;
1324  tinfo->type_size = rec.type_size;
1325  tinfo->type_align = rec.type_align;
1326  tinfo->operator_new = rec.operator_new;
1327  tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
1328  tinfo->init_instance = rec.init_instance;
1329  tinfo->dealloc = rec.dealloc;
1330  tinfo->simple_type = true;
1331  tinfo->simple_ancestors = true;
1332  tinfo->default_holder = rec.default_holder;
1333  tinfo->module_local = rec.module_local;
1334 
1335  auto &internals = get_internals();
1336  auto tindex = std::type_index(*rec.type);
1337  tinfo->direct_conversions = &internals.direct_conversions[tindex];
1338  if (rec.module_local) {
1339  get_local_internals().registered_types_cpp[tindex] = tinfo;
1340  } else {
1341  internals.registered_types_cpp[tindex] = tinfo;
1342  }
1343  internals.registered_types_py[(PyTypeObject *) m_ptr] = {tinfo};
1344 
1345  if (rec.bases.size() > 1 || rec.multiple_inheritance) {
1346  mark_parents_nonsimple(tinfo->type);
1347  tinfo->simple_ancestors = false;
1348  } else if (rec.bases.size() == 1) {
1349  auto *parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
1350  assert(parent_tinfo != nullptr);
1351  bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1352  tinfo->simple_ancestors = parent_simple_ancestors;
1353  // The parent can no longer be a simple type if it has MI and has a child
1354  parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1355  }
1356 
1357  if (rec.module_local) {
1358  // Stash the local typeinfo and loader so that external modules can access it.
1359  tinfo->module_local_load = &type_caster_generic::local_load;
1361  }
1362  }
1363 
1365  void mark_parents_nonsimple(PyTypeObject *value) {
1366  auto t = reinterpret_borrow<tuple>(value->tp_bases);
1367  for (handle h : t) {
1368  auto *tinfo2 = get_type_info((PyTypeObject *) h.ptr());
1369  if (tinfo2) {
1370  tinfo2->simple_type = false;
1371  }
1372  mark_parents_nonsimple((PyTypeObject *) h.ptr());
1373  }
1374  }
1375 
1376  void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *),
1377  void *get_buffer_data) {
1378  auto *type = (PyHeapTypeObject *) m_ptr;
1379  auto *tinfo = detail::get_type_info(&type->ht_type);
1380 
1381  if (!type->ht_type.tp_as_buffer) {
1382  pybind11_fail("To be able to register buffer protocol support for the type '"
1383  + get_fully_qualified_tp_name(tinfo->type)
1384  + "' the associated class<>(..) invocation must "
1385  "include the pybind11::buffer_protocol() annotation!");
1386  }
1387 
1388  tinfo->get_buffer = get_buffer;
1389  tinfo->get_buffer_data = get_buffer_data;
1390  }
1391 
1392  // rec_func must be set for either fget or fset.
1393  void def_property_static_impl(const char *name,
1394  handle fget,
1395  handle fset,
1396  detail::function_record *rec_func) {
1397  const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);
1398  const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)
1399  && pybind11::options::show_user_defined_docstrings();
1400  auto property = handle(
1401  (PyObject *) (is_static ? get_internals().static_property_type : &PyProperty_Type));
1402  attr(name) = property(fget.ptr() ? fget : none(),
1403  fset.ptr() ? fset : none(),
1404  /*deleter*/ none(),
1405  pybind11::str(has_doc ? rec_func->doc : ""));
1406  }
1407 };
1408 
1410 template <typename T,
1411  typename = void_t<decltype(static_cast<void *(*) (size_t)>(T::operator new))>>
1413  r->operator_new = &T::operator new;
1414 }
1415 
1416 template <typename>
1417 void set_operator_new(...) {}
1418 
1419 template <typename T, typename SFINAE = void>
1420 struct has_operator_delete : std::false_type {};
1421 template <typename T>
1423  : std::true_type {};
1424 template <typename T, typename SFINAE = void>
1425 struct has_operator_delete_size : std::false_type {};
1426 template <typename T>
1428  T,
1429  void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type {
1430 };
1433 void call_operator_delete(T *p, size_t, size_t) {
1434  T::operator delete(p);
1435 }
1436 template <typename T,
1438  = 0>
1439 void call_operator_delete(T *p, size_t s, size_t) {
1440  T::operator delete(p, s);
1441 }
1442 
1443 inline void call_operator_delete(void *p, size_t s, size_t a) {
1444  (void) s;
1445  (void) a;
1446 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1447  if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1448 # ifdef __cpp_sized_deallocation
1449  ::operator delete(p, s, std::align_val_t(a));
1450 # else
1451  ::operator delete(p, std::align_val_t(a));
1452 # endif
1453  return;
1454  }
1455 #endif
1456 #ifdef __cpp_sized_deallocation
1457  ::operator delete(p, s);
1458 #else
1459  ::operator delete(p);
1460 #endif
1461 }
1462 
1463 inline void add_class_method(object &cls, const char *name_, const cpp_function &cf) {
1464  cls.attr(cf.name()) = cf;
1465  if (std::strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) {
1466  cls.attr("__hash__") = none();
1467  }
1468 }
1469 
1471 
1472 template <typename /*Derived*/, typename F>
1475 auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
1476  return std::forward<F>(f);
1477 }
1478 
1479 template <typename Derived, typename Return, typename Class, typename... Args>
1480 auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
1481  static_assert(
1483  "Cannot bind an inaccessible base class method; use a lambda definition instead");
1484  return pmf;
1485 }
1486 
1487 template <typename Derived, typename Return, typename Class, typename... Args>
1488 auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
1489  static_assert(
1491  "Cannot bind an inaccessible base class method; use a lambda definition instead");
1492  return pmf;
1493 }
1494 
1495 template <typename type_, typename... options>
1496 class class_ : public detail::generic_type {
1497  template <typename T>
1498  using is_holder = detail::is_holder_type<type_, T>;
1499  template <typename T>
1500  using is_subtype = detail::is_strict_base_of<type_, T>;
1501  template <typename T>
1502  using is_base = detail::is_strict_base_of<T, type_>;
1503  // struct instead of using here to help MSVC:
1504  template <typename T>
1505  struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
1506 
1507 public:
1508  using type = type_;
1510  constexpr static bool has_alias = !std::is_void<type_alias>::value;
1511  using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
1512 
1513  static_assert(detail::all_of<is_valid_class_option<options>...>::value,
1514  "Unknown/invalid class_ template parameters provided");
1515 
1516  static_assert(!has_alias || std::is_polymorphic<type>::value,
1517  "Cannot use an alias class with a non-polymorphic type");
1518 
1519  PYBIND11_OBJECT(class_, generic_type, PyType_Check)
1520 
1521  template <typename... Extra>
1522  class_(handle scope, const char *name, const Extra &...extra) {
1523  using namespace detail;
1524 
1525  // MI can only be specified via class_ template options, not constructor parameters
1526  static_assert(
1527  none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
1528  (constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
1529  constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
1530  // no multiple_inheritance attr
1531  none_of<std::is_same<multiple_inheritance, Extra>...>::value),
1532  "Error: multiple inheritance bases must be specified via class_ template options");
1533 
1534  type_record record;
1535  record.scope = scope;
1536  record.name = name;
1537  record.type = &typeid(type);
1540  record.holder_size = sizeof(holder_type);
1541  record.init_instance = init_instance;
1542  record.dealloc = dealloc;
1544 
1545  set_operator_new<type>(&record);
1546 
1547  /* Register base classes specified via template arguments to class_, if any */
1548  PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
1549 
1550  /* Process optional arguments, if any */
1551  process_attributes<Extra...>::init(extra..., &record);
1552 
1553  generic_type::initialize(record);
1554 
1555  if (has_alias) {
1556  auto &instances = record.module_local ? get_local_internals().registered_types_cpp
1558  instances[std::type_index(typeid(type_alias))]
1559  = instances[std::type_index(typeid(type))];
1560  }
1561  }
1562 
1564  static void add_base(detail::type_record &rec) {
1565  rec.add_base(typeid(Base), [](void *src) -> void * {
1566  return static_cast<Base *>(reinterpret_cast<type *>(src));
1567  });
1568  }
1569 
1571  static void add_base(detail::type_record &) {}
1572 
1573  template <typename Func, typename... Extra>
1574  class_ &def(const char *name_, Func &&f, const Extra &...extra) {
1575  cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
1576  name(name_),
1577  is_method(*this),
1578  sibling(getattr(*this, name_, none())),
1579  extra...);
1580  add_class_method(*this, name_, cf);
1581  return *this;
1582  }
1583 
1584  template <typename Func, typename... Extra>
1585  class_ &def_static(const char *name_, Func &&f, const Extra &...extra) {
1587  "def_static(...) called with a non-static member function pointer");
1588  cpp_function cf(std::forward<Func>(f),
1589  name(name_),
1590  scope(*this),
1591  sibling(getattr(*this, name_, none())),
1592  extra...);
1593  auto cf_name = cf.name();
1594  attr(std::move(cf_name)) = staticmethod(std::move(cf));
1595  return *this;
1596  }
1597 
1598  template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1599  class_ &def(const T &op, const Extra &...extra) {
1600  op.execute(*this, extra...);
1601  return *this;
1602  }
1603 
1604  template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1605  class_ &def_cast(const T &op, const Extra &...extra) {
1606  op.execute_cast(*this, extra...);
1607  return *this;
1608  }
1609 
1610  template <typename... Args, typename... Extra>
1611  class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra &...extra) {
1613  init.execute(*this, extra...);
1614  return *this;
1615  }
1616 
1617  template <typename... Args, typename... Extra>
1618  class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra &...extra) {
1620  init.execute(*this, extra...);
1621  return *this;
1622  }
1623 
1624  template <typename... Args, typename... Extra>
1625  class_ &def(detail::initimpl::factory<Args...> &&init, const Extra &...extra) {
1626  std::move(init).execute(*this, extra...);
1627  return *this;
1628  }
1629 
1630  template <typename... Args, typename... Extra>
1631  class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
1632  std::move(pf).execute(*this, extra...);
1633  return *this;
1634  }
1635 
1636  template <typename Func>
1637  class_ &def_buffer(Func &&func) {
1638  struct capture {
1639  Func func;
1640  };
1641  auto *ptr = new capture{std::forward<Func>(func)};
1642  install_buffer_funcs(
1643  [](PyObject *obj, void *ptr) -> buffer_info * {
1644  detail::make_caster<type> caster;
1645  if (!caster.load(obj, false)) {
1646  return nullptr;
1647  }
1648  return new buffer_info(((capture *) ptr)->func(std::move(caster)));
1649  },
1650  ptr);
1652  delete ptr;
1653  wr.dec_ref();
1654  }))
1655  .release();
1656  return *this;
1657  }
1658 
1659  template <typename Return, typename Class, typename... Args>
1660  class_ &def_buffer(Return (Class::*func)(Args...)) {
1661  return def_buffer([func](type &obj) { return (obj.*func)(); });
1662  }
1663 
1664  template <typename Return, typename Class, typename... Args>
1665  class_ &def_buffer(Return (Class::*func)(Args...) const) {
1666  return def_buffer([func](const type &obj) { return (obj.*func)(); });
1667  }
1668 
1669  template <typename C, typename D, typename... Extra>
1670  class_ &def_readwrite(const char *name, D C::*pm, const Extra &...extra) {
1672  "def_readwrite() requires a class member (or base class member)");
1673  cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this)),
1674  fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
1675  def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
1676  return *this;
1677  }
1678 
1679  template <typename C, typename D, typename... Extra>
1680  class_ &def_readonly(const char *name, const D C::*pm, const Extra &...extra) {
1682  "def_readonly() requires a class member (or base class member)");
1683  cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this));
1684  def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
1685  return *this;
1686  }
1687 
1688  template <typename D, typename... Extra>
1689  class_ &def_readwrite_static(const char *name, D *pm, const Extra &...extra) {
1690  cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)),
1691  fset([pm](const object &, const D &value) { *pm = value; }, scope(*this));
1692  def_property_static(name, fget, fset, return_value_policy::reference, extra...);
1693  return *this;
1694  }
1695 
1696  template <typename D, typename... Extra>
1697  class_ &def_readonly_static(const char *name, const D *pm, const Extra &...extra) {
1698  cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this));
1699  def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
1700  return *this;
1701  }
1702 
1704  template <typename Getter, typename... Extra>
1705  class_ &def_property_readonly(const char *name, const Getter &fget, const Extra &...extra) {
1706  return def_property_readonly(name,
1707  cpp_function(method_adaptor<type>(fget)),
1709  extra...);
1710  }
1711 
1713  template <typename... Extra>
1714  class_ &
1715  def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra) {
1716  return def_property(name, fget, nullptr, extra...);
1717  }
1718 
1720  template <typename Getter, typename... Extra>
1721  class_ &
1722  def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra) {
1723  return def_property_readonly_static(
1725  }
1726 
1728  template <typename... Extra>
1729  class_ &def_property_readonly_static(const char *name,
1730  const cpp_function &fget,
1731  const Extra &...extra) {
1732  return def_property_static(name, fget, nullptr, extra...);
1733  }
1734 
1736  template <typename Getter, typename Setter, typename... Extra>
1737  class_ &
1738  def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) {
1739  return def_property(
1740  name, fget, cpp_function(method_adaptor<type>(fset), is_setter()), extra...);
1741  }
1742  template <typename Getter, typename... Extra>
1743  class_ &def_property(const char *name,
1744  const Getter &fget,
1745  const cpp_function &fset,
1746  const Extra &...extra) {
1747  return def_property(name,
1748  cpp_function(method_adaptor<type>(fget)),
1749  fset,
1751  extra...);
1752  }
1753 
1755  template <typename... Extra>
1756  class_ &def_property(const char *name,
1757  const cpp_function &fget,
1758  const cpp_function &fset,
1759  const Extra &...extra) {
1760  return def_property_static(name, fget, fset, is_method(*this), extra...);
1761  }
1762 
1764  template <typename Getter, typename... Extra>
1765  class_ &def_property_static(const char *name,
1766  const Getter &fget,
1767  const cpp_function &fset,
1768  const Extra &...extra) {
1769  return def_property_static(
1770  name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1771  }
1772 
1774  template <typename... Extra>
1775  class_ &def_property_static(const char *name,
1776  const cpp_function &fget,
1777  const cpp_function &fset,
1778  const Extra &...extra) {
1780  "Argument annotations are not allowed for properties");
1781  auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1782  auto *rec_active = rec_fget;
1783  if (rec_fget) {
1784  char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific
1785  documentation string */
1786  detail::process_attributes<Extra...>::init(extra..., rec_fget);
1787  if (rec_fget->doc && rec_fget->doc != doc_prev) {
1788  std::free(doc_prev);
1789  rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc);
1790  }
1791  }
1792  if (rec_fset) {
1793  char *doc_prev = rec_fset->doc;
1794  detail::process_attributes<Extra...>::init(extra..., rec_fset);
1795  if (rec_fset->doc && rec_fset->doc != doc_prev) {
1796  std::free(doc_prev);
1797  rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc);
1798  }
1799  if (!rec_active) {
1800  rec_active = rec_fset;
1801  }
1802  }
1803  def_property_static_impl(name, fget, fset, rec_active);
1804  return *this;
1805  }
1806 
1807 private:
1809  template <typename T>
1810  static void init_holder(detail::instance *inst,
1811  detail::value_and_holder &v_h,
1812  const holder_type * /* unused */,
1813  const std::enable_shared_from_this<T> * /* dummy */) {
1814 
1815  auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1816  detail::try_get_shared_from_this(v_h.value_ptr<type>()));
1817  if (sh) {
1818  new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
1819  v_h.set_holder_constructed();
1820  }
1821 
1822  if (!v_h.holder_constructed() && inst->owned) {
1823  new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1824  v_h.set_holder_constructed();
1825  }
1826  }
1827 
1828  static void init_holder_from_existing(const detail::value_and_holder &v_h,
1829  const holder_type *holder_ptr,
1830  std::true_type /*is_copy_constructible*/) {
1831  new (std::addressof(v_h.holder<holder_type>()))
1832  holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1833  }
1834 
1835  static void init_holder_from_existing(const detail::value_and_holder &v_h,
1836  const holder_type *holder_ptr,
1837  std::false_type /*is_copy_constructible*/) {
1838  new (std::addressof(v_h.holder<holder_type>()))
1839  holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1840  }
1841 
1844  static void init_holder(detail::instance *inst,
1845  detail::value_and_holder &v_h,
1846  const holder_type *holder_ptr,
1847  const void * /* dummy -- not enable_shared_from_this<T>) */) {
1848  if (holder_ptr) {
1849  init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1850  v_h.set_holder_constructed();
1852  new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1853  v_h.set_holder_constructed();
1854  }
1855  }
1856 
1861  static void init_instance(detail::instance *inst, const void *holder_ptr) {
1862  auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
1863  if (!v_h.instance_registered()) {
1864  register_instance(inst, v_h.value_ptr(), v_h.type);
1865  v_h.set_instance_registered();
1866  }
1867  init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
1868  }
1869 
1871  static void dealloc(detail::value_and_holder &v_h) {
1872  // We could be deallocating because we are cleaning up after a Python exception.
1873  // If so, the Python error indicator will be set. We need to clear that before
1874  // running the destructor, in case the destructor code calls more Python.
1875  // If we don't, the Python API will exit with an exception, and pybind11 will
1876  // throw error_already_set from the C++ destructor which is forbidden and triggers
1877  // std::terminate().
1879  if (v_h.holder_constructed()) {
1880  v_h.holder<holder_type>().~holder_type();
1881  v_h.set_holder_constructed(false);
1882  } else {
1884  v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align);
1885  }
1886  v_h.value_ptr() = nullptr;
1887  }
1888 
1889  static detail::function_record *get_function_record(handle h) {
1891  if (!h) {
1892  return nullptr;
1893  }
1894 
1895  handle func_self = PyCFunction_GET_SELF(h.ptr());
1896  if (!func_self) {
1897  throw error_already_set();
1898  }
1899  if (!isinstance<capsule>(func_self)) {
1900  return nullptr;
1901  }
1902  auto cap = reinterpret_borrow<capsule>(func_self);
1904  return nullptr;
1905  }
1906  return cap.get_pointer<detail::function_record>();
1907  }
1908 };
1909 
1911 template <typename... Args>
1912 detail::initimpl::constructor<Args...> init() {
1913  return {};
1914 }
1917 template <typename... Args>
1918 detail::initimpl::alias_constructor<Args...> init_alias() {
1919  return {};
1920 }
1921 
1923 template <typename Func, typename Ret = detail::initimpl::factory<Func>>
1924 Ret init(Func &&f) {
1925  return {std::forward<Func>(f)};
1926 }
1927 
1931 template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1932 Ret init(CFunc &&c, AFunc &&a) {
1933  return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1934 }
1935 
1938 template <typename GetState, typename SetState>
1939 detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
1940  return {std::forward<GetState>(g), std::forward<SetState>(s)};
1941 }
1942 
1944 
1946  dict entries = arg.get_type().attr("__entries");
1947  for (auto kv : entries) {
1948  if (handle(kv.second[int_(0)]).equal(arg)) {
1949  return pybind11::str(kv.first);
1950  }
1951  }
1952  return "???";
1953 }
1954 
1955 struct enum_base {
1956  enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) {}
1957 
1958  PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
1959  m_base.attr("__entries") = dict();
1960  auto property = handle((PyObject *) &PyProperty_Type);
1961  auto static_property = handle((PyObject *) get_internals().static_property_type);
1962 
1963  m_base.attr("__repr__") = cpp_function(
1964  [](const object &arg) -> str {
1966  object type_name = type.attr("__name__");
1967  return pybind11::str("<{}.{}: {}>")
1968  .format(std::move(type_name), enum_name(arg), int_(arg));
1969  },
1970  name("__repr__"),
1971  is_method(m_base));
1972 
1973  m_base.attr("name") = property(cpp_function(&enum_name, name("name"), is_method(m_base)));
1974 
1975  m_base.attr("__str__") = cpp_function(
1976  [](handle arg) -> str {
1977  object type_name = type::handle_of(arg).attr("__name__");
1978  return pybind11::str("{}.{}").format(std::move(type_name), enum_name(arg));
1979  },
1980  name("name"),
1981  is_method(m_base));
1982 
1984  m_base.attr("__doc__") = static_property(
1985  cpp_function(
1986  [](handle arg) -> std::string {
1987  std::string docstring;
1988  dict entries = arg.attr("__entries");
1989  if (((PyTypeObject *) arg.ptr())->tp_doc) {
1990  docstring += std::string(
1991  reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);
1992  docstring += "\n\n";
1993  }
1994  docstring += "Members:";
1995  for (auto kv : entries) {
1996  auto key = std::string(pybind11::str(kv.first));
1997  auto comment = kv.second[int_(1)];
1998  docstring += "\n\n ";
1999  docstring += key;
2000  if (!comment.is_none()) {
2001  docstring += " : ";
2002  docstring += pybind11::str(comment).cast<std::string>();
2003  }
2004  }
2005  return docstring;
2006  },
2007  name("__doc__")),
2008  none(),
2009  none(),
2010  "");
2011  }
2012 
2013  m_base.attr("__members__") = static_property(cpp_function(
2014  [](handle arg) -> dict {
2015  dict entries = arg.attr("__entries"),
2016  m;
2017  for (auto kv : entries) {
2018  m[kv.first] = kv.second[int_(0)];
2019  }
2020  return m;
2021  },
2022  name("__members__")),
2023  none(),
2024  none(),
2025  "");
2026 
2027 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
2028  m_base.attr(op) = cpp_function( \
2029  [](const object &a, const object &b) { \
2030  if (!type::handle_of(a).is(type::handle_of(b))) \
2031  strict_behavior; /* NOLINT(bugprone-macro-parentheses) */ \
2032  return expr; \
2033  }, \
2034  name(op), \
2035  is_method(m_base), \
2036  arg("other"))
2037 
2038 #define PYBIND11_ENUM_OP_CONV(op, expr) \
2039  m_base.attr(op) = cpp_function( \
2040  [](const object &a_, const object &b_) { \
2041  int_ a(a_), b(b_); \
2042  return expr; \
2043  }, \
2044  name(op), \
2045  is_method(m_base), \
2046  arg("other"))
2047 
2048 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
2049  m_base.attr(op) = cpp_function( \
2050  [](const object &a_, const object &b) { \
2051  int_ a(a_); \
2052  return expr; \
2053  }, \
2054  name(op), \
2055  is_method(m_base), \
2056  arg("other"))
2057 
2058  if (is_convertible) {
2059  PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
2060  PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
2061 
2062  if (is_arithmetic) {
2063  PYBIND11_ENUM_OP_CONV("__lt__", a < b);
2064  PYBIND11_ENUM_OP_CONV("__gt__", a > b);
2065  PYBIND11_ENUM_OP_CONV("__le__", a <= b);
2066  PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
2067  PYBIND11_ENUM_OP_CONV("__and__", a & b);
2068  PYBIND11_ENUM_OP_CONV("__rand__", a & b);
2069  PYBIND11_ENUM_OP_CONV("__or__", a | b);
2070  PYBIND11_ENUM_OP_CONV("__ror__", a | b);
2071  PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
2072  PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
2073  m_base.attr("__invert__")
2074  = cpp_function([](const object &arg) { return ~(int_(arg)); },
2075  name("__invert__"),
2076  is_method(m_base));
2077  }
2078  } else {
2079  PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
2080  PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
2081 
2082  if (is_arithmetic) {
2083 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
2088 #undef PYBIND11_THROW
2089  }
2090  }
2091 
2092 #undef PYBIND11_ENUM_OP_CONV_LHS
2093 #undef PYBIND11_ENUM_OP_CONV
2094 #undef PYBIND11_ENUM_OP_STRICT
2095 
2096  m_base.attr("__getstate__") = cpp_function(
2097  [](const object &arg) { return int_(arg); }, name("__getstate__"), is_method(m_base));
2098 
2099  m_base.attr("__hash__") = cpp_function(
2100  [](const object &arg) { return int_(arg); }, name("__hash__"), is_method(m_base));
2101  }
2102 
2103  PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc = nullptr) {
2104  dict entries = m_base.attr("__entries");
2105  str name(name_);
2106  if (entries.contains(name)) {
2107  std::string type_name = (std::string) str(m_base.attr("__name__"));
2108  throw value_error(std::move(type_name) + ": element \"" + std::string(name_)
2109  + "\" already exists!");
2110  }
2111 
2112  entries[name] = pybind11::make_tuple(value, doc);
2113  m_base.attr(std::move(name)) = std::move(value);
2114  }
2115 
2117  dict entries = m_base.attr("__entries");
2118  for (auto kv : entries) {
2119  m_parent.attr(kv.first) = kv.second[int_(0)];
2120  }
2121  }
2122 
2125 };
2126 
2127 template <bool is_signed, size_t length>
2129 template <>
2130 struct equivalent_integer<true, 1> {
2131  using type = int8_t;
2132 };
2133 template <>
2134 struct equivalent_integer<false, 1> {
2135  using type = uint8_t;
2136 };
2137 template <>
2138 struct equivalent_integer<true, 2> {
2139  using type = int16_t;
2140 };
2141 template <>
2142 struct equivalent_integer<false, 2> {
2143  using type = uint16_t;
2144 };
2145 template <>
2146 struct equivalent_integer<true, 4> {
2147  using type = int32_t;
2148 };
2149 template <>
2150 struct equivalent_integer<false, 4> {
2151  using type = uint32_t;
2152 };
2153 template <>
2154 struct equivalent_integer<true, 8> {
2155  using type = int64_t;
2156 };
2157 template <>
2158 struct equivalent_integer<false, 8> {
2159  using type = uint64_t;
2160 };
2161 
2162 template <typename IntLike>
2163 using equivalent_integer_t =
2165 
2167 
2168 template <typename Type>
2170 class enum_ : public class_<Type> {
2171 public:
2173  using Base::attr;
2174  using Base::def;
2175  using Base::def_property_readonly;
2176  using Base::def_property_readonly_static;
2178  // Scalar is the integer representation of underlying type
2179  using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2180  std::is_same<Underlying, bool>>::value,
2181  detail::equivalent_integer_t<Underlying>,
2183 
2184  template <typename... Extra>
2185  enum_(const handle &scope, const char *name, const Extra &...extra)
2186  : class_<Type>(scope, name, extra...), m_base(*this, scope) {
2187  constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
2188  constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
2189  m_base.init(is_arithmetic, is_convertible);
2190 
2191  def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
2192  def_property_readonly("value", [](Type value) { return (Scalar) value; });
2193  def("__int__", [](Type value) { return (Scalar) value; });
2194  def("__index__", [](Type value) { return (Scalar) value; });
2195  attr("__setstate__") = cpp_function(
2196  [](detail::value_and_holder &v_h, Scalar arg) {
2197  detail::initimpl::setstate<Base>(
2198  v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type);
2199  },
2200  detail::is_new_style_constructor(),
2201  pybind11::name("__setstate__"),
2202  is_method(*this),
2203  arg("state"));
2204  }
2205 
2208  m_base.export_values();
2209  return *this;
2210  }
2211 
2213  enum_ &value(char const *name, Type value, const char *doc = nullptr) {
2215  return *this;
2216  }
2217 
2218 private:
2219  detail::enum_base m_base;
2220 };
2221 
2223 
2225  if (!nurse || !patient) {
2226  pybind11_fail("Could not activate keep_alive!");
2227  }
2228 
2229  if (patient.is_none() || nurse.is_none()) {
2230  return; /* Nothing to keep alive or nothing to be kept alive by */
2231  }
2232 
2233  auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
2234  if (!tinfo.empty()) {
2235  /* It's a pybind-registered type, so we can store the patient in the
2236  * internal list. */
2237  add_patient(nurse.ptr(), patient.ptr());
2238  } else {
2239  /* Fall back to clever approach based on weak references taken from
2240  * Boost.Python. This is not used for pybind-registered types because
2241  * the objects can be destroyed out-of-order in a GC pass. */
2242  cpp_function disable_lifesupport([patient](handle weakref) {
2243  patient.dec_ref();
2244  weakref.dec_ref();
2245  });
2246 
2247  weakref wr(nurse, disable_lifesupport);
2248 
2249  patient.inc_ref(); /* reference patient and leak the weak reference */
2250  (void) wr.release();
2251  }
2252 }
2253 
2254 PYBIND11_NOINLINE void
2255 keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
2256  auto get_arg = [&](size_t n) {
2257  if (n == 0) {
2258  return ret;
2259  }
2260  if (n == 1 && call.init_self) {
2261  return call.init_self;
2262  }
2263  if (n <= call.args.size()) {
2264  return call.args[n - 1];
2265  }
2266  return handle();
2267  };
2268 
2269  keep_alive_impl(get_arg(Nurse), get_arg(Patient));
2270 }
2271 
2272 inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
2274  auto res = get_internals()
2276 #ifdef __cpp_lib_unordered_map_try_emplace
2277  .try_emplace(type);
2278 #else
2279  .emplace(type, std::vector<detail::type_info *>());
2280 #endif
2281  if (res.second) {
2282  // New cache entry created; set up a weak reference to automatically remove it if the type
2283  // gets destroyed:
2284  weakref((PyObject *) type, cpp_function([type](handle wr) {
2286 
2287  // TODO consolidate the erasure code in pybind11_meta_dealloc() in class.h
2288  auto &cache = get_internals().inactive_override_cache;
2289  for (auto it = cache.begin(), last = cache.end(); it != last;) {
2290  if (it->first == reinterpret_cast<PyObject *>(type)) {
2291  it = cache.erase(it);
2292  } else {
2293  ++it;
2294  }
2295  }
2296 
2297  wr.dec_ref();
2298  }))
2299  .release();
2300  }
2301 
2302  return res;
2303 }
2304 
2305 /* There are a large number of apparently unused template arguments because
2306  * each combination requires a separate py::class_ registration.
2307  */
2308 template <typename Access,
2309  return_value_policy Policy,
2310  typename Iterator,
2311  typename Sentinel,
2312  typename ValueType,
2313  typename... Extra>
2315  Iterator it;
2316  Sentinel end;
2318 };
2319 
2320 // Note: these helpers take the iterator by non-const reference because some
2321 // iterators in the wild can't be dereferenced when const. The & after Iterator
2322 // is required for MSVC < 16.9. SFINAE cannot be reused for result_type due to
2323 // bugs in ICC, NVCC, and PGI compilers. See PR #3293.
2324 template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
2326  using result_type = decltype(*std::declval<Iterator &>());
2327  // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
2328  result_type operator()(Iterator &it) const { return *it; }
2329 };
2330 
2331 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).first)>
2333 private:
2334  using pair_type = decltype(*std::declval<Iterator &>());
2335 
2336 public:
2337  /* If either the pair itself or the element of the pair is a reference, we
2338  * want to return a reference, otherwise a value. When the decltype
2339  * expression is parenthesized it is based on the value category of the
2340  * expression; otherwise it is the declared type of the pair member.
2341  * The use of declval<pair_type> in the second branch rather than directly
2342  * using *std::declval<Iterator &>() is a workaround for nvcc
2343  * (it's not used in the first branch because going via decltype and back
2344  * through declval does not perfectly preserve references).
2345  */
2346  using result_type
2348  decltype(((*std::declval<Iterator &>()).first)),
2349  decltype(std::declval<pair_type>().first)>;
2350  result_type operator()(Iterator &it) const { return (*it).first; }
2351 };
2352 
2353 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
2355 private:
2356  using pair_type = decltype(*std::declval<Iterator &>());
2357 
2358 public:
2359  using result_type
2361  decltype(((*std::declval<Iterator &>()).second)),
2362  decltype(std::declval<pair_type>().second)>;
2363  result_type operator()(Iterator &it) const { return (*it).second; }
2364 };
2365 
2366 template <typename Access,
2367  return_value_policy Policy,
2368  typename Iterator,
2369  typename Sentinel,
2370  typename ValueType,
2371  typename... Extra>
2372 iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra) {
2373  using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
2374  // TODO: state captures only the types of Extra, not the values
2375 
2376  if (!detail::get_type_info(typeid(state), false)) {
2377  class_<state>(handle(), "iterator", pybind11::module_local())
2378  .def("__iter__", [](state &s) -> state & { return s; })
2379  .def(
2380  "__next__",
2381  [](state &s) -> ValueType {
2382  if (!s.first_or_done) {
2383  ++s.it;
2384  } else {
2385  s.first_or_done = false;
2386  }
2387  if (s.it == s.end) {
2388  s.first_or_done = true;
2389  throw stop_iteration();
2390  }
2391  return Access()(s.it);
2392  // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
2393  },
2394  std::forward<Extra>(extra)...,
2395  Policy);
2396  }
2397 
2398  return cast(state{first, last, true});
2399 }
2400 
2402 
2405  typename Iterator,
2406  typename Sentinel,
2407  typename ValueType = typename detail::iterator_access<Iterator>::result_type,
2408  typename... Extra>
2409 iterator make_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2410  return detail::make_iterator_impl<detail::iterator_access<Iterator>,
2411  Policy,
2412  Iterator,
2413  Sentinel,
2414  ValueType,
2415  Extra...>(first, last, std::forward<Extra>(extra)...);
2416 }
2417 
2421  typename Iterator,
2422  typename Sentinel,
2423  typename KeyType = typename detail::iterator_key_access<Iterator>::result_type,
2424  typename... Extra>
2425 iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2426  return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
2427  Policy,
2428  Iterator,
2429  Sentinel,
2430  KeyType,
2431  Extra...>(first, last, std::forward<Extra>(extra)...);
2432 }
2433 
2437  typename Iterator,
2438  typename Sentinel,
2439  typename ValueType = typename detail::iterator_value_access<Iterator>::result_type,
2440  typename... Extra>
2441 iterator make_value_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2442  return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
2443  Policy,
2444  Iterator,
2445  Sentinel,
2446  ValueType,
2447  Extra...>(first, last, std::forward<Extra>(extra)...);
2448 }
2449 
2453  typename Type,
2454  typename... Extra>
2455 iterator make_iterator(Type &value, Extra &&...extra) {
2456  return make_iterator<Policy>(
2457  std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2458 }
2459 
2463  typename Type,
2464  typename... Extra>
2465 iterator make_key_iterator(Type &value, Extra &&...extra) {
2466  return make_key_iterator<Policy>(
2467  std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2468 }
2469 
2473  typename Type,
2474  typename... Extra>
2476  return make_value_iterator<Policy>(
2477  std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2478 }
2479 
2480 template <typename InputType, typename OutputType>
2482  struct set_flag {
2483  bool &flag;
2484  explicit set_flag(bool &flag_) : flag(flag_) { flag_ = true; }
2485  ~set_flag() { flag = false; }
2486  };
2487  auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
2488  static bool currently_used = false;
2489  if (currently_used) { // implicit conversions are non-reentrant
2490  return nullptr;
2491  }
2492  set_flag flag_helper(currently_used);
2493  if (!detail::make_caster<InputType>().load(obj, false)) {
2494  return nullptr;
2495  }
2496  tuple args(1);
2497  args[0] = obj;
2498  PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
2499  if (result == nullptr) {
2500  PyErr_Clear();
2501  }
2502  return result;
2503  };
2504 
2505  if (auto *tinfo = detail::get_type_info(typeid(OutputType))) {
2506  tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
2507  } else {
2508  pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
2509  }
2510 }
2511 
2514  std::forward<ExceptionTranslator>(translator));
2515 }
2516 
2525  std::forward<ExceptionTranslator>(translator));
2526 }
2527 
2535 template <typename type>
2536 class exception : public object {
2537 public:
2538  exception() = default;
2539  exception(handle scope, const char *name, handle base = PyExc_Exception) {
2540  std::string full_name
2541  = scope.attr("__name__").cast<std::string>() + std::string(".") + name;
2542  m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), nullptr);
2543  if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name)) {
2544  pybind11_fail("Error during initialization: multiple incompatible "
2545  "definitions with name \""
2546  + std::string(name) + "\"");
2547  }
2548  scope.attr(name) = *this;
2549  }
2550 
2551  // Sets the current python exception to this exception object with the given message
2552  void operator()(const char *message) { PyErr_SetString(m_ptr, message); }
2553 };
2554 
2556 // Returns a reference to a function-local static exception object used in the simple
2557 // register_exception approach below. (It would be simpler to have the static local variable
2558 // directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
2559 template <typename CppException>
2560 exception<CppException> &get_exception_object() {
2561  static exception<CppException> ex;
2562  return ex;
2563 }
2564 
2565 // Helper function for register_exception and register_local_exception
2566 template <typename CppException>
2567 exception<CppException> &
2568 register_exception_impl(handle scope, const char *name, handle base, bool isLocal) {
2569  auto &ex = detail::get_exception_object<CppException>();
2570  if (!ex) {
2571  ex = exception<CppException>(scope, name, base);
2572  }
2573 
2574  auto register_func
2576 
2577  register_func([](std::exception_ptr p) {
2578  if (!p) {
2579  return;
2580  }
2581  try {
2582  std::rethrow_exception(p);
2583  } catch (const CppException &e) {
2584  detail::get_exception_object<CppException>()(e.what());
2585  }
2586  });
2587  return ex;
2588 }
2589 
2591 
2592 
2598 template <typename CppException>
2599 exception<CppException> &
2600 register_exception(handle scope, const char *name, handle base = PyExc_Exception) {
2601  return detail::register_exception_impl<CppException>(scope, name, base, false /* isLocal */);
2602 }
2603 
2612 template <typename CppException>
2613 exception<CppException> &
2614 register_local_exception(handle scope, const char *name, handle base = PyExc_Exception) {
2615  return detail::register_exception_impl<CppException>(scope, name, base, true /* isLocal */);
2616 }
2617 
2620  auto strings = tuple(args.size());
2621  for (size_t i = 0; i < args.size(); ++i) {
2622  strings[i] = str(args[i]);
2623  }
2624  auto sep = kwargs.contains("sep") ? kwargs["sep"] : str(" ");
2625  auto line = sep.attr("join")(std::move(strings));
2626 
2627  object file;
2628  if (kwargs.contains("file")) {
2629  file = kwargs["file"].cast<object>();
2630  } else {
2631  try {
2632  file = module_::import("sys").attr("stdout");
2633  } catch (const error_already_set &) {
2634  /* If print() is called from code that is executed as
2635  part of garbage collection during interpreter shutdown,
2636  importing 'sys' can fail. Give up rather than crashing the
2637  interpreter in this case. */
2638  return;
2639  }
2640  }
2641 
2642  auto write = file.attr("write");
2643  write(std::move(line));
2644  write(kwargs.contains("end") ? kwargs["end"] : str("\n"));
2645 
2646  if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) {
2647  file.attr("flush")();
2648  }
2649 }
2651 
2652 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
2653 void print(Args &&...args) {
2654  auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
2655  detail::print(c.args(), c.kwargs());
2656 }
2657 
2658 inline void
2659 error_already_set::m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr) {
2660  gil_scoped_acquire gil;
2662  delete raw_ptr;
2663 }
2664 
2665 inline const char *error_already_set::what() const noexcept {
2666  gil_scoped_acquire gil;
2668  return m_fetched_error->error_string().c_str();
2669 }
2670 
2672 
2673 inline function
2674 get_type_override(const void *this_ptr, const type_info *this_type, const char *name) {
2675  handle self = get_object_handle(this_ptr, this_type);
2676  if (!self) {
2677  return function();
2678  }
2679  handle type = type::handle_of(self);
2680  auto key = std::make_pair(type.ptr(), name);
2681 
2682  /* Cache functions that aren't overridden in Python to avoid
2683  many costly Python dictionary lookups below */
2684  auto &cache = get_internals().inactive_override_cache;
2685  if (cache.find(key) != cache.end()) {
2686  return function();
2687  }
2688 
2689  function override = getattr(self, name, function());
2690  if (override.is_cpp_function()) {
2691  cache.insert(std::move(key));
2692  return function();
2693  }
2694 
2695  /* Don't call dispatch code if invoked from overridden function.
2696  Unfortunately this doesn't work on PyPy. */
2697 #if !defined(PYPY_VERSION)
2698 # if PY_VERSION_HEX >= 0x03090000
2699  PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
2700  if (frame != nullptr) {
2701  PyCodeObject *f_code = PyFrame_GetCode(frame);
2702  // f_code is guaranteed to not be NULL
2703  if ((std::string) str(f_code->co_name) == name && f_code->co_argcount > 0) {
2704  PyObject *locals = PyEval_GetLocals();
2705  if (locals != nullptr) {
2706  PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code, "co_varnames");
2707  PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
2708  Py_DECREF(co_varnames);
2709  PyObject *self_caller = dict_getitem(locals, self_arg);
2710  if (self_caller == self.ptr()) {
2711  Py_DECREF(f_code);
2712  Py_DECREF(frame);
2713  return function();
2714  }
2715  }
2716  }
2717  Py_DECREF(f_code);
2718  Py_DECREF(frame);
2719  }
2720 # else
2721  PyFrameObject *frame = PyThreadState_Get()->frame;
2722  if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name
2723  && frame->f_code->co_argcount > 0) {
2724  PyFrame_FastToLocals(frame);
2725  PyObject *self_caller
2726  = dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2727  if (self_caller == self.ptr()) {
2728  return function();
2729  }
2730  }
2731 # endif
2732 
2733 #else
2734  /* PyPy currently doesn't provide a detailed cpyext emulation of
2735  frame objects, so we have to emulate this using Python. This
2736  is going to be slow..*/
2737  dict d;
2738  d["self"] = self;
2739  d["name"] = pybind11::str(name);
2740  PyObject *result
2741  = PyRun_String("import inspect\n"
2742  "frame = inspect.currentframe()\n"
2743  "if frame is not None:\n"
2744  " frame = frame.f_back\n"
2745  " if frame is not None and str(frame.f_code.co_name) == name and "
2746  "frame.f_code.co_argcount > 0:\n"
2747  " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2748  " if self_caller == self:\n"
2749  " self = None\n",
2750  Py_file_input,
2751  d.ptr(),
2752  d.ptr());
2753  if (result == nullptr)
2754  throw error_already_set();
2755  Py_DECREF(result);
2756  if (d["self"].is_none())
2757  return function();
2758 #endif
2759 
2760  return override;
2761 }
2763 
2764 
2773 template <class T>
2774 function get_override(const T *this_ptr, const char *name) {
2775  auto *tinfo = detail::get_type_info(typeid(T));
2776  return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
2777 }
2778 
2779 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
2780  do { \
2781  pybind11::gil_scoped_acquire gil; \
2782  pybind11::function override \
2783  = pybind11::get_override(static_cast<const cname *>(this), name); \
2784  if (override) { \
2785  auto o = override(__VA_ARGS__); \
2786  if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
2787  static pybind11::detail::override_caster_t<ret_type> caster; \
2788  return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
2789  } \
2790  return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2791  } \
2792  } while (false)
2793 
2812 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
2813  do { \
2814  PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2815  return cname::fn(__VA_ARGS__); \
2816  } while (false)
2817 
2822 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
2823  do { \
2824  PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2825  pybind11::pybind11_fail( \
2826  "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
2827  } while (false)
2828 
2854 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
2855  PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2856 
2861 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
2862  PYBIND11_OVERRIDE_PURE_NAME( \
2863  PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2864 
2865 // Deprecated versions
2866 
2867 PYBIND11_DEPRECATED("get_type_overload has been deprecated")
2868 inline function
2869 get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
2870  return detail::get_type_override(this_ptr, this_type, name);
2871 }
2872 
2873 template <class T>
2874 inline function get_overload(const T *this_ptr, const char *name) {
2875  return get_override(this_ptr, name);
2876 }
2877 
2878 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
2879  PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
2880 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
2881  PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
2882 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
2883  PYBIND11_OVERRIDE_PURE_NAME( \
2884  PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
2885 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
2886  PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
2887 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2888  PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
2889 
return_value_policy::reference_internal
@ reference_internal
module_::import
static module_ import(const char *name)
Import and return a module or throws error_already_set.
Definition: pybind11.h:1211
int_
Definition: pytypes.h:1793
ExceptionTranslator
void(*)(std::exception_ptr) ExceptionTranslator
Definition: internals.h:51
cpp_function::destruct
static void destruct(detail::function_record *rec, bool free_strings=true)
When a cpp_function is GCed, release any memory allocated by pybind11.
Definition: pybind11.h:630
cpp_function::initialize
void initialize(Func &&f, Return(*)(Args...), const Extra &...extra)
Special internal constructor for functors, lambda functions, etc.
Definition: pybind11.h:169
all_of
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... > > all_of
Definition: wrap/pybind11/include/pybind11/detail/common.h:726
error_scope
RAII wrapper that temporarily clears any Python error state.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1076
class_::add_base
static void add_base(detail::type_record &)
Definition: pybind11.h:1571
class_::def_readonly
class_ & def_readonly(const char *name, const D C::*pm, const Extra &...extra)
Definition: pybind11.h:1680
module_::add_object
PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite=false)
Definition: pybind11.h:1235
exception::exception
exception()=default
PYBIND11_MODULE_LOCAL_ID
#define PYBIND11_MODULE_LOCAL_ID
Definition: internals.h:315
equivalent_integer_t
typename equivalent_integer< std::is_signed< IntLike >::value, sizeof(IntLike)>::type equivalent_integer_t
Definition: pybind11.h:2164
implicitly_convertible
void implicitly_convertible()
Definition: pybind11.h:2481
cpp_function::cpp_function
cpp_function()=default
attr.h
is_setter
Annotation for setters.
Definition: attr.h:30
name
Annotation for function names.
Definition: attr.h:51
function_record
Definition: attr.h:191
setattr
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:905
PYBIND11_EXPAND_SIDE_EFFECTS
#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)
Definition: wrap/pybind11/include/pybind11/detail/common.h:978
PYBIND11_INSTANCE_METHOD_GET_FUNCTION
#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION
Definition: wrap/pybind11/include/pybind11/detail/common.h:348
internals
Definition: internals.h:168
base
Annotation indicating that a class derives from another given type.
Definition: attr.h:64
enum_
Binds C++ enumerations and enumeration classes to Python.
Definition: pybind11.h:2170
class_< Type >::is_subtype
detail::is_strict_base_of< Type, T > is_subtype
Definition: pybind11.h:1500
cpp_function::initialize_generic
void initialize_generic(unique_function_record &&unique_rec, const char *text, const std::type_info *const *types, size_t args)
Register a function call with Python (generic non-templated code goes here)
Definition: pybind11.h:342
get_type_override
function get_type_override(const void *this_ptr, const type_info *this_type, const char *name)
Definition: pybind11.h:2674
class_::def_cast
class_ & def_cast(const T &op, const Extra &...extra)
Definition: pybind11.h:1605
function_record::scope
handle scope
Python handle to the parent scope (a class or a module)
Definition: attr.h:262
class_< Type >::is_base
detail::is_strict_base_of< T, Type > is_base
Definition: pybind11.h:1502
int16_t
signed short int16_t
Definition: ms_stdint.h:81
D
MatrixXcd D
Definition: EigenSolver_EigenSolver_MatrixType.cpp:14
class_::dealloc
static void dealloc(detail::value_and_holder &v_h)
Deallocates an instance; via holder, if constructed; otherwise via operator delete.
Definition: pybind11.h:1871
class.h
add_patient
void add_patient(PyObject *nurse, PyObject *patient)
Definition: class.h:382
gtsam.examples.DogLegOptimizerExample.type
type
Definition: DogLegOptimizerExample.py:111
PYBIND11_OBJECT
#define PYBIND11_OBJECT(Name, Parent, CheckFun)
Definition: pytypes.h:1397
function::is_cpp_function
bool is_cpp_function() const
Definition: pytypes.h:2215
scope
Annotation for parent scope.
Definition: attr.h:39
error_already_set
Definition: pytypes.h:722
type_info
Definition: internals.h:226
PYBIND11_WARNING_DISABLE_GCC
#define PYBIND11_WARNING_DISABLE_GCC(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:67
kwargs
Definition: pytypes.h:2166
s
RealScalar s
Definition: level1_cplx_impl.h:126
const_name
constexpr descr< N - 1 > const_name(char const (&text)[N])
Definition: descr.h:60
e
Array< double, 1, 3 > e(1./3., 0.5, 2.)
d
static const double d[K][N]
Definition: igam.h:11
iterator_key_access::result_type
conditional_t< std::is_reference< decltype(*std::declval< Iterator & >())>::value, decltype(((*std::declval< Iterator & >()).first)), decltype(std::declval< pair_type >().first)> result_type
Definition: pybind11.h:2349
enum_::value
enum_ & value(char const *name, Type value, const char *doc=nullptr)
Add an enumeration entry.
Definition: pybind11.h:2213
cpp_function::name
object name() const
Return the function name.
Definition: pybind11.h:151
staticmethod
Definition: pytypes.h:2218
return_value_policy
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
Definition: wrap/pybind11/include/pybind11/detail/common.h:485
cpp_function::strdup_guard::operator()
char * operator()(const char *s)
Definition: pybind11.h:330
class_::def_property
class_ & def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
Definition: pybind11.h:1738
internals::registered_types_cpp
type_map< type_info * > registered_types_cpp
Definition: internals.h:170
enum_::m_base
detail::enum_base m_base
Definition: pybind11.h:2219
uint32_t
unsigned int uint32_t
Definition: ms_stdint.h:85
get_global_type_info
detail::type_info * get_global_type_info(const std::type_index &tp)
Definition: type_caster_base.h:205
instance::get_value_and_holder
value_and_holder get_value_and_holder(const type_info *find_type=nullptr, bool throw_if_missing=true)
Definition: type_caster_base.h:380
void_t
typename void_t_impl< Ts... >::type void_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:713
class_::def_readwrite
class_ & def_readwrite(const char *name, D C::*pm, const Extra &...extra)
Definition: pybind11.h:1670
class_< Type >::holder_type
detail::exactly_one_t< is_holder, std::unique_ptr< type >, options... > holder_type
Definition: pybind11.h:1511
cpp_function::strdup_guard::release
void release()
Definition: pybind11.h:335
c
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
b
Scalar * b
Definition: benchVecAdd.cpp:17
iterator_access::result_type
decltype(*std::declval< Iterator & >()) result_type
Definition: pybind11.h:2326
cpp_function::cpp_function
cpp_function(Return(Class::*f)(Arg...), const Extra &...extra)
Construct a cpp_function from a class method (non-const, no ref-qualifier)
Definition: pybind11.h:109
clean_type_id
PYBIND11_NOINLINE void clean_type_id(std::string &name)
Definition: typeid.h:35
constexpr_sum
constexpr size_t constexpr_sum()
Compile-time integer sum.
Definition: wrap/pybind11/include/pybind11/detail/common.h:814
cpp_function::dispatcher
static PyObject * dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in)
Main dispatch logic for calls to functions bound using pybind11.
Definition: pybind11.h:676
class_::def_readonly_static
class_ & def_readonly_static(const char *name, const D *pm, const Extra &...extra)
Definition: pybind11.h:1697
PYBIND11_THROW
#define PYBIND11_THROW
enum_base
Definition: pybind11.h:1955
cpp_function::strdup_guard::~strdup_guard
~strdup_guard()
Definition: pybind11.h:325
pybind_wrapper_test_script.this
this
Definition: pybind_wrapper_test_script.py:38
try_get_shared_from_this
static std::shared_ptr< T > try_get_shared_from_this(std::enable_shared_from_this< T > *holder_value_ptr)
Definition: wrap/pybind11/include/pybind11/detail/common.h:1187
handle::inc_ref
const handle & inc_ref() const &
Definition: pytypes.h:249
module_::module_def
PyModuleDef module_def
Definition: pybind11.h:1245
ret
DenseIndex ret
Definition: level1_cplx_impl.h:44
enum_base::value
PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc=nullptr)
Definition: pybind11.h:2103
local_internals::registered_exception_translators
std::forward_list< ExceptionTranslator > registered_exception_translators
Definition: internals.h:546
print
PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs)
Definition: pybind11.h:2619
PYBIND11_WARNING_POP
PYBIND11_WARNING_PUSH PYBIND11_WARNING_POP
Definition: tensor.h:30
iterator_value_access::operator()
result_type operator()(Iterator &it) const
Definition: pybind11.h:2363
iterator_value_access
Definition: pybind11.h:2354
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:80
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:853
cpp_function::unique_function_record
std::unique_ptr< detail::function_record, InitializingFunctionRecordDeleter > unique_function_record
Definition: pybind11.h:160
capsule
Definition: pytypes.h:1909
PYBIND11_NOINLINE
#define PYBIND11_NOINLINE
Definition: wrap/pybind11/include/pybind11/detail/common.h:186
type
Definition: pytypes.h:1491
get_overload
function get_overload(const T *this_ptr, const char *name)
Definition: pybind11.h:2874
getattr
object getattr(handle obj, handle name)
Definition: pytypes.h:873
class_::def_buffer
class_ & def_buffer(Func &&func)
Definition: pybind11.h:1637
value_and_holder
Definition: type_caster_base.h:253
iterator_state::end
Sentinel end
Definition: pybind11.h:2316
T
Eigen::Triplet< double > T
Definition: Tutorial_sparse_example.cpp:6
handle::m_ptr
PyObject * m_ptr
Definition: pytypes.h:297
options::show_enum_members_docstring
static bool show_enum_members_docstring()
Definition: options.h:68
class_< Type >::type_alias
detail::exactly_one_t< is_subtype, void, options... > type_alias
Definition: pybind11.h:1509
detail
Definition: testSerializationNonlinear.cpp:70
class_::def_readwrite_static
class_ & def_readwrite_static(const char *name, D *pm, const Extra &...extra)
Definition: pybind11.h:1689
options.h
type_record::init_instance
void(* init_instance)(instance *, const void *)
Function pointer to class_<..>::init_instance.
Definition: attr.h:299
dict_getitemstring
PyObject * dict_getitemstring(PyObject *v, const char *key)
Definition: pytypes.h:943
type_record::name
const char * name
Name of the class.
Definition: attr.h:281
any_of
negation< all_of< negation< Ts >... > > any_of
Definition: wrap/pybind11/include/pybind11/detail/common.h:728
get_internals
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
Definition: internals.h:467
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:76
cpp_function::cpp_function
cpp_function(Return(Class::*f)(Arg...) &, const Extra &...extra)
Definition: pybind11.h:121
iterator
Definition: pytypes.h:1426
res
cout<< "Here is the matrix m:"<< endl<< m<< endl;Matrix< ptrdiff_t, 3, 1 > res
Definition: PartialRedux_count.cpp:3
size_in_ptrs
static constexpr size_t size_in_ptrs(size_t s)
Definition: wrap/pybind11/include/pybind11/detail/common.h:543
class_::def
class_ & def(const T &op, const Extra &...extra)
Definition: pybind11.h:1599
iterator_value_access::pair_type
decltype(*std::declval< Iterator & >()) pair_type
Definition: pybind11.h:2356
h
const double h
Definition: testSimpleHelicopter.cpp:19
Eigen::last
static const symbolic::SymbolExpr< internal::symbolic_last_tag > last
Definition: IndexedViewHelper.h:38
type_record::holder_size
size_t holder_size
How large is the type's holder?
Definition: attr.h:293
all_type_info
const std::vector< detail::type_info * > & all_type_info(PyTypeObject *type)
Definition: type_caster_base.h:169
internals::registered_exception_translators
std::forward_list< ExceptionTranslator > registered_exception_translators
Definition: internals.h:178
get_local_type_info
detail::type_info * get_local_type_info(const std::type_index &tp)
Definition: type_caster_base.h:196
register_exception_translator
void register_exception_translator(ExceptionTranslator &&translator)
Definition: pybind11.h:2512
result
Values result
Definition: OdometryOptimize.cpp:8
get_type_overload
function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name)
Definition: pybind11.h:2869
class_::init_holder_from_existing
static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::true_type)
Definition: pybind11.h:1828
is_method
Annotation for methods.
Definition: attr.h:24
enum_base::init
PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible)
Definition: pybind11.h:1958
class_< Type >::is_holder
detail::is_holder_type< Type, T > is_holder
Definition: pybind11.h:1498
class_::add_base
static void add_base(detail::type_record &rec)
Definition: pybind11.h:1564
weakref
Definition: pytypes.h:1850
object::PYBIND11_DEPRECATED
PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()") object(handle h
uint8_t
unsigned char uint8_t
Definition: ms_stdint.h:83
iterator_state::first_or_done
bool first_or_done
Definition: pybind11.h:2317
conditional_t
typename std::conditional< B, T, F >::type conditional_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:642
type_record::module_local
bool module_local
Is the class definition local to the module shared object?
Definition: attr.h:329
name
static char name[]
Definition: rgamma.c:72
enum_name
str enum_name(handle arg)
Definition: pybind11.h:1945
argument_record
Internal data structure which holds metadata about a keyword argument.
Definition: attr.h:178
type_record::default_holder
bool default_holder
Is the default (unique_ptr) holder type used?
Definition: attr.h:326
instance
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
Definition: wrap/pybind11/include/pybind11/detail/common.h:569
class_::def
class_ & def(const char *name_, Func &&f, const Extra &...extra)
Definition: pybind11.h:1574
type_name
string type_name()
Definition: benchmark-blocking-sizes.cpp:252
process_shonan_timing_results.args
args
Definition: process_shonan_timing_results.py:163
function_call
Internal data associated with a single function call.
Definition: cast.h:1394
argument_record::name
const char * name
Argument name.
Definition: attr.h:179
n
int n
Definition: BiCGSTAB_simple.cpp:1
sibling
Annotation indicating that a function is an overload associated with a given "sibling".
Definition: attr.h:57
is_pos_only
std::is_same< intrinsic_t< T >, pos_only > is_pos_only
Definition: cast.h:1388
argument_record::convert
bool convert
True if the argument is allowed to convert when loading.
Definition: attr.h:182
class_::def
class_ & def(detail::initimpl::pickle_factory< Args... > &&pf, const Extra &...extra)
Definition: pybind11.h:1631
doc
Annotation for documentation.
Definition: attr.h:45
PYBIND11_ENUM_OP_CONV
#define PYBIND11_ENUM_OP_CONV(op, expr)
type_record::multiple_inheritance
bool multiple_inheritance
Multiple inheritance marker.
Definition: attr.h:317
is_kw_only
std::is_same< intrinsic_t< T >, kw_only > is_kw_only
Definition: cast.h:1386
arg::name
const char * name
If non-null, this is a named kwargs argument.
Definition: cast.h:1296
class_< Type >
dict
Definition: pytypes.h:2065
exactly_one_t
typename exactly_one< Predicate, Default, Ts... >::type exactly_one_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:875
raise_from
void raise_from(PyObject *type, const char *message)
Definition: pytypes.h:780
get_fully_qualified_tp_name
std::string get_fully_qualified_tp_name(PyTypeObject *type)
Definition: class.h:28
get_function_record_capsule_name
const char * get_function_record_capsule_name()
Definition: internals.h:605
data
int data[]
Definition: Map_placement_new.cpp:1
error_already_set::m_fetched_error_deleter
static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr)
Definition: pybind11.h:2659
handle
Definition: pytypes.h:217
cpp_function::strdup_guard
Definition: pybind11.h:319
gil.h
type_caster
Definition: cast.h:38
all_type_info_get_cache
std::pair< decltype(internals::registered_types_py)::iterator, bool > all_type_info_get_cache(PyTypeObject *type)
Definition: pybind11.h:2273
cpp_function::InitializingFunctionRecordDeleter
Definition: pybind11.h:154
handle::cast
T cast() const
Definition: cast.h:1110
iterator_value_access::result_type
conditional_t< std::is_reference< decltype(*std::declval< Iterator & >())>::value, decltype(((*std::declval< Iterator & >()).second)), decltype(std::declval< pair_type >().second)> result_type
Definition: pybind11.h:2362
exception::operator()
void operator()(const char *message)
Definition: pybind11.h:2552
type::handle_of
static handle handle_of()
Definition: cast.h:1684
make_tuple
tuple make_tuple()
Definition: cast.h:1248
int64_t
signed __int64 int64_t
Definition: ms_stdint.h:94
internals::inactive_override_cache
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
Definition: internals.h:175
function_call::init_self
handle init_self
If this is a call to an initializer, this argument contains self
Definition: cast.h:1414
enum_::export_values
enum_ & export_values()
Export enumeration entries into the parent scope.
Definition: pybind11.h:2207
generic_type::install_buffer_funcs
void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *), void *get_buffer_data)
Definition: pybind11.h:1376
enum_::Underlying
typename std::underlying_type< Type >::type Underlying
Definition: pybind11.h:2177
init.h
make_iterator
iterator make_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator from a first and past-the-end C++ InputIterator.
Definition: pybind11.h:2409
return_value_policy_override::policy
static return_value_policy policy(return_value_policy p)
Definition: cast.h:999
class_::def_property_static
class_ & def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
Uses return_value_policy::reference by default.
Definition: pybind11.h:1765
get_override
function get_override(const T *this_ptr, const char *name)
Definition: pybind11.h:2774
enum_::enum_
enum_(const handle &scope, const char *name, const Extra &...extra)
Definition: pybind11.h:2185
return_value_policy::copy
@ copy
type_record::bases
list bases
List of base classes of the newly created type.
Definition: attr.h:305
args_are_all_keyword_or_ds
constexpr bool args_are_all_keyword_or_ds()
Definition: pytypes.h:2061
class_::def
class_ & def(const detail::initimpl::constructor< Args... > &init, const Extra &...extra)
Definition: pybind11.h:1611
extract_guard_t
typename exactly_one_t< is_call_guard, call_guard<>, Extra... >::type extract_guard_t
Extract the type from the first call_guard in Extras... (or void_type if none found)
Definition: attr.h:678
iterator_key_access::operator()
result_type operator()(Iterator &it) const
Definition: pybind11.h:2350
object::object
object()=default
object::release
handle release()
Definition: pytypes.h:368
class_::def_property_readonly_static
class_ & def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference by default.
Definition: pybind11.h:1722
class_::init_holder
static void init_holder(detail::instance *inst, detail::value_and_holder &v_h, const holder_type *holder_ptr, const void *)
Definition: pybind11.h:1844
pickle
detail::initimpl::pickle_factory< GetState, SetState > pickle(GetState &&g, SetState &&s)
Definition: pybind11.h:1939
enum_::Scalar
detail::conditional_t< detail::any_of< detail::is_std_char_type< Underlying >, std::is_same< Underlying, bool > >::value, detail::equivalent_integer_t< Underlying >, Underlying > Scalar
Definition: pybind11.h:2182
get_function
handle get_function(handle value)
Definition: pytypes.h:928
local_internals::registered_types_cpp
type_map< type_info * > registered_types_cpp
Definition: internals.h:545
iterator_key_access::pair_type
decltype(*std::declval< Iterator & >()) pair_type
Definition: pybind11.h:2334
cpp_function::strdup_guard::strings
std::vector< char * > strings
Definition: pybind11.h:338
type_record
Special data structure which (temporarily) holds metadata about a bound class.
Definition: attr.h:272
iterator_key_access
Definition: pybind11.h:2332
func
int func(const int &a)
Definition: testDSF.cpp:221
Eigen::Architecture::Type
Type
Definition: Constants.h:471
arg
Definition: cast.h:1277
PYBIND11_INSTANCE_METHOD_CHECK
#define PYBIND11_INSTANCE_METHOD_CHECK
Definition: wrap/pybind11/include/pybind11/detail/common.h:347
return_value_policy::reference
@ reference
PYBIND11_DETAILED_ERROR_MESSAGES
#define PYBIND11_DETAILED_ERROR_MESSAGES
Definition: wrap/pybind11/include/pybind11/detail/common.h:1251
process_attributes::postcall
static void postcall(function_call &call, handle fn_ret)
Definition: attr.h:664
conftest.capture
def capture(capsys)
Definition: conftest.py:138
function_record::is_constructor
bool is_constructor
True if name == 'init'.
Definition: attr.h:222
Eigen::internal::first
EIGEN_CONSTEXPR Index first(const T &x) EIGEN_NOEXCEPT
Definition: IndexedViewHelper.h:81
negation
Definition: wrap/pybind11/include/pybind11/detail/common.h:699
function_record::next
function_record * next
Pointer to next overload.
Definition: attr.h:268
class_::is_valid_class_option
Definition: pybind11.h:1505
get_type_info
PYBIND11_NOINLINE detail::type_info * get_type_info(PyTypeObject *type)
Definition: type_caster_base.h:184
make_value_iterator
iterator make_value_iterator(Iterator first, Sentinel last, Extra &&...extra)
Definition: pybind11.h:2441
PYBIND11_NAMESPACE
Definition: test_custom_type_casters.cpp:24
m
Matrix3f m
Definition: AngleAxis_mimic_euler.cpp:1
class_::init_holder
static void init_holder(detail::instance *inst, detail::value_and_holder &v_h, const holder_type *, const std::enable_shared_from_this< T > *)
Initialize holder object, variant 1: object derives from enable_shared_from_this.
Definition: pybind11.h:1810
Eigen::Triplet< double >
cpp_function
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
Definition: pybind11.h:82
arg
EIGEN_DEVICE_FUNC const EIGEN_STRONG_INLINE ArgReturnType arg() const
Definition: ArrayCwiseUnaryOps.h:66
int8_t
signed char int8_t
Definition: ms_stdint.h:80
enum_base::export_values
PYBIND11_NOINLINE void export_values()
Definition: pybind11.h:2116
gil_scoped_acquire
Definition: gil.h:215
dict_getitem
PyObject * dict_getitem(PyObject *v, PyObject *key)
Definition: pytypes.h:958
cpp_function::strdup_guard::strdup_guard
strdup_guard()=default
register_local_exception_translator
void register_local_exception_translator(ExceptionTranslator &&translator)
Definition: pybind11.h:2523
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1013
init
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
Definition: pybind11.h:1912
gtsam::symbol_shorthand::F
Key F(std::uint64_t j)
Definition: inference/Symbol.h:153
argument_record::none
bool none
True if None is allowed when loading.
Definition: attr.h:183
class_::def_buffer
class_ & def_buffer(Return(Class::*func)(Args...))
Definition: pybind11.h:1660
function_call::args_ref
object args_ref
Definition: cast.h:1408
size_t
std::size_t size_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:476
PYBIND11_TRY_NEXT_OVERLOAD
#define PYBIND11_TRY_NEXT_OVERLOAD
Definition: wrap/pybind11/include/pybind11/detail/common.h:373
pc
int RealScalar int RealScalar int RealScalar * pc
Definition: level1_cplx_impl.h:119
type_record::operator_new
void *(* operator_new)(size_t)
The global operator new can be overridden with a class-specific variant.
Definition: attr.h:296
g
void g(const string &key, int i)
Definition: testBTree.cpp:41
class_::def_property_static
class_ & def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
Definition: pybind11.h:1775
class_::def_property
class_ & def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
Definition: pybind11.h:1743
enum_base::enum_base
enum_base(const handle &base, const handle &parent)
Definition: pybind11.h:1956
cpp_function::InitializingFunctionRecordDeleter::operator()
void operator()(detail::function_record *rec)
Definition: pybind11.h:157
class_::init_holder_from_existing
static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::false_type)
Definition: pybind11.h:1835
iterator_access::operator()
result_type operator()(Iterator &it) const
Definition: pybind11.h:2328
is_function_record_capsule
bool is_function_record_capsule(const capsule &cap)
Definition: internals.h:619
str
Definition: pytypes.h:1524
key
const gtsam::Symbol key('X', 0)
class_::def_property_readonly
class_ & def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
Definition: pybind11.h:1715
tree::f
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
Definition: testExpression.cpp:218
generic_type::mark_parents_nonsimple
void mark_parents_nonsimple(PyTypeObject *value)
Helper function which tags all parents of a type using mult. inheritance.
Definition: pybind11.h:1365
function_record::is_operator
bool is_operator
True if this is an operator (add), etc.
Definition: attr.h:231
module_::def_submodule
module_ def_submodule(const char *name, const char *doc=nullptr)
Definition: pybind11.h:1192
error_already_set::what
const char * what() const noexcept override
Definition: pybind11.h:2665
get_object_handle
PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type)
Definition: type_caster_base.h:473
a
ArrayXXi a
Definition: Array_initializer_list_23_cxx11.cpp:1
PYBIND11_OBJECT_DEFAULT
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
Definition: pytypes.h:1411
apply_exception_translators
bool apply_exception_translators(std::forward_list< ExceptionTranslator > &translators)
Definition: pybind11.h:59
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100
#define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
Definition: wrap/pybind11/include/pybind11/detail/common.h:1217
conftest.scope
scope
Definition: conftest.py:27
PYBIND11_DESCR_CONSTEXPR
#define PYBIND11_DESCR_CONSTEXPR
Definition: descr.h:18
internals::direct_conversions
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
Definition: internals.h:176
module_::reload
void reload()
Reload the module or throws error_already_set.
Definition: pybind11.h:1220
C
Matrix< Scalar, Dynamic, Dynamic > C
Definition: bench_gemm.cpp:50
dict::contains
bool contains(T &&key) const
Definition: pytypes.h:2086
type_caster_generic::local_load
static PYBIND11_NOINLINE void * local_load(PyObject *src, const type_info *ti)
Definition: type_caster_base.h:642
handle::ptr
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:241
tuple::size
size_t size() const
Definition: pytypes.h:2046
class_::def_property
class_ & def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
Definition: pybind11.h:1756
type_record::dealloc
void(* dealloc)(detail::value_and_holder &)
Function pointer to class_<..>::dealloc.
Definition: attr.h:302
cpp_function::cpp_function
cpp_function(Func &&f, const Extra &...extra)
Construct a cpp_function from a lambda function (possibly with internal state)
Definition: pybind11.h:101
module_
Wrapper for Python extension modules.
Definition: pybind11.h:1153
PYBIND11_ENUM_OP_CONV_LHS
#define PYBIND11_ENUM_OP_CONV_LHS(op, expr)
PYBIND11_WARNING_DISABLE_MSVC
PYBIND11_WARNING_PUSH PYBIND11_WARNING_DISABLE_MSVC(5054) PYBIND11_WARNING_POP static_assert(EIGEN_VERSION_AT_LEAST(3
handle::handle
handle()=default
The default constructor creates a handle with a nullptr-valued pointer.
enum_base::m_base
handle m_base
Definition: pybind11.h:2123
dict::empty
bool empty() const
Definition: pytypes.h:2081
pm
Matrix4d pm
Definition: HessenbergDecomposition_packedMatrix.cpp:4
iterator_state::it
Iterator it
Definition: pybind11.h:2315
class_::init_instance
static void init_instance(detail::instance *inst, const void *holder_ptr)
Definition: pybind11.h:1861
Class
Definition: testExpression.cpp:116
make_key_iterator
iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra)
Definition: pybind11.h:2425
Eigen::TensorSycl::internal::write
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ::Eigen::internal::enable_if< dt !=data_source::global_mem, void >::type write(PacketType &packet_data, DataScalar ptr)
write, a template function used for storing the data to local memory. This function is used to guaran...
Definition: TensorContractionSycl.h:238
argument_loader
Helper class which loads arguments for C++ functions called from Python.
Definition: cast.h:1419
PYBIND11_ENUM_OP_STRICT
#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)
std
Definition: BFloat16.h:88
PYBIND11_COMPAT_STRDUP
#define PYBIND11_COMPAT_STRDUP
Definition: pybind11.h:76
void_type
Helper type to replace 'void' in some expressions.
Definition: wrap/pybind11/include/pybind11/detail/common.h:801
args
Definition: pytypes.h:2163
buffer_info
Information record describing a Python buffer object.
Definition: buffer_info.h:46
class_::def
class_ & def(detail::initimpl::factory< Args... > &&init, const Extra &...extra)
Definition: pybind11.h:1625
p
float * p
Definition: Tutorial_Map_using.cpp:9
c_str
const char * c_str(Args &&...args)
Definition: internals.h:599
get_local_internals
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
Definition: internals.h:584
add_class_method
void add_class_method(object &cls, const char *name_, const cpp_function &cf)
Definition: pybind11.h:1463
enum_base::m_parent
handle m_parent
Definition: pybind11.h:2124
class_::def_property_readonly
class_ & def_property_readonly(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
Definition: pybind11.h:1705
uint16_t
unsigned short uint16_t
Definition: ms_stdint.h:84
tuple
Definition: pytypes.h:2035
iterator_access
Definition: pybind11.h:2325
sep
std::string sep
Definition: IOFormat.cpp:1
is_pyobject
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
Definition: pytypes.h:72
options::show_function_signatures
static bool show_function_signatures()
Definition: options.h:66
register_local_exception
exception< CppException > & register_local_exception(handle scope, const char *name, handle base=PyExc_Exception)
Definition: pybind11.h:2614
class_::def
class_ & def(const detail::initimpl::alias_constructor< Args... > &init, const Extra &...extra)
Definition: pybind11.h:1618
handle::dec_ref
const handle & dec_ref() const &
Definition: pytypes.h:267
has_operator_delete_size
Definition: pybind11.h:1425
options::show_user_defined_docstrings
static bool show_user_defined_docstrings()
Definition: options.h:62
make_new_python_type
PyObject * make_new_python_type(const type_record &rec)
Definition: class.h:630
get_exception_object
exception< CppException > & get_exception_object()
Definition: pybind11.h:2560
if
if((m *x).isApprox(y))
Definition: FullPivLU_solve.cpp:6
type_record::type_align
size_t type_align
What is the alignment of the underlying C++ type?
Definition: attr.h:290
min
#define min(a, b)
Definition: datatypes.h:19
type_record::scope
handle scope
Handle to the parent scope.
Definition: attr.h:278
function
Definition: pytypes.h:2205
cpp_function::make_function_record
PYBIND11_NOINLINE unique_function_record make_function_record()
Space optimization: don't inline this frequently instantiated fragment.
Definition: pybind11.h:163
internals::registered_types_py
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
Definition: internals.h:172
generic_type::initialize
void initialize(const type_record &rec)
Definition: pybind11.h:1305
cpp_function::cpp_function
cpp_function(Return(Class::*f)(Arg...) const &, const Extra &...extra)
Definition: pybind11.h:143
int32_t
signed int int32_t
Definition: ms_stdint.h:82
type_record::type_size
size_t type_size
How large is the underlying C++ type?
Definition: attr.h:287
function_record::name
char * name
Function name.
Definition: attr.h:198
class_::def_property_readonly_static
class_ & def_property_readonly_static(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
Definition: pybind11.h:1729
set_operator_new
void set_operator_new(type_record *r)
Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
Definition: pybind11.h:1412
cpp_function::cpp_function
cpp_function(Return(*f)(Args...), const Extra &...extra)
Construct a cpp_function from a vanilla function pointer.
Definition: pybind11.h:92
uint64_t
unsigned __int64 uint64_t
Definition: ms_stdint.h:95
generic_type::def_property_static_impl
void def_property_static_impl(const char *name, handle fget, handle fset, detail::function_record *rec_func)
Definition: pybind11.h:1393
class_::def_buffer
class_ & def_buffer(Return(Class::*func)(Args...) const)
Definition: pybind11.h:1665
function_call::args
std::vector< handle > args
Arguments passed to the function:
Definition: cast.h:1401
class_::get_function_record
static detail::function_record * get_function_record(handle h)
Definition: pybind11.h:1889
object::cast
T cast() const &
Definition: cast.h:1169
conftest.doc
def doc()
Definition: conftest.py:174
PYBIND11_STD_LAUNDER
#define PYBIND11_STD_LAUNDER
Definition: pybind11.h:31
process_attributes::precall
static void precall(function_call &call)
Definition: attr.h:658
module_::def
module_ & def(const char *name_, Func &&f, const Extra &...extra)
Definition: pybind11.h:1169
Eigen::placeholders::end
static const EIGEN_DEPRECATED end_t end
Definition: IndexedViewHelper.h:181
globals
dict globals()
Definition: pybind11.h:1287
none
Definition: pytypes.h:1744
iterator_state
Definition: pybind11.h:2314
func
Definition: benchGeometry.cpp:23
method_adaptor
auto method_adaptor(F &&f) -> decltype(std::forward< F >(f))
Definition: pybind11.h:1475
loader_life_support
Definition: type_caster_base.h:34
align_3::t
Point2 t(10, 10)
equivalent_integer
Definition: pybind11.h:2128
function_call::kwargs_ref
object kwargs_ref
Definition: cast.h:1408
register_exception_impl
exception< CppException > & register_exception_impl(handle scope, const char *name, handle base, bool isLocal)
Definition: pybind11.h:2568
constexpr_first
constexpr int constexpr_first()
Definition: wrap/pybind11/include/pybind11/detail/common.h:839
process_attributes::init
static void init(const Args &...args, function_record *r)
Definition: attr.h:644
return_value_policy::automatic_reference
@ automatic_reference
init
Definition: TutorialInplaceLU.cpp:2
class_::def_static
class_ & def_static(const char *name_, Func &&f, const Extra &...extra)
Definition: pybind11.h:1585
gtsam.examples.ShonanAveragingCLI.str
str
Definition: ShonanAveragingCLI.py:115
enable_if_t
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
Definition: wrap/pybind11/include/pybind11/detail/common.h:640
matlab_wrap.file
file
Definition: matlab_wrap.py:57
gtsam::equal
bool equal(const T &obj1, const T &obj2, double tol)
Definition: Testable.h:85
init_alias
detail::initimpl::alias_constructor< Args... > init_alias()
Definition: pybind11.h:1918
options
Definition: options.h:16
test_callbacks.value
value
Definition: test_callbacks.py:158
make_iterator_impl
iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra)
Definition: pybind11.h:2372
i
int i
Definition: BiCGSTAB_step_by_step.cpp:9
register_instance
void register_instance(instance *self, void *valptr, const type_info *tinfo)
Definition: class.h:331
keep_alive_impl
PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient)
Definition: pybind11.h:2224
relicense.text
text
Definition: relicense.py:59
function_call::args_convert
std::vector< bool > args_convert
The convert value the arguments should be loaded with.
Definition: cast.h:1404
register_exception
exception< CppException > & register_exception(handle scope, const char *name, handle base=PyExc_Exception)
Definition: pybind11.h:2600
Eigen::internal::cast
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
Definition: Eigen/src/Core/MathFunctions.h:460
PYBIND11_INSTANCE_METHOD_NEW
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_)
Compatibility macros for Python 2 / Python 3 versions TODO: remove.
Definition: wrap/pybind11/include/pybind11/detail/common.h:346
cpp_function::cpp_function
cpp_function(std::nullptr_t, const is_setter &)
Definition: pybind11.h:87
remove_reference_t
typename std::remove_reference< T >::type remove_reference_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:646
class_::class_
class_(handle scope, const char *name, const Extra &...extra)
Definition: pybind11.h:1522
for
for(size_t i=1;i< poses.size();++i)
Definition: doc/Code/VisualISAMExample.cpp:7
cpp_function::strdup_guard::operator=
strdup_guard & operator=(const strdup_guard &)=delete
pybind_wrapper_test_script.inst
inst
Definition: pybind_wrapper_test_script.py:49
cpp_function::cpp_function
cpp_function(std::nullptr_t)
Definition: pybind11.h:86
call_operator_delete
void call_operator_delete(T *p, size_t, size_t)
Call class-specific delete if it exists or global otherwise. Can also be an overload set.
Definition: pybind11.h:1433
module_::create_extension_module
static module_ create_extension_module(const char *name, const char *doc, module_def *def)
Definition: pybind11.h:1252
has_operator_delete
Definition: pybind11.h:1420
make_changelog.state
state
Definition: make_changelog.py:28
type_record::type
const std::type_info * type
Definition: attr.h:284
pybind11.msg
msg
Definition: wrap/pybind11/pybind11/__init__.py:4
exception::exception
exception(handle scope, const char *name, handle base=PyExc_Exception)
Definition: pybind11.h:2539
cpp_function::cpp_function
cpp_function(Return(Class::*f)(Arg...) const, const Extra &...extra)
Construct a cpp_function from a class method (const, no ref-qualifier)
Definition: pybind11.h:131
repr
str repr(handle h)
Definition: pytypes.h:2420


gtsam
Author(s):
autogenerated on Thu Jun 13 2024 03:04:47