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


gtsam
Author(s):
autogenerated on Thu Dec 19 2024 04:02:44