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


gtsam
Author(s):
autogenerated on Thu Apr 10 2025 03:02:59