cppyabm  1.0.17
An agent-based library to integrate C++ and Python
pybind11.h
Go to the documentation of this file.
1 /*
2  pybind11/pybind11.h: Main header file of the C++11 python
3  binding generator library
4 
5  Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6 
7  All rights reserved. Use of this source code is governed by a
8  BSD-style license that can be found in the LICENSE file.
9 */
10 
11 #pragma once
12 
13 #if defined(__INTEL_COMPILER)
14 # pragma warning push
15 # pragma warning disable 68 // integer conversion resulted in a change of sign
16 # pragma warning disable 186 // pointless comparison of unsigned integer with zero
17 # pragma warning disable 878 // incompatible exception specifications
18 # pragma warning disable 1334 // the "template" keyword used for syntactic disambiguation may only be used within a template
19 # pragma warning disable 1682 // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem)
20 # pragma warning disable 1786 // function "strdup" was declared deprecated
21 # pragma warning disable 1875 // offsetof applied to non-POD (Plain Old Data) types is nonstandard
22 # pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
23 #elif defined(_MSC_VER)
24 # pragma warning(push)
25 # pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
26 # pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
27 # pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
28 # pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
29 # pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
30 # pragma warning(disable: 4702) // warning C4702: unreachable code
31 # pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
32 # pragma warning(disable: 4505) // warning C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
33 #elif defined(__GNUG__) && !defined(__clang__)
34 # pragma GCC diagnostic push
35 # pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
36 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
37 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
38 # pragma GCC diagnostic ignored "-Wstrict-aliasing"
39 # pragma GCC diagnostic ignored "-Wattributes"
40 # if __GNUC__ >= 7
41 # pragma GCC diagnostic ignored "-Wnoexcept-type"
42 # endif
43 #endif
44 
45 #include "attr.h"
46 #include "options.h"
47 #include "detail/class.h"
48 #include "detail/init.h"
49 
50 #include <memory>
51 #include <vector>
52 #include <string>
53 #include <utility>
54 
55 #if defined(__GNUG__) && !defined(__clang__)
56 # include <cxxabi.h>
57 #endif
58 
60 
61 /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
62 class cpp_function : public function {
63 public:
64  cpp_function() = default;
65  cpp_function(std::nullptr_t) { }
66 
67  /// Construct a cpp_function from a vanilla function pointer
68  template <typename Return, typename... Args, typename... Extra>
69  cpp_function(Return (*f)(Args...), const Extra&... extra) {
70  initialize(f, f, extra...);
71  }
72 
73  /// Construct a cpp_function from a lambda function (possibly with internal state)
74  template <typename Func, typename... Extra,
76  cpp_function(Func &&f, const Extra&... extra) {
77  initialize(std::forward<Func>(f),
78  (detail::function_signature_t<Func> *) nullptr, extra...);
79  }
80 
81  /// Construct a cpp_function from a class method (non-const, no ref-qualifier)
82  template <typename Return, typename Class, typename... Arg, typename... Extra>
83  cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
84  initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
85  (Return (*) (Class *, Arg...)) nullptr, extra...);
86  }
87 
88  /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier)
89  /// A copy of the overload for non-const functions without explicit ref-qualifier
90  /// but with an added `&`.
91  template <typename Return, typename Class, typename... Arg, typename... Extra>
92  cpp_function(Return (Class::*f)(Arg...)&, const Extra&... extra) {
93  initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
94  (Return (*) (Class *, Arg...)) nullptr, extra...);
95  }
96 
97  /// Construct a cpp_function from a class method (const, no ref-qualifier)
98  template <typename Return, typename Class, typename... Arg, typename... Extra>
99  cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
100  initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
101  (Return (*)(const Class *, Arg ...)) nullptr, extra...);
102  }
103 
104  /// Construct a cpp_function from a class method (const, lvalue ref-qualifier)
105  /// A copy of the overload for const functions without explicit ref-qualifier
106  /// but with an added `&`.
107  template <typename Return, typename Class, typename... Arg, typename... Extra>
108  cpp_function(Return (Class::*f)(Arg...) const&, const Extra&... extra) {
109  initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
110  (Return (*)(const Class *, Arg ...)) nullptr, extra...);
111  }
112 
113  /// Return the function name
114  object name() const { return attr("__name__"); }
115 
116 protected:
118  // `destruct(function_record, false)`: `initialize_generic` copies strings and
119  // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`.
120  void operator()(detail::function_record * rec) { destruct(rec, false); }
121  };
122  using unique_function_record = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
123 
124  /// Space optimization: don't inline this frequently instantiated fragment
126  return unique_function_record(new detail::function_record());
127  }
128 
129  /// Special internal constructor for functors, lambda functions, etc.
130  template <typename Func, typename Return, typename... Args, typename... Extra>
131  void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
132  using namespace detail;
133  struct capture { remove_reference_t<Func> f; };
134 
135  /* Store the function including any extra state it might have (e.g. a lambda capture object) */
136  // The unique_ptr makes sure nothing is leaked in case of an exception.
137  auto unique_rec = make_function_record();
138  auto rec = unique_rec.get();
139 
140  /* Store the capture object directly in the function record if there is enough space */
141  if (sizeof(capture) <= sizeof(rec->data)) {
142  /* Without these pragmas, GCC warns that there might not be
143  enough space to use the placement new operator. However, the
144  'if' statement above ensures that this is the case. */
145 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
146 # pragma GCC diagnostic push
147 # pragma GCC diagnostic ignored "-Wplacement-new"
148 #endif
149  new ((capture *) &rec->data) capture { std::forward<Func>(f) };
150 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
151 # pragma GCC diagnostic pop
152 #endif
154  rec->free_data = [](function_record *r) { ((capture *) &r->data)->~capture(); };
155  } else {
156  rec->data[0] = new capture { std::forward<Func>(f) };
157  rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
158  }
159 
160  /* Type casters for the function arguments and return value */
161  using cast_in = argument_loader<Args...>;
162  using cast_out = make_caster<
164  >;
165 
166  static_assert(expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
167  "The number of argument annotations does not match the number of function arguments");
168 
169  /* Dispatch code which converts function arguments and performs the actual function call */
170  rec->impl = [](function_call &call) -> handle {
171  cast_in args_converter;
172 
173  /* Try to cast the function arguments into the C++ domain */
174  if (!args_converter.load_args(call))
176 
177  /* Invoke call policy pre-call hook */
179 
180  /* Get a pointer to the capture object */
181  auto data = (sizeof(capture) <= sizeof(call.func.data)
182  ? &call.func.data : call.func.data[0]);
183  auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
184 
185  /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
187 
188  /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
189  using Guard = extract_guard_t<Extra...>;
190 
191  /* Perform the function call */
192  handle result = cast_out::cast(
193  std::move(args_converter).template call<Return, Guard>(cap->f), policy, call.parent);
194 
195  /* Invoke call policy post-call hook */
197 
198  return result;
199  };
200 
201  /* Process any user-provided function attributes */
202  process_attributes<Extra...>::init(extra..., rec);
203 
204  {
205  constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
206  has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
208  has_arg_annotations = any_of<is_keyword<Extra>...>::value;
209  static_assert(has_arg_annotations || !has_kw_only_args, "py::kw_only requires the use of argument annotations");
210  static_assert(has_arg_annotations || !has_pos_only_args, "py::pos_only requires the use of argument annotations (for docstrings and aligning the annotations to the argument)");
211  static_assert(!(has_args && has_kw_only_args), "py::kw_only cannot be combined with a py::args argument");
212  }
213 
214  /* Generate a readable signature describing the function's arguments and return value types */
215  static constexpr auto signature = _("(") + cast_in::arg_names + _(") -> ") + cast_out::name;
216  PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
217 
218  /* Register the function with Python from generic (non-templated) code */
219  // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid.
220  initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));
221 
222  if (cast_in::has_args) rec->has_args = true;
223  if (cast_in::has_kwargs) rec->has_kwargs = true;
224 
225  /* Stash some additional information used by an important optimization in 'functional.h' */
226  using FunctionType = Return (*)(Args...);
227  constexpr bool is_function_ptr =
229  sizeof(capture) == sizeof(void *);
230  if (is_function_ptr) {
231  rec->is_stateless = true;
232  rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
233  }
234  }
235 
236  // Utility class that keeps track of all duplicated strings, and cleans them up in its destructor,
237  // unless they are released. Basically a RAII-solution to deal with exceptions along the way.
238  class strdup_guard {
239  public:
241  for (auto s : strings)
242  std::free(s);
243  }
244  char *operator()(const char *s) {
245  auto t = strdup(s);
246  strings.push_back(t);
247  return t;
248  }
249  void release() {
250  strings.clear();
251  }
252  private:
253  std::vector<char *> strings;
254  };
255 
256  /// Register a function call with Python (generic non-templated code goes here)
257  void initialize_generic(unique_function_record &&unique_rec, const char *text,
258  const std::type_info *const *types, size_t args) {
259  // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr,
260  // we do not want this to destuct the pointer. `initialize` (the caller) still relies on the
261  // pointee being alive after this call. Only move out if a `capsule` is going to keep it alive.
262  auto rec = unique_rec.get();
263 
264  // Keep track of strdup'ed strings, and clean them up as long as the function's capsule
265  // has not taken ownership yet (when `unique_rec.release()` is called).
266  // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the strings
267  // are only referenced before strdup'ing. So only *after* the following block could `destruct`
268  // safely be called, but even then, `repr` could still throw in the middle of copying all strings.
269  strdup_guard guarded_strdup;
270 
271  /* Create copies of all referenced C-style strings */
272  rec->name = guarded_strdup(rec->name ? rec->name : "");
273  if (rec->doc) rec->doc = guarded_strdup(rec->doc);
274  for (auto &a: rec->args) {
275  if (a.name)
276  a.name = guarded_strdup(a.name);
277  if (a.descr)
278  a.descr = guarded_strdup(a.descr);
279  else if (a.value)
280  a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());
281  }
282 
283  rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
284 
285 #if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
286  if (rec->is_constructor && !rec->is_new_style_constructor) {
287  const auto class_name = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
288  const auto func_name = std::string(rec->name);
289  PyErr_WarnEx(
290  PyExc_FutureWarning,
291  ("pybind11-bound class '" + class_name + "' is using an old-style "
292  "placement-new '" + func_name + "' which has been deprecated. See "
293  "the upgrade guide in pybind11's docs. This message is only visible "
294  "when compiled in debug mode.").c_str(), 0
295  );
296  }
297 #endif
298 
299  /* Generate a proper function signature */
300  std::string signature;
301  size_t type_index = 0, arg_index = 0;
302  for (auto *pc = text; *pc != '\0'; ++pc) {
303  const auto c = *pc;
304 
305  if (c == '{') {
306  // Write arg name for everything except *args and **kwargs.
307  if (*(pc + 1) == '*')
308  continue;
309  // Separator for keyword-only arguments, placed before the kw
310  // arguments start
311  if (rec->nargs_kw_only > 0 && arg_index + rec->nargs_kw_only == args)
312  signature += "*, ";
313  if (arg_index < rec->args.size() && rec->args[arg_index].name) {
314  signature += rec->args[arg_index].name;
315  } else if (arg_index == 0 && rec->is_method) {
316  signature += "self";
317  } else {
318  signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
319  }
320  signature += ": ";
321  } else if (c == '}') {
322  // Write default value if available.
323  if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
324  signature += " = ";
325  signature += rec->args[arg_index].descr;
326  }
327  // Separator for positional-only arguments (placed after the
328  // argument, rather than before like *
329  if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only)
330  signature += ", /";
331  arg_index++;
332  } else if (c == '%') {
333  const std::type_info *t = types[type_index++];
334  if (!t)
335  pybind11_fail("Internal error while parsing type signature (1)");
336  if (auto tinfo = detail::get_type_info(*t)) {
337  handle th((PyObject *) tinfo->type);
338  signature +=
339  th.attr("__module__").cast<std::string>() + "." +
340  th.attr("__qualname__").cast<std::string>(); // Python 3.3+, but we backport it to earlier versions
341  } else if (rec->is_new_style_constructor && arg_index == 0) {
342  // A new-style `__init__` takes `self` as `value_and_holder`.
343  // Rewrite it to the proper class type.
344  signature +=
345  rec->scope.attr("__module__").cast<std::string>() + "." +
346  rec->scope.attr("__qualname__").cast<std::string>();
347  } else {
348  std::string tname(t->name());
349  detail::clean_type_id(tname);
350  signature += tname;
351  }
352  } else {
353  signature += c;
354  }
355  }
356 
357  if (arg_index != args || types[type_index] != nullptr)
358  pybind11_fail("Internal error while parsing type signature (2)");
359 
360 #if PY_MAJOR_VERSION < 3
361  if (strcmp(rec->name, "__next__") == 0) {
362  std::free(rec->name);
363  rec->name = guarded_strdup("next");
364  } else if (strcmp(rec->name, "__bool__") == 0) {
365  std::free(rec->name);
366  rec->name = guarded_strdup("__nonzero__");
367  }
368 #endif
369  rec->signature = guarded_strdup(signature.c_str());
370  rec->args.shrink_to_fit();
371  rec->nargs = (std::uint16_t) args;
372 
373  if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr()))
374  rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
375 
376  detail::function_record *chain = nullptr, *chain_start = rec;
377  if (rec->sibling) {
378  if (PyCFunction_Check(rec->sibling.ptr())) {
379  auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
380  chain = (detail::function_record *) rec_capsule;
381  /* Never append a method to an overload chain of a parent class;
382  instead, hide the parent's overloads in this case */
383  if (!chain->scope.is(rec->scope))
384  chain = nullptr;
385  }
386  // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
387  else if (!rec->sibling.is_none() && rec->name[0] != '_')
388  pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
389  "\" with a function of the same name");
390  }
391 
392  if (!chain) {
393  /* No existing overload was found, create a new function object */
394  rec->def = new PyMethodDef();
395  std::memset(rec->def, 0, sizeof(PyMethodDef));
396  rec->def->ml_name = rec->name;
397  rec->def->ml_meth = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(*dispatcher));
398  rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
399 
400  capsule rec_capsule(unique_rec.release(), [](void *ptr) {
401  destruct((detail::function_record *) ptr);
402  });
403  guarded_strdup.release();
404 
405  object scope_module;
406  if (rec->scope) {
407  if (hasattr(rec->scope, "__module__")) {
408  scope_module = rec->scope.attr("__module__");
409  } else if (hasattr(rec->scope, "__name__")) {
410  scope_module = rec->scope.attr("__name__");
411  }
412  }
413 
414  m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
415  if (!m_ptr)
416  pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
417  } else {
418  /* Append at the beginning or end of the overload chain */
419  m_ptr = rec->sibling.ptr();
420  inc_ref();
421  if (chain->is_method != rec->is_method)
422  pybind11_fail("overloading a method with both static and instance methods is not supported; "
423  #if defined(NDEBUG)
424  "compile in debug mode for more details"
425  #else
426  "error while attempting to bind " + std::string(rec->is_method ? "instance" : "static") + " method " +
427  std::string(pybind11::str(rec->scope.attr("__name__"))) + "." + std::string(rec->name) + signature
428  #endif
429  );
430 
431  if (rec->prepend) {
432  // Beginning of chain; we need to replace the capsule's current head-of-the-chain
433  // pointer with this one, then make this one point to the previous head of the
434  // chain.
435  chain_start = rec;
436  rec->next = chain;
437  auto rec_capsule = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self);
438  rec_capsule.set_pointer(unique_rec.release());
439  guarded_strdup.release();
440  } else {
441  // Or end of chain (normal behavior)
442  chain_start = chain;
443  while (chain->next)
444  chain = chain->next;
445  chain->next = unique_rec.release();
446  guarded_strdup.release();
447  }
448  }
449 
450  std::string signatures;
451  int index = 0;
452  /* Create a nice pydoc rec including all signatures and
453  docstrings of the functions in the overload chain */
454  if (chain && options::show_function_signatures()) {
455  // First a generic signature
456  signatures += rec->name;
457  signatures += "(*args, **kwargs)\n";
458  signatures += "Overloaded function.\n\n";
459  }
460  // Then specific overload signatures
461  bool first_user_def = true;
462  for (auto it = chain_start; it != nullptr; it = it->next) {
464  if (index > 0) signatures += "\n";
465  if (chain)
466  signatures += std::to_string(++index) + ". ";
467  signatures += rec->name;
468  signatures += it->signature;
469  signatures += "\n";
470  }
471  if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
472  // If we're appending another docstring, and aren't printing function signatures, we
473  // need to append a newline first:
475  if (first_user_def) first_user_def = false;
476  else signatures += "\n";
477  }
478  if (options::show_function_signatures()) signatures += "\n";
479  signatures += it->doc;
480  if (options::show_function_signatures()) signatures += "\n";
481  }
482  }
483 
484  /* Install docstring */
485  auto *func = (PyCFunctionObject *) m_ptr;
486  std::free(const_cast<char *>(func->m_ml->ml_doc));
487  // Install docstring if it's non-empty (when at least one option is enabled)
488  func->m_ml->ml_doc = signatures.empty() ? nullptr : strdup(signatures.c_str());
489 
490  if (rec->is_method) {
491  m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
492  if (!m_ptr)
493  pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
494  Py_DECREF(func);
495  }
496  }
497 
498  /// When a cpp_function is GCed, release any memory allocated by pybind11
499  static void destruct(detail::function_record *rec, bool free_strings = true) {
500  // If on Python 3.9, check the interpreter "MICRO" (patch) version.
501  // If this is running on 3.9.0, we have to work around a bug.
502  #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
503  static bool is_zero = Py_GetVersion()[4] == '0';
504  #endif
505 
506  while (rec) {
507  detail::function_record *next = rec->next;
508  if (rec->free_data)
509  rec->free_data(rec);
510  // During initialization, these strings might not have been copied yet,
511  // so they cannot be freed. Once the function has been created, they can.
512  // Check `make_function_record` for more details.
513  if (free_strings) {
514  std::free((char *) rec->name);
515  std::free((char *) rec->doc);
516  std::free((char *) rec->signature);
517  for (auto &arg: rec->args) {
518  std::free(const_cast<char *>(arg.name));
519  std::free(const_cast<char *>(arg.descr));
520  }
521  }
522  for (auto &arg: rec->args)
523  arg.value.dec_ref();
524  if (rec->def) {
525  std::free(const_cast<char *>(rec->def->ml_doc));
526  // Python 3.9.0 decref's these in the wrong order; rec->def
527  // If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)
528  // See https://github.com/python/cpython/pull/22670
529  #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
530  if (!is_zero)
531  delete rec->def;
532  #else
533  delete rec->def;
534  #endif
535  }
536  delete rec;
537  rec = next;
538  }
539  }
540 
541  /// Main dispatch logic for calls to functions bound using pybind11
542  static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
543  using namespace detail;
544 
545  /* Iterator over the list of potentially admissible overloads */
546  const function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
547  *it = overloads;
548 
549  /* Need to know how many arguments + keyword arguments there are to pick the right overload */
550  const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
551 
552  handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
554 
555  auto self_value_and_holder = value_and_holder();
556  if (overloads->is_constructor) {
557  if (!PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
558  PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid `self` argument");
559  return nullptr;
560  }
561 
562  const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
563  const auto pi = reinterpret_cast<instance *>(parent.ptr());
564  self_value_and_holder = pi->get_value_and_holder(tinfo, true);
565 
566  // If this value is already registered it must mean __init__ is invoked multiple times;
567  // we really can't support that in C++, so just ignore the second __init__.
568  if (self_value_and_holder.instance_registered())
569  return none().release().ptr();
570  }
571 
572  try {
573  // We do this in two passes: in the first pass, we load arguments with `convert=false`;
574  // in the second, we allow conversion (except for arguments with an explicit
575  // py::arg().noconvert()). This lets us prefer calls without conversion, with
576  // conversion as a fallback.
577  std::vector<function_call> second_pass;
578 
579  // However, if there are no overloads, we can just skip the no-convert pass entirely
580  const bool overloaded = it != nullptr && it->next != nullptr;
581 
582  for (; it != nullptr; it = it->next) {
583 
584  /* For each overload:
585  1. Copy all positional arguments we were given, also checking to make sure that
586  named positional arguments weren't *also* specified via kwarg.
587  2. If we weren't given enough, try to make up the omitted ones by checking
588  whether they were provided by a kwarg matching the `py::arg("name")` name. If
589  so, use it (and remove it from kwargs; if not, see if the function binding
590  provided a default that we can use.
591  3. Ensure that either all keyword arguments were "consumed", or that the function
592  takes a kwargs argument to accept unconsumed kwargs.
593  4. Any positional arguments still left get put into a tuple (for args), and any
594  leftover kwargs get put into a dict.
595  5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
596  extra tuple or dict at the end of the positional arguments.
597  6. Call the function call dispatcher (function_record::impl)
598 
599  If one of these fail, move on to the next overload and keep trying until we get a
600  result other than PYBIND11_TRY_NEXT_OVERLOAD.
601  */
602 
603  const function_record &func = *it;
604  size_t num_args = func.nargs; // Number of positional arguments that we need
605  if (func.has_args) --num_args; // (but don't count py::args
606  if (func.has_kwargs) --num_args; // or py::kwargs)
607  size_t pos_args = num_args - func.nargs_kw_only;
608 
609  if (!func.has_args && n_args_in > pos_args)
610  continue; // Too many positional arguments for this overload
611 
612  if (n_args_in < pos_args && func.args.size() < pos_args)
613  continue; // Not enough positional arguments given, and not enough defaults to fill in the blanks
614 
615  function_call call(func, parent);
616 
617  size_t args_to_copy = (std::min)(pos_args, n_args_in); // Protect std::min with parentheses
618  size_t args_copied = 0;
619 
620  // 0. Inject new-style `self` argument
621  if (func.is_new_style_constructor) {
622  // The `value` may have been preallocated by an old-style `__init__`
623  // if it was a preceding candidate for overload resolution.
624  if (self_value_and_holder)
625  self_value_and_holder.type->dealloc(self_value_and_holder);
626 
627  call.init_self = PyTuple_GET_ITEM(args_in, 0);
628  call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
629  call.args_convert.push_back(false);
630  ++args_copied;
631  }
632 
633  // 1. Copy any position arguments given.
634  bool bad_arg = false;
635  for (; args_copied < args_to_copy; ++args_copied) {
636  const argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
637  if (kwargs_in && arg_rec && arg_rec->name && PyDict_GetItemString(kwargs_in, arg_rec->name)) {
638  bad_arg = true;
639  break;
640  }
641 
642  handle arg(PyTuple_GET_ITEM(args_in, args_copied));
643  if (arg_rec && !arg_rec->none && arg.is_none()) {
644  bad_arg = true;
645  break;
646  }
647  call.args.push_back(arg);
648  call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
649  }
650  if (bad_arg)
651  continue; // Maybe it was meant for another overload (issue #688)
652 
653  // We'll need to copy this if we steal some kwargs for defaults
654  dict kwargs = reinterpret_borrow<dict>(kwargs_in);
655 
656  // 1.5. Fill in any missing pos_only args from defaults if they exist
657  if (args_copied < func.nargs_pos_only) {
658  for (; args_copied < func.nargs_pos_only; ++args_copied) {
659  const auto &arg_rec = func.args[args_copied];
660  handle value;
661 
662  if (arg_rec.value) {
663  value = arg_rec.value;
664  }
665  if (value) {
666  call.args.push_back(value);
667  call.args_convert.push_back(arg_rec.convert);
668  } else
669  break;
670  }
671 
672  if (args_copied < func.nargs_pos_only)
673  continue; // Not enough defaults to fill the positional arguments
674  }
675 
676  // 2. Check kwargs and, failing that, defaults that may help complete the list
677  if (args_copied < num_args) {
678  bool copied_kwargs = false;
679 
680  for (; args_copied < num_args; ++args_copied) {
681  const auto &arg_rec = func.args[args_copied];
682 
683  handle value;
684  if (kwargs_in && arg_rec.name)
685  value = PyDict_GetItemString(kwargs.ptr(), arg_rec.name);
686 
687  if (value) {
688  // Consume a kwargs value
689  if (!copied_kwargs) {
690  kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
691  copied_kwargs = true;
692  }
693  PyDict_DelItemString(kwargs.ptr(), arg_rec.name);
694  } else if (arg_rec.value) {
695  value = arg_rec.value;
696  }
697 
698  if (!arg_rec.none && value.is_none()) {
699  break;
700  }
701 
702  if (value) {
703  call.args.push_back(value);
704  call.args_convert.push_back(arg_rec.convert);
705  }
706  else
707  break;
708  }
709 
710  if (args_copied < num_args)
711  continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments
712  }
713 
714  // 3. Check everything was consumed (unless we have a kwargs arg)
715  if (kwargs && !kwargs.empty() && !func.has_kwargs)
716  continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
717 
718  // 4a. If we have a py::args argument, create a new tuple with leftovers
719  if (func.has_args) {
720  tuple extra_args;
721  if (args_to_copy == 0) {
722  // We didn't copy out any position arguments from the args_in tuple, so we
723  // can reuse it directly without copying:
724  extra_args = reinterpret_borrow<tuple>(args_in);
725  } else if (args_copied >= n_args_in) {
726  extra_args = tuple(0);
727  } else {
728  size_t args_size = n_args_in - args_copied;
729  extra_args = tuple(args_size);
730  for (size_t i = 0; i < args_size; ++i) {
731  extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i);
732  }
733  }
734  call.args.push_back(extra_args);
735  call.args_convert.push_back(false);
736  call.args_ref = std::move(extra_args);
737  }
738 
739  // 4b. If we have a py::kwargs, pass on any remaining kwargs
740  if (func.has_kwargs) {
741  if (!kwargs.ptr())
742  kwargs = dict(); // If we didn't get one, send an empty one
743  call.args.push_back(kwargs);
744  call.args_convert.push_back(false);
745  call.kwargs_ref = std::move(kwargs);
746  }
747 
748  // 5. Put everything in a vector. Not technically step 5, we've been building it
749  // in `call.args` all along.
750  #if !defined(NDEBUG)
751  if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
752  pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
753  #endif
754 
755  std::vector<bool> second_pass_convert;
756  if (overloaded) {
757  // We're in the first no-convert pass, so swap out the conversion flags for a
758  // set of all-false flags. If the call fails, we'll swap the flags back in for
759  // the conversion-allowed call below.
760  second_pass_convert.resize(func.nargs, false);
761  call.args_convert.swap(second_pass_convert);
762  }
763 
764  // 6. Call the function.
765  try {
766  loader_life_support guard{};
767  result = func.impl(call);
768  } catch (reference_cast_error &) {
770  }
771 
772  if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
773  break;
774 
775  if (overloaded) {
776  // The (overloaded) call failed; if the call has at least one argument that
777  // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
778  // then add this call to the list of second pass overloads to try.
779  for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
780  if (second_pass_convert[i]) {
781  // Found one: swap the converting flags back in and store the call for
782  // the second pass.
783  call.args_convert.swap(second_pass_convert);
784  second_pass.push_back(std::move(call));
785  break;
786  }
787  }
788  }
789  }
790 
791  if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
792  // The no-conversion pass finished without success, try again with conversion allowed
793  for (auto &call : second_pass) {
794  try {
795  loader_life_support guard{};
796  result = call.func.impl(call);
797  } catch (reference_cast_error &) {
799  }
800 
801  if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
802  // The error reporting logic below expects 'it' to be valid, as it would be
803  // if we'd encountered this failure in the first-pass loop.
804  if (!result)
805  it = &call.func;
806  break;
807  }
808  }
809  }
810  } catch (error_already_set &e) {
811  e.restore();
812  return nullptr;
813 #ifdef __GLIBCXX__
814  } catch ( abi::__forced_unwind& ) {
815  throw;
816 #endif
817  } catch (...) {
818  /* When an exception is caught, give each registered exception
819  translator a chance to translate it to a Python exception
820  in reverse order of registration.
821 
822  A translator may choose to do one of the following:
823 
824  - catch the exception and call PyErr_SetString or PyErr_SetObject
825  to set a standard (or custom) Python exception, or
826  - do nothing and let the exception fall through to the next translator, or
827  - delegate translation to the next translator by throwing a new type of exception. */
828 
829  auto last_exception = std::current_exception();
830  auto &registered_exception_translators = get_internals().registered_exception_translators;
831  for (auto& translator : registered_exception_translators) {
832  try {
833  translator(last_exception);
834  } catch (...) {
835  last_exception = std::current_exception();
836  continue;
837  }
838  return nullptr;
839  }
840  PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
841  return nullptr;
842  }
843 
844  auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
845  if (msg.find("std::") != std::string::npos) {
846  msg += "\n\n"
847  "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
848  "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
849  "conversions are optional and require extra headers to be included\n"
850  "when compiling your pybind11 module.";
851  }
852  };
853 
854  if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
855  if (overloads->is_operator)
856  return handle(Py_NotImplemented).inc_ref().ptr();
857 
858  std::string msg = std::string(overloads->name) + "(): incompatible " +
859  std::string(overloads->is_constructor ? "constructor" : "function") +
860  " arguments. The following argument types are supported:\n";
861 
862  int ctr = 0;
863  for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
864  msg += " "+ std::to_string(++ctr) + ". ";
865 
866  bool wrote_sig = false;
867  if (overloads->is_constructor) {
868  // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
869  std::string sig = it2->signature;
870  size_t start = sig.find('(') + 7; // skip "(self: "
871  if (start < sig.size()) {
872  // End at the , for the next argument
873  size_t end = sig.find(", "), next = end + 2;
874  size_t ret = sig.rfind(" -> ");
875  // Or the ), if there is no comma:
876  if (end >= sig.size()) next = end = sig.find(')');
877  if (start < end && next < sig.size()) {
878  msg.append(sig, start, end - start);
879  msg += '(';
880  msg.append(sig, next, ret - next);
881  wrote_sig = true;
882  }
883  }
884  }
885  if (!wrote_sig) msg += it2->signature;
886 
887  msg += "\n";
888  }
889  msg += "\nInvoked with: ";
890  auto args_ = reinterpret_borrow<tuple>(args_in);
891  bool some_args = false;
892  for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
893  if (!some_args) some_args = true;
894  else msg += ", ";
895  try {
896  msg += pybind11::repr(args_[ti]);
897  } catch (const error_already_set&) {
898  msg += "<repr raised Error>";
899  }
900  }
901  if (kwargs_in) {
902  auto kwargs = reinterpret_borrow<dict>(kwargs_in);
903  if (!kwargs.empty()) {
904  if (some_args) msg += "; ";
905  msg += "kwargs: ";
906  bool first = true;
907  for (auto kwarg : kwargs) {
908  if (first) first = false;
909  else msg += ", ";
910  msg += pybind11::str("{}=").format(kwarg.first);
911  try {
912  msg += pybind11::repr(kwarg.second);
913  } catch (const error_already_set&) {
914  msg += "<repr raised Error>";
915  }
916  }
917  }
918  }
919 
920  append_note_if_missing_header_is_suspected(msg);
921  PyErr_SetString(PyExc_TypeError, msg.c_str());
922  return nullptr;
923  } else if (!result) {
924  std::string msg = "Unable to convert function return value to a "
925  "Python type! The signature was\n\t";
926  msg += it->signature;
927  append_note_if_missing_header_is_suspected(msg);
928  PyErr_SetString(PyExc_TypeError, msg.c_str());
929  return nullptr;
930  } else {
931  if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
932  auto *pi = reinterpret_cast<instance *>(parent.ptr());
933  self_value_and_holder.type->init_instance(pi, nullptr);
934  }
935  return result.ptr();
936  }
937  }
938 };
939 
940 /// Wrapper for Python extension modules
941 class module_ : public object {
942 public:
943  PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)
944 
945  /// Create a new top-level Python module with the given name and docstring
946  PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead")
947  explicit module_(const char *name, const char *doc = nullptr) {
948 #if PY_MAJOR_VERSION >= 3
949  *this = create_extension_module(name, doc, new PyModuleDef());
950 #else
951  *this = create_extension_module(name, doc, nullptr);
952 #endif
953  }
954 
955  /** \rst
956  Create Python binding for a new function within the module scope. ``Func``
957  can be a plain C++ function, a function pointer, or a lambda function. For
958  details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
959  \endrst */
960  template <typename Func, typename... Extra>
961  module_ &def(const char *name_, Func &&f, const Extra& ... extra) {
962  cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
963  sibling(getattr(*this, name_, none())), extra...);
964  // NB: allow overwriting here because cpp_function sets up a chain with the intention of
965  // overwriting (and has already checked internally that it isn't overwriting non-functions).
966  add_object(name_, func, true /* overwrite */);
967  return *this;
968  }
969 
970  /** \rst
971  Create and return a new Python submodule with the given name and docstring.
972  This also works recursively, i.e.
973 
974  .. code-block:: cpp
975 
976  py::module_ m("example", "pybind11 example plugin");
977  py::module_ m2 = m.def_submodule("sub", "A submodule of 'example'");
978  py::module_ m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
979  \endrst */
980  module_ def_submodule(const char *name, const char *doc = nullptr) {
981  std::string full_name = std::string(PyModule_GetName(m_ptr))
982  + std::string(".") + std::string(name);
983  auto result = reinterpret_borrow<module_>(PyImport_AddModule(full_name.c_str()));
985  result.attr("__doc__") = pybind11::str(doc);
986  attr(name) = result;
987  return result;
988  }
989 
990  /// Import and return a module or throws `error_already_set`.
991  static module_ import(const char *name) {
992  PyObject *obj = PyImport_ImportModule(name);
993  if (!obj)
994  throw error_already_set();
995  return reinterpret_steal<module_>(obj);
996  }
997 
998  /// Reload the module or throws `error_already_set`.
999  void reload() {
1000  PyObject *obj = PyImport_ReloadModule(ptr());
1001  if (!obj)
1002  throw error_already_set();
1003  *this = reinterpret_steal<module_>(obj);
1004  }
1005 
1006  /** \rst
1007  Adds an object to the module using the given name. Throws if an object with the given name
1008  already exists.
1009 
1010  ``overwrite`` should almost always be false: attempting to overwrite objects that pybind11 has
1011  established will, in most cases, break things.
1012  \endrst */
1013  PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
1014  if (!overwrite && hasattr(*this, name))
1015  pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
1016  std::string(name) + "\"");
1017 
1018  PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
1019  }
1020 
1021 #if PY_MAJOR_VERSION >= 3
1022  using module_def = PyModuleDef;
1023 #else
1024  struct module_def {};
1025 #endif
1026 
1027  /** \rst
1028  Create a new top-level module that can be used as the main module of a C extension.
1029 
1030  For Python 3, ``def`` should point to a statically allocated module_def.
1031  For Python 2, ``def`` can be a nullptr and is completely ignored.
1032  \endrst */
1033  static module_ create_extension_module(const char *name, const char *doc, module_def *def) {
1034 #if PY_MAJOR_VERSION >= 3
1035  // module_def is PyModuleDef
1036  def = new (def) PyModuleDef { // Placement new (not an allocation).
1037  /* m_base */ PyModuleDef_HEAD_INIT,
1038  /* m_name */ name,
1039  /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr,
1040  /* m_size */ -1,
1041  /* m_methods */ nullptr,
1042  /* m_slots */ nullptr,
1043  /* m_traverse */ nullptr,
1044  /* m_clear */ nullptr,
1045  /* m_free */ nullptr
1046  };
1047  auto m = PyModule_Create(def);
1048 #else
1049  // Ignore module_def *def; only necessary for Python 3
1050  (void) def;
1051  auto m = Py_InitModule3(name, nullptr, options::show_user_defined_docstrings() ? doc : nullptr);
1052 #endif
1053  if (m == nullptr) {
1054  if (PyErr_Occurred())
1055  throw error_already_set();
1056  pybind11_fail("Internal error in module_::create_extension_module()");
1057  }
1058  // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when returned from PyInit_...
1059  // For Python 2, reinterpret_borrow is correct.
1060  return reinterpret_borrow<module_>(m);
1061  }
1062 };
1063 
1064 // When inside a namespace (or anywhere as long as it's not the first item on a line),
1065 // C++20 allows "module" to be used. This is provided for backward compatibility, and for
1066 // simplicity, if someone wants to use py::module for example, that is perfectly safe.
1067 using module = module_;
1068 
1069 /// \ingroup python_builtins
1070 /// Return a dictionary representing the global variables in the current execution frame,
1071 /// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
1072 inline dict globals() {
1073  PyObject *p = PyEval_GetGlobals();
1074  return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
1075 }
1076 
1078 /// Generic support for creating new Python heap types
1079 class generic_type : public object {
1080 public:
1081  PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
1082 protected:
1083  void initialize(const type_record &rec) {
1084  if (rec.scope && hasattr(rec.scope, "__dict__") && rec.scope.attr("__dict__").contains(rec.name))
1085  pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
1086  "\": an object with that name is already defined");
1087 
1089  pybind11_fail("generic_type: type \"" + std::string(rec.name) +
1090  "\" is already registered!");
1091 
1092  m_ptr = make_new_python_type(rec);
1093 
1094  /* Register supplemental type information in C++ dict */
1095  auto *tinfo = new detail::type_info();
1096  tinfo->type = (PyTypeObject *) m_ptr;
1097  tinfo->cpptype = rec.type;
1098  tinfo->type_size = rec.type_size;
1099  tinfo->type_align = rec.type_align;
1100  tinfo->operator_new = rec.operator_new;
1101  tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
1102  tinfo->init_instance = rec.init_instance;
1103  tinfo->dealloc = rec.dealloc;
1104  tinfo->simple_type = true;
1105  tinfo->simple_ancestors = true;
1106  tinfo->default_holder = rec.default_holder;
1107  tinfo->module_local = rec.module_local;
1108 
1109  auto &internals = get_internals();
1110  auto tindex = std::type_index(*rec.type);
1111  tinfo->direct_conversions = &internals.direct_conversions[tindex];
1112  if (rec.module_local)
1113  registered_local_types_cpp()[tindex] = tinfo;
1114  else
1115  internals.registered_types_cpp[tindex] = tinfo;
1116  internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo };
1117 
1118  if (rec.bases.size() > 1 || rec.multiple_inheritance) {
1119  mark_parents_nonsimple(tinfo->type);
1120  tinfo->simple_ancestors = false;
1121  }
1122  else if (rec.bases.size() == 1) {
1123  auto parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
1124  tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
1125  }
1126 
1127  if (rec.module_local) {
1128  // Stash the local typeinfo and loader so that external modules can access it.
1129  tinfo->module_local_load = &type_caster_generic::local_load;
1130  setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
1131  }
1132  }
1133 
1134  /// Helper function which tags all parents of a type using mult. inheritance
1135  void mark_parents_nonsimple(PyTypeObject *value) {
1136  auto t = reinterpret_borrow<tuple>(value->tp_bases);
1137  for (handle h : t) {
1138  auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
1139  if (tinfo2)
1140  tinfo2->simple_type = false;
1141  mark_parents_nonsimple((PyTypeObject *) h.ptr());
1142  }
1143  }
1144 
1146  buffer_info *(*get_buffer)(PyObject *, void *),
1147  void *get_buffer_data) {
1148  auto *type = (PyHeapTypeObject*) m_ptr;
1149  auto tinfo = detail::get_type_info(&type->ht_type);
1150 
1151  if (!type->ht_type.tp_as_buffer)
1152  pybind11_fail(
1153  "To be able to register buffer protocol support for the type '" +
1154  get_fully_qualified_tp_name(tinfo->type) +
1155  "' the associated class<>(..) invocation must "
1156  "include the pybind11::buffer_protocol() annotation!");
1157 
1158  tinfo->get_buffer = get_buffer;
1159  tinfo->get_buffer_data = get_buffer_data;
1160  }
1161 
1162  // rec_func must be set for either fget or fset.
1163  void def_property_static_impl(const char *name,
1164  handle fget, handle fset,
1165  detail::function_record *rec_func) {
1166  const auto is_static = rec_func && !(rec_func->is_method && rec_func->scope);
1167  const auto has_doc = rec_func && rec_func->doc && pybind11::options::show_user_defined_docstrings();
1168  auto property = handle((PyObject *) (is_static ? get_internals().static_property_type
1169  : &PyProperty_Type));
1170  attr(name) = property(fget.ptr() ? fget : none(),
1171  fset.ptr() ? fset : none(),
1172  /*deleter*/none(),
1173  pybind11::str(has_doc ? rec_func->doc : ""));
1174  }
1175 };
1176 
1177 /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
1178 template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator new))>>
1179 void set_operator_new(type_record *r) { r->operator_new = &T::operator new; }
1180 
1181 template <typename> void set_operator_new(...) { }
1182 
1183 template <typename T, typename SFINAE = void> struct has_operator_delete : std::false_type { };
1184 template <typename T> struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
1185  : std::true_type { };
1186 template <typename T, typename SFINAE = void> struct has_operator_delete_size : std::false_type { };
1187 template <typename T> struct has_operator_delete_size<T, void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>>
1188  : std::true_type { };
1189 /// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
1191 void call_operator_delete(T *p, size_t, size_t) { T::operator delete(p); }
1193 void call_operator_delete(T *p, size_t s, size_t) { T::operator delete(p, s); }
1194 
1195 inline void call_operator_delete(void *p, size_t s, size_t a) {
1196  (void)s; (void)a;
1197  #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1198  if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1199  #ifdef __cpp_sized_deallocation
1200  ::operator delete(p, s, std::align_val_t(a));
1201  #else
1202  ::operator delete(p, std::align_val_t(a));
1203  #endif
1204  return;
1205  }
1206  #endif
1207  #ifdef __cpp_sized_deallocation
1208  ::operator delete(p, s);
1209  #else
1210  ::operator delete(p);
1211  #endif
1212 }
1213 
1214 inline void add_class_method(object& cls, const char *name_, const cpp_function &cf) {
1215  cls.attr(cf.name()) = cf;
1216  if (strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) {
1217  cls.attr("__hash__") = none();
1218  }
1219 }
1220 
1221 PYBIND11_NAMESPACE_END(detail)
1222 
1223 /// Given a pointer to a member function, cast it to its `Derived` version.
1224 /// Forward everything else unchanged.
1225 template <typename /*Derived*/, typename F>
1226 auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) { return std::forward<F>(f); }
1227 
1228 template <typename Derived, typename Return, typename Class, typename... Args>
1229 auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
1231  "Cannot bind an inaccessible base class method; use a lambda definition instead");
1232  return pmf;
1233 }
1234 
1235 template <typename Derived, typename Return, typename Class, typename... Args>
1236 auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
1238  "Cannot bind an inaccessible base class method; use a lambda definition instead");
1239  return pmf;
1240 }
1241 
1242 template <typename type_, typename... options>
1243 class class_ : public detail::generic_type {
1244  template <typename T> using is_holder = detail::is_holder_type<type_, T>;
1245  template <typename T> using is_subtype = detail::is_strict_base_of<type_, T>;
1246  template <typename T> using is_base = detail::is_strict_base_of<T, type_>;
1247  // struct instead of using here to help MSVC:
1248  template <typename T> struct is_valid_class_option :
1249  detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
1250 
1251 public:
1252  using type = type_;
1253  using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
1254  constexpr static bool has_alias = !std::is_void<type_alias>::value;
1255  using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
1256 
1257  static_assert(detail::all_of<is_valid_class_option<options>...>::value,
1258  "Unknown/invalid class_ template parameters provided");
1259 
1260  static_assert(!has_alias || std::is_polymorphic<type>::value,
1261  "Cannot use an alias class with a non-polymorphic type");
1262 
1263  PYBIND11_OBJECT(class_, generic_type, PyType_Check)
1264 
1265  template <typename... Extra>
1266  class_(handle scope, const char *name, const Extra &... extra) {
1267  using namespace detail;
1268 
1269  // MI can only be specified via class_ template options, not constructor parameters
1270  static_assert(
1271  none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
1272  ( constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
1273  constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
1274  none_of<std::is_same<multiple_inheritance, Extra>...>::value), // no multiple_inheritance attr
1275  "Error: multiple inheritance bases must be specified via class_ template options");
1276 
1277  type_record record;
1278  record.scope = scope;
1279  record.name = name;
1280  record.type = &typeid(type);
1283  record.holder_size = sizeof(holder_type);
1284  record.init_instance = init_instance;
1285  record.dealloc = dealloc;
1287 
1288  set_operator_new<type>(&record);
1289 
1290  /* Register base classes specified via template arguments to class_, if any */
1291  PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
1292 
1293  /* Process optional arguments, if any */
1294  process_attributes<Extra...>::init(extra..., &record);
1295 
1296  generic_type::initialize(record);
1297 
1298  if (has_alias) {
1300  instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
1301  }
1302  }
1303 
1305  static void add_base(detail::type_record &rec) {
1306  rec.add_base(typeid(Base), [](void *src) -> void * {
1307  return static_cast<Base *>(reinterpret_cast<type *>(src));
1308  });
1309  }
1310 
1312  static void add_base(detail::type_record &) { }
1313 
1314  template <typename Func, typename... Extra>
1315  class_ &def(const char *name_, Func&& f, const Extra&... extra) {
1316  cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), name(name_), is_method(*this),
1317  sibling(getattr(*this, name_, none())), extra...);
1318  add_class_method(*this, name_, cf);
1319  return *this;
1320  }
1321 
1322  template <typename Func, typename... Extra> class_ &
1323  def_static(const char *name_, Func &&f, const Extra&... extra) {
1325  "def_static(...) called with a non-static member function pointer");
1326  cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
1327  sibling(getattr(*this, name_, none())), extra...);
1328  attr(cf.name()) = staticmethod(cf);
1329  return *this;
1330  }
1331 
1332  template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
1333  class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
1334  op.execute(*this, extra...);
1335  return *this;
1336  }
1337 
1338  template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
1339  class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
1340  op.execute_cast(*this, extra...);
1341  return *this;
1342  }
1343 
1344  template <typename... Args, typename... Extra>
1345  class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra&... extra) {
1346  init.execute(*this, extra...);
1347  return *this;
1348  }
1349 
1350  template <typename... Args, typename... Extra>
1351  class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra&... extra) {
1352  init.execute(*this, extra...);
1353  return *this;
1354  }
1355 
1356  template <typename... Args, typename... Extra>
1357  class_ &def(detail::initimpl::factory<Args...> &&init, const Extra&... extra) {
1358  std::move(init).execute(*this, extra...);
1359  return *this;
1360  }
1361 
1362  template <typename... Args, typename... Extra>
1363  class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
1364  std::move(pf).execute(*this, extra...);
1365  return *this;
1366  }
1367 
1368  template <typename Func>
1369  class_& def_buffer(Func &&func) {
1370  struct capture { Func func; };
1371  auto *ptr = new capture { std::forward<Func>(func) };
1372  install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
1373  detail::make_caster<type> caster;
1374  if (!caster.load(obj, false))
1375  return nullptr;
1376  return new buffer_info(((capture *) ptr)->func(caster));
1377  }, ptr);
1378  weakref(m_ptr, cpp_function([ptr](handle wr) {
1379  delete ptr;
1380  wr.dec_ref();
1381  })).release();
1382  return *this;
1383  }
1384 
1385  template <typename Return, typename Class, typename... Args>
1386  class_ &def_buffer(Return (Class::*func)(Args...)) {
1387  return def_buffer([func] (type &obj) { return (obj.*func)(); });
1388  }
1389 
1390  template <typename Return, typename Class, typename... Args>
1391  class_ &def_buffer(Return (Class::*func)(Args...) const) {
1392  return def_buffer([func] (const type &obj) { return (obj.*func)(); });
1393  }
1394 
1395  template <typename C, typename D, typename... Extra>
1396  class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
1397  static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value, "def_readwrite() requires a class member (or base class member)");
1398  cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this)),
1399  fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
1401  return *this;
1402  }
1403 
1404  template <typename C, typename D, typename... Extra>
1405  class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
1406  static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value, "def_readonly() requires a class member (or base class member)");
1407  cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this));
1409  return *this;
1410  }
1411 
1412  template <typename D, typename... Extra>
1413  class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
1414  cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
1415  fset([pm](object, const D &value) { *pm = value; }, scope(*this));
1417  return *this;
1418  }
1419 
1420  template <typename D, typename... Extra>
1421  class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
1422  cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
1424  return *this;
1425  }
1426 
1427  /// Uses return_value_policy::reference_internal by default
1428  template <typename Getter, typename... Extra>
1429  class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
1430  return def_property_readonly(name, cpp_function(method_adaptor<type>(fget)),
1432  }
1433 
1434  /// Uses cpp_function's return_value_policy by default
1435  template <typename... Extra>
1436  class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
1437  return def_property(name, fget, nullptr, extra...);
1438  }
1439 
1440  /// Uses return_value_policy::reference by default
1441  template <typename Getter, typename... Extra>
1442  class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
1444  }
1445 
1446  /// Uses cpp_function's return_value_policy by default
1447  template <typename... Extra>
1448  class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
1449  return def_property_static(name, fget, nullptr, extra...);
1450  }
1451 
1452  /// Uses return_value_policy::reference_internal by default
1453  template <typename Getter, typename Setter, typename... Extra>
1454  class_ &def_property(const char *name, const Getter &fget, const Setter &fset, const Extra& ...extra) {
1455  return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
1456  }
1457  template <typename Getter, typename... Extra>
1458  class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1459  return def_property(name, cpp_function(method_adaptor<type>(fget)), fset,
1461  }
1462 
1463  /// Uses cpp_function's return_value_policy by default
1464  template <typename... Extra>
1465  class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1466  return def_property_static(name, fget, fset, is_method(*this), extra...);
1467  }
1468 
1469  /// Uses return_value_policy::reference by default
1470  template <typename Getter, typename... Extra>
1471  class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1472  return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1473  }
1474 
1475  /// Uses cpp_function's return_value_policy by default
1476  template <typename... Extra>
1477  class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1479  "Argument annotations are not allowed for properties");
1480  auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1481  auto *rec_active = rec_fget;
1482  if (rec_fget) {
1483  char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
1484  detail::process_attributes<Extra...>::init(extra..., rec_fget);
1485  if (rec_fget->doc && rec_fget->doc != doc_prev) {
1486  free(doc_prev);
1487  rec_fget->doc = strdup(rec_fget->doc);
1488  }
1489  }
1490  if (rec_fset) {
1491  char *doc_prev = rec_fset->doc;
1492  detail::process_attributes<Extra...>::init(extra..., rec_fset);
1493  if (rec_fset->doc && rec_fset->doc != doc_prev) {
1494  free(doc_prev);
1495  rec_fset->doc = strdup(rec_fset->doc);
1496  }
1497  if (! rec_active) rec_active = rec_fset;
1498  }
1499  def_property_static_impl(name, fget, fset, rec_active);
1500  return *this;
1501  }
1502 
1503 private:
1504  /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1505  template <typename T>
1506  static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1507  const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
1508 
1509  auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1510  detail::try_get_shared_from_this(v_h.value_ptr<type>()));
1511  if (sh) {
1512  new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
1513  v_h.set_holder_constructed();
1514  }
1515 
1516  if (!v_h.holder_constructed() && inst->owned) {
1517  new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1518  v_h.set_holder_constructed();
1519  }
1520  }
1521 
1522  static void init_holder_from_existing(const detail::value_and_holder &v_h,
1523  const holder_type *holder_ptr, std::true_type /*is_copy_constructible*/) {
1524  new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1525  }
1526 
1527  static void init_holder_from_existing(const detail::value_and_holder &v_h,
1528  const holder_type *holder_ptr, std::false_type /*is_copy_constructible*/) {
1529  new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1530  }
1531 
1532  /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
1533  static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1534  const holder_type *holder_ptr, const void * /* dummy -- not enable_shared_from_this<T>) */) {
1535  if (holder_ptr) {
1536  init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1537  v_h.set_holder_constructed();
1538  } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
1539  new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1540  v_h.set_holder_constructed();
1541  }
1542  }
1543 
1544  /// Performs instance initialization including constructing a holder and registering the known
1545  /// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes an
1546  /// optional pointer to an existing holder to use; if not specified and the instance is
1547  /// `.owned`, a new holder will be constructed to manage the value pointer.
1548  static void init_instance(detail::instance *inst, const void *holder_ptr) {
1549  auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
1550  if (!v_h.instance_registered()) {
1551  register_instance(inst, v_h.value_ptr(), v_h.type);
1552  v_h.set_instance_registered();
1553  }
1554  init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
1555  }
1556 
1557  /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
1558  static void dealloc(detail::value_and_holder &v_h) {
1559  // We could be deallocating because we are cleaning up after a Python exception.
1560  // If so, the Python error indicator will be set. We need to clear that before
1561  // running the destructor, in case the destructor code calls more Python.
1562  // If we don't, the Python API will exit with an exception, and pybind11 will
1563  // throw error_already_set from the C++ destructor which is forbidden and triggers
1564  // std::terminate().
1566  if (v_h.holder_constructed()) {
1567  v_h.holder<holder_type>().~holder_type();
1568  v_h.set_holder_constructed(false);
1569  }
1570  else {
1571  detail::call_operator_delete(v_h.value_ptr<type>(),
1572  v_h.type->type_size,
1573  v_h.type->type_align
1574  );
1575  }
1576  v_h.value_ptr() = nullptr;
1577  }
1578 
1579  static detail::function_record *get_function_record(handle h) {
1580  h = detail::get_function(h);
1581  return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
1582  : nullptr;
1583  }
1584 };
1585 
1586 /// Binds an existing constructor taking arguments Args...
1587 template <typename... Args> detail::initimpl::constructor<Args...> init() { return {}; }
1588 /// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
1589 /// when not inheriting on the Python side).
1590 template <typename... Args> detail::initimpl::alias_constructor<Args...> init_alias() { return {}; }
1591 
1592 /// Binds a factory function as a constructor
1593 template <typename Func, typename Ret = detail::initimpl::factory<Func>>
1594 Ret init(Func &&f) { return {std::forward<Func>(f)}; }
1595 
1596 /// Dual-argument factory function: the first function is called when no alias is needed, the second
1597 /// when an alias is needed (i.e. due to python-side inheritance). Arguments must be identical.
1598 template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1599 Ret init(CFunc &&c, AFunc &&a) {
1600  return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1601 }
1602 
1603 /// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
1604 /// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
1605 template <typename GetState, typename SetState>
1606 detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
1607  return {std::forward<GetState>(g), std::forward<SetState>(s)};
1608 }
1609 
1611 
1613  dict entries = arg.get_type().attr("__entries");
1614  for (auto kv : entries) {
1615  if (handle(kv.second[int_(0)]).equal(arg))
1616  return pybind11::str(kv.first);
1617  }
1618  return "???";
1619 }
1620 
1621 struct enum_base {
1622  enum_base(handle base, handle parent) : m_base(base), m_parent(parent) { }
1623 
1624  PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
1625  m_base.attr("__entries") = dict();
1626  auto property = handle((PyObject *) &PyProperty_Type);
1627  auto static_property = handle((PyObject *) get_internals().static_property_type);
1628 
1629  m_base.attr("__repr__") = cpp_function(
1630  [](object arg) -> str {
1632  object type_name = type.attr("__name__");
1633  return pybind11::str("<{}.{}: {}>").format(type_name, enum_name(arg), int_(arg));
1634  }, name("__repr__"), is_method(m_base)
1635  );
1636 
1637  m_base.attr("name") = property(cpp_function(&enum_name, name("name"), is_method(m_base)));
1638 
1639  m_base.attr("__str__") = cpp_function(
1640  [](handle arg) -> str {
1641  object type_name = type::handle_of(arg).attr("__name__");
1642  return pybind11::str("{}.{}").format(type_name, enum_name(arg));
1643  }, name("name"), is_method(m_base)
1644  );
1645 
1646  m_base.attr("__doc__") = static_property(cpp_function(
1647  [](handle arg) -> std::string {
1648  std::string docstring;
1649  dict entries = arg.attr("__entries");
1650  if (((PyTypeObject *) arg.ptr())->tp_doc)
1651  docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) + "\n\n";
1652  docstring += "Members:";
1653  for (auto kv : entries) {
1654  auto key = std::string(pybind11::str(kv.first));
1655  auto comment = kv.second[int_(1)];
1656  docstring += "\n\n " + key;
1657  if (!comment.is_none())
1658  docstring += " : " + (std::string) pybind11::str(comment);
1659  }
1660  return docstring;
1661  }, name("__doc__")
1662  ), none(), none(), "");
1663 
1664  m_base.attr("__members__") = static_property(cpp_function(
1665  [](handle arg) -> dict {
1666  dict entries = arg.attr("__entries"), m;
1667  for (auto kv : entries)
1668  m[kv.first] = kv.second[int_(0)];
1669  return m;
1670  }, name("__members__")), none(), none(), ""
1671  );
1672 
1673  #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
1674  m_base.attr(op) = cpp_function( \
1675  [](object a, object b) { \
1676  if (!type::handle_of(a).is(type::handle_of(b))) \
1677  strict_behavior; \
1678  return expr; \
1679  }, \
1680  name(op), is_method(m_base), arg("other"))
1681 
1682  #define PYBIND11_ENUM_OP_CONV(op, expr) \
1683  m_base.attr(op) = cpp_function( \
1684  [](object a_, object b_) { \
1685  int_ a(a_), b(b_); \
1686  return expr; \
1687  }, \
1688  name(op), is_method(m_base), arg("other"))
1689 
1690  #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
1691  m_base.attr(op) = cpp_function( \
1692  [](object a_, object b) { \
1693  int_ a(a_); \
1694  return expr; \
1695  }, \
1696  name(op), is_method(m_base), arg("other"))
1697 
1698  if (is_convertible) {
1699  PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
1700  PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
1701 
1702  if (is_arithmetic) {
1703  PYBIND11_ENUM_OP_CONV("__lt__", a < b);
1704  PYBIND11_ENUM_OP_CONV("__gt__", a > b);
1705  PYBIND11_ENUM_OP_CONV("__le__", a <= b);
1706  PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
1707  PYBIND11_ENUM_OP_CONV("__and__", a & b);
1708  PYBIND11_ENUM_OP_CONV("__rand__", a & b);
1709  PYBIND11_ENUM_OP_CONV("__or__", a | b);
1710  PYBIND11_ENUM_OP_CONV("__ror__", a | b);
1711  PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
1712  PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
1713  m_base.attr("__invert__") = cpp_function(
1714  [](object arg) { return ~(int_(arg)); }, name("__invert__"), is_method(m_base));
1715  }
1716  } else {
1717  PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
1718  PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
1719 
1720  if (is_arithmetic) {
1721  #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
1722  PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
1723  PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
1724  PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
1725  PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
1726  #undef PYBIND11_THROW
1727  }
1728  }
1729 
1730  #undef PYBIND11_ENUM_OP_CONV_LHS
1731  #undef PYBIND11_ENUM_OP_CONV
1732  #undef PYBIND11_ENUM_OP_STRICT
1733 
1734  m_base.attr("__getstate__") = cpp_function(
1735  [](object arg) { return int_(arg); }, name("__getstate__"), is_method(m_base));
1736 
1737  m_base.attr("__hash__") = cpp_function(
1738  [](object arg) { return int_(arg); }, name("__hash__"), is_method(m_base));
1739  }
1740 
1741  PYBIND11_NOINLINE void value(char const* name_, object value, const char *doc = nullptr) {
1742  dict entries = m_base.attr("__entries");
1743  str name(name_);
1744  if (entries.contains(name)) {
1745  std::string type_name = (std::string) str(m_base.attr("__name__"));
1746  throw value_error(type_name + ": element \"" + std::string(name_) + "\" already exists!");
1747  }
1748 
1749  entries[name] = std::make_pair(value, doc);
1750  m_base.attr(name) = value;
1751  }
1752 
1754  dict entries = m_base.attr("__entries");
1755  for (auto kv : entries)
1756  m_parent.attr(kv.first) = kv.second[int_(0)];
1757  }
1758 
1761 };
1762 
1763 PYBIND11_NAMESPACE_END(detail)
1764 
1765 /// Binds C++ enumerations and enumeration classes to Python
1766 template <typename Type> class enum_ : public class_<Type> {
1767 public:
1769  using Base::def;
1770  using Base::attr;
1771  using Base::def_property_readonly;
1772  using Base::def_property_readonly_static;
1773  using Scalar = typename std::underlying_type<Type>::type;
1774 
1775  template <typename... Extra>
1776  enum_(const handle &scope, const char *name, const Extra&... extra)
1777  : class_<Type>(scope, name, extra...), m_base(*this, scope) {
1778  constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
1779  constexpr bool is_convertible = std::is_convertible<Type, Scalar>::value;
1780  m_base.init(is_arithmetic, is_convertible);
1781 
1782  def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
1783  def_property_readonly("value", [](Type value) { return (Scalar) value; });
1784  def("__int__", [](Type value) { return (Scalar) value; });
1785  #if PY_MAJOR_VERSION < 3
1786  def("__long__", [](Type value) { return (Scalar) value; });
1787  #endif
1788  #if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 8)
1789  def("__index__", [](Type value) { return (Scalar) value; });
1790  #endif
1791 
1792  attr("__setstate__") = cpp_function(
1793  [](detail::value_and_holder &v_h, Scalar arg) {
1794  detail::initimpl::setstate<Base>(v_h, static_cast<Type>(arg),
1795  Py_TYPE(v_h.inst) != v_h.type->type); },
1796  detail::is_new_style_constructor(),
1797  pybind11::name("__setstate__"), is_method(*this), arg("state"));
1798  }
1799 
1800  /// Export enumeration entries into the parent scope
1802  m_base.export_values();
1803  return *this;
1804  }
1805 
1806  /// Add an enumeration entry
1807  enum_& value(char const* name, Type value, const char *doc = nullptr) {
1808  m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
1809  return *this;
1810  }
1811 
1812 private:
1813  detail::enum_base m_base;
1814 };
1815 
1817 
1818 
1819 inline void keep_alive_impl(handle nurse, handle patient) {
1820  if (!nurse || !patient)
1821  pybind11_fail("Could not activate keep_alive!");
1822 
1823  if (patient.is_none() || nurse.is_none())
1824  return; /* Nothing to keep alive or nothing to be kept alive by */
1825 
1826  auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
1827  if (!tinfo.empty()) {
1828  /* It's a pybind-registered type, so we can store the patient in the
1829  * internal list. */
1830  add_patient(nurse.ptr(), patient.ptr());
1831  }
1832  else {
1833  /* Fall back to clever approach based on weak references taken from
1834  * Boost.Python. This is not used for pybind-registered types because
1835  * the objects can be destroyed out-of-order in a GC pass. */
1836  cpp_function disable_lifesupport(
1837  [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
1838 
1839  weakref wr(nurse, disable_lifesupport);
1840 
1841  patient.inc_ref(); /* reference patient and leak the weak reference */
1842  (void) wr.release();
1843  }
1844 }
1845 
1846 PYBIND11_NOINLINE inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
1847  auto get_arg = [&](size_t n) {
1848  if (n == 0)
1849  return ret;
1850  else if (n == 1 && call.init_self)
1851  return call.init_self;
1852  else if (n <= call.args.size())
1853  return call.args[n - 1];
1854  return handle();
1855  };
1856 
1857  keep_alive_impl(get_arg(Nurse), get_arg(Patient));
1858 }
1859 
1860 inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type) {
1861  auto res = get_internals().registered_types_py
1862 #ifdef __cpp_lib_unordered_map_try_emplace
1863  .try_emplace(type);
1864 #else
1865  .emplace(type, std::vector<detail::type_info *>());
1866 #endif
1867  if (res.second) {
1868  // New cache entry created; set up a weak reference to automatically remove it if the type
1869  // gets destroyed:
1870  weakref((PyObject *) type, cpp_function([type](handle wr) {
1872  wr.dec_ref();
1873  })).release();
1874  }
1875 
1876  return res;
1877 }
1878 
1879 template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
1881  Iterator it;
1882  Sentinel end;
1884 };
1885 
1886 PYBIND11_NAMESPACE_END(detail)
1887 
1888 /// Makes a python iterator from a first and past-the-end C++ InputIterator.
1890  typename Iterator,
1891  typename Sentinel,
1892 #ifndef DOXYGEN_SHOULD_SKIP_THIS // Issue in breathe 4.26.1
1893  typename ValueType = decltype(*std::declval<Iterator>()),
1894 #endif
1895  typename... Extra>
1896 iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1897  using state = detail::iterator_state<Iterator, Sentinel, false, Policy>;
1898 
1899  if (!detail::get_type_info(typeid(state), false)) {
1900  class_<state>(handle(), "iterator", pybind11::module_local())
1901  .def("__iter__", [](state &s) -> state& { return s; })
1902  .def("__next__", [](state &s) -> ValueType {
1903  if (!s.first_or_done)
1904  ++s.it;
1905  else
1906  s.first_or_done = false;
1907  if (s.it == s.end) {
1908  s.first_or_done = true;
1909  throw stop_iteration();
1910  }
1911  return *s.it;
1912  }, std::forward<Extra>(extra)..., Policy);
1913  }
1914 
1915  return cast(state{first, last, true});
1916 }
1917 
1918 /// Makes an python iterator over the keys (`.first`) of a iterator over pairs from a
1919 /// first and past-the-end InputIterator.
1921  typename Iterator,
1922  typename Sentinel,
1923 #ifndef DOXYGEN_SHOULD_SKIP_THIS // Issue in breathe 4.26.1
1924  typename KeyType = decltype((*std::declval<Iterator>()).first),
1925 #endif
1926  typename... Extra>
1927 iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1928  using state = detail::iterator_state<Iterator, Sentinel, true, Policy>;
1929 
1930  if (!detail::get_type_info(typeid(state), false)) {
1931  class_<state>(handle(), "iterator", pybind11::module_local())
1932  .def("__iter__", [](state &s) -> state& { return s; })
1933  .def("__next__", [](state &s) -> KeyType {
1934  if (!s.first_or_done)
1935  ++s.it;
1936  else
1937  s.first_or_done = false;
1938  if (s.it == s.end) {
1939  s.first_or_done = true;
1940  throw stop_iteration();
1941  }
1942  return (*s.it).first;
1943  }, std::forward<Extra>(extra)..., Policy);
1944  }
1945 
1946  return cast(state{first, last, true});
1947 }
1948 
1949 /// Makes an iterator over values of an stl container or other container supporting
1950 /// `std::begin()`/`std::end()`
1952  typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
1953  return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
1954 }
1955 
1956 /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
1957 /// `std::begin()`/`std::end()`
1959  typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
1960  return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
1961 }
1962 
1963 template <typename InputType, typename OutputType> void implicitly_convertible() {
1964  struct set_flag {
1965  bool &flag;
1966  set_flag(bool &flag_) : flag(flag_) { flag_ = true; }
1967  ~set_flag() { flag = false; }
1968  };
1969  auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
1970  static bool currently_used = false;
1971  if (currently_used) // implicit conversions are non-reentrant
1972  return nullptr;
1973  set_flag flag_helper(currently_used);
1974  if (!detail::make_caster<InputType>().load(obj, false))
1975  return nullptr;
1976  tuple args(1);
1977  args[0] = obj;
1978  PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1979  if (result == nullptr)
1980  PyErr_Clear();
1981  return result;
1982  };
1983 
1984  if (auto tinfo = detail::get_type_info(typeid(OutputType)))
1985  tinfo->implicit_conversions.push_back(implicit_caster);
1986  else
1987  pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
1988 }
1989 
1990 template <typename ExceptionTranslator>
1991 void register_exception_translator(ExceptionTranslator&& translator) {
1993  std::forward<ExceptionTranslator>(translator));
1994 }
1995 
1996 /**
1997  * Wrapper to generate a new Python exception type.
1998  *
1999  * This should only be used with PyErr_SetString for now.
2000  * It is not (yet) possible to use as a py::base.
2001  * Template type argument is reserved for future use.
2002  */
2003 template <typename type>
2004 class exception : public object {
2005 public:
2006  exception() = default;
2007  exception(handle scope, const char *name, handle base = PyExc_Exception) {
2008  std::string full_name = scope.attr("__name__").cast<std::string>() +
2009  std::string(".") + name;
2010  m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), NULL);
2011  if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name))
2012  pybind11_fail("Error during initialization: multiple incompatible "
2013  "definitions with name \"" + std::string(name) + "\"");
2014  scope.attr(name) = *this;
2015  }
2016 
2017  // Sets the current python exception to this exception object with the given message
2018  void operator()(const char *message) {
2019  PyErr_SetString(m_ptr, message);
2020  }
2021 };
2022 
2024 // Returns a reference to a function-local static exception object used in the simple
2025 // register_exception approach below. (It would be simpler to have the static local variable
2026 // directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
2027 template <typename CppException>
2029 PYBIND11_NAMESPACE_END(detail)
2030 
2031 /**
2032  * Registers a Python exception in `m` of the given `name` and installs an exception translator to
2033  * translate the C++ exception to the created Python exception using the exceptions what() method.
2034  * This is intended for simple exception translations; for more complex translation, register the
2035  * exception object and translator directly.
2036  */
2037 template <typename CppException>
2039  const char *name,
2040  handle base = PyExc_Exception) {
2041  auto &ex = detail::get_exception_object<CppException>();
2042  if (!ex) ex = exception<CppException>(scope, name, base);
2043 
2044  register_exception_translator([](std::exception_ptr p) {
2045  if (!p) return;
2046  try {
2047  std::rethrow_exception(p);
2048  } catch (const CppException &e) {
2049  detail::get_exception_object<CppException>()(e.what());
2050  }
2051  });
2052  return ex;
2053 }
2054 
2057  auto strings = tuple(args.size());
2058  for (size_t i = 0; i < args.size(); ++i) {
2059  strings[i] = str(args[i]);
2060  }
2061  auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
2062  auto line = sep.attr("join")(strings);
2063 
2064  object file;
2065  if (kwargs.contains("file")) {
2066  file = kwargs["file"].cast<object>();
2067  } else {
2068  try {
2069  file = module_::import("sys").attr("stdout");
2070  } catch (const error_already_set &) {
2071  /* If print() is called from code that is executed as
2072  part of garbage collection during interpreter shutdown,
2073  importing 'sys' can fail. Give up rather than crashing the
2074  interpreter in this case. */
2075  return;
2076  }
2077  }
2078 
2079  auto write = file.attr("write");
2080  write(line);
2081  write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
2082 
2083  if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
2084  file.attr("flush")();
2085 }
2086 PYBIND11_NAMESPACE_END(detail)
2087 
2088 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
2089 void print(Args &&...args) {
2090  auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
2091  detail::print(c.args(), c.kwargs());
2092 }
2093 
2094 #if defined(WITH_THREAD) && !defined(PYPY_VERSION)
2095 
2096 /* The functions below essentially reproduce the PyGILState_* API using a RAII
2097  * pattern, but there are a few important differences:
2098  *
2099  * 1. When acquiring the GIL from an non-main thread during the finalization
2100  * phase, the GILState API blindly terminates the calling thread, which
2101  * is often not what is wanted. This API does not do this.
2102  *
2103  * 2. The gil_scoped_release function can optionally cut the relationship
2104  * of a PyThreadState and its associated thread, which allows moving it to
2105  * another thread (this is a fairly rare/advanced use case).
2106  *
2107  * 3. The reference count of an acquired thread state can be controlled. This
2108  * can be handy to prevent cases where callbacks issued from an external
2109  * thread would otherwise constantly construct and destroy thread state data
2110  * structures.
2111  *
2112  * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
2113  * example which uses features 2 and 3 to migrate the Python thread of
2114  * execution to another thread (to run the event loop on the original thread,
2115  * in this case).
2116  */
2117 
2118 class gil_scoped_acquire {
2119 public:
2121  auto const &internals = detail::get_internals();
2122  tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
2123 
2124  if (!tstate) {
2125  /* Check if the GIL was acquired using the PyGILState_* API instead (e.g. if
2126  calling from a Python thread). Since we use a different key, this ensures
2127  we don't create a new thread state and deadlock in PyEval_AcquireThread
2128  below. Note we don't save this state with internals.tstate, since we don't
2129  create it we would fail to clear it (its reference count should be > 0). */
2130  tstate = PyGILState_GetThisThreadState();
2131  }
2132 
2133  if (!tstate) {
2134  tstate = PyThreadState_New(internals.istate);
2135  #if !defined(NDEBUG)
2136  if (!tstate)
2137  pybind11_fail("scoped_acquire: could not create thread state!");
2138  #endif
2139  tstate->gilstate_counter = 0;
2140  PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
2141  } else {
2142  release = detail::get_thread_state_unchecked() != tstate;
2143  }
2144 
2145  if (release) {
2146  PyEval_AcquireThread(tstate);
2147  }
2148 
2149  inc_ref();
2150  }
2151 
2152  void inc_ref() {
2153  ++tstate->gilstate_counter;
2154  }
2155 
2156  PYBIND11_NOINLINE void dec_ref() {
2157  --tstate->gilstate_counter;
2158  #if !defined(NDEBUG)
2159  if (detail::get_thread_state_unchecked() != tstate)
2160  pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
2161  if (tstate->gilstate_counter < 0)
2162  pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
2163  #endif
2164  if (tstate->gilstate_counter == 0) {
2165  #if !defined(NDEBUG)
2166  if (!release)
2167  pybind11_fail("scoped_acquire::dec_ref(): internal error!");
2168  #endif
2169  PyThreadState_Clear(tstate);
2170  if (active)
2171  PyThreadState_DeleteCurrent();
2173  release = false;
2174  }
2175  }
2176 
2177  /// This method will disable the PyThreadState_DeleteCurrent call and the
2178  /// GIL won't be acquired. This method should be used if the interpreter
2179  /// could be shutting down when this is called, as thread deletion is not
2180  /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and
2181  /// protect subsequent code.
2182  PYBIND11_NOINLINE void disarm() {
2183  active = false;
2184  }
2185 
2187  dec_ref();
2188  if (release)
2189  PyEval_SaveThread();
2190  }
2191 private:
2192  PyThreadState *tstate = nullptr;
2193  bool release = true;
2194  bool active = true;
2195 };
2196 
2197 class gil_scoped_release {
2198 public:
2199  explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
2200  // `get_internals()` must be called here unconditionally in order to initialize
2201  // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
2202  // initialization race could occur as multiple threads try `gil_scoped_acquire`.
2203  const auto &internals = detail::get_internals();
2204  tstate = PyEval_SaveThread();
2205  if (disassoc) {
2206  auto key = internals.tstate;
2208  }
2209  }
2210 
2211  /// This method will disable the PyThreadState_DeleteCurrent call and the
2212  /// GIL won't be acquired. This method should be used if the interpreter
2213  /// could be shutting down when this is called, as thread deletion is not
2214  /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and
2215  /// protect subsequent code.
2216  PYBIND11_NOINLINE void disarm() {
2217  active = false;
2218  }
2219 
2220  ~gil_scoped_release() {
2221  if (!tstate)
2222  return;
2223  // `PyEval_RestoreThread()` should not be called if runtime is finalizing
2224  if (active)
2225  PyEval_RestoreThread(tstate);
2226  if (disassoc) {
2227  auto key = detail::get_internals().tstate;
2228  PYBIND11_TLS_REPLACE_VALUE(key, tstate);
2229  }
2230  }
2231 private:
2232  PyThreadState *tstate;
2233  bool disassoc;
2234  bool active = true;
2235 };
2236 #elif defined(PYPY_VERSION)
2237 class gil_scoped_acquire {
2238  PyGILState_STATE state;
2239 public:
2240  gil_scoped_acquire() { state = PyGILState_Ensure(); }
2241  ~gil_scoped_acquire() { PyGILState_Release(state); }
2242  void disarm() {}
2243 };
2244 
2245 class gil_scoped_release {
2246  PyThreadState *state;
2247 public:
2248  gil_scoped_release() { state = PyEval_SaveThread(); }
2249  ~gil_scoped_release() { PyEval_RestoreThread(state); }
2250  void disarm() {}
2251 };
2252 #else
2254  void disarm() {}
2255 };
2257  void disarm() {}
2258 };
2259 #endif
2260 
2262  if (m_type) {
2263  gil_scoped_acquire gil;
2265  m_type.release().dec_ref();
2266  m_value.release().dec_ref();
2267  m_trace.release().dec_ref();
2268  }
2269 }
2270 
2272 inline function get_type_override(const void *this_ptr, const type_info *this_type, const char *name) {
2273  handle self = get_object_handle(this_ptr, this_type);
2274  if (!self)
2275  return function();
2276  handle type = type::handle_of(self);
2277  auto key = std::make_pair(type.ptr(), name);
2278 
2279  /* Cache functions that aren't overridden in Python to avoid
2280  many costly Python dictionary lookups below */
2281  auto &cache = get_internals().inactive_override_cache;
2282  if (cache.find(key) != cache.end())
2283  return function();
2284 
2285  function override = getattr(self, name, function());
2286  if (override.is_cpp_function()) {
2287  cache.insert(key);
2288  return function();
2289  }
2290 
2291  /* Don't call dispatch code if invoked from overridden function.
2292  Unfortunately this doesn't work on PyPy. */
2293 #if !defined(PYPY_VERSION)
2294  PyFrameObject *frame = PyThreadState_Get()->frame;
2295  if (frame && (std::string) str(frame->f_code->co_name) == name &&
2296  frame->f_code->co_argcount > 0) {
2297  PyFrame_FastToLocals(frame);
2298  PyObject *self_caller = PyDict_GetItem(
2299  frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2300  if (self_caller == self.ptr())
2301  return function();
2302  }
2303 #else
2304  /* PyPy currently doesn't provide a detailed cpyext emulation of
2305  frame objects, so we have to emulate this using Python. This
2306  is going to be slow..*/
2307  dict d; d["self"] = self; d["name"] = pybind11::str(name);
2308  PyObject *result = PyRun_String(
2309  "import inspect\n"
2310  "frame = inspect.currentframe()\n"
2311  "if frame is not None:\n"
2312  " frame = frame.f_back\n"
2313  " if frame is not None and str(frame.f_code.co_name) == name and "
2314  "frame.f_code.co_argcount > 0:\n"
2315  " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2316  " if self_caller == self:\n"
2317  " self = None\n",
2318  Py_file_input, d.ptr(), d.ptr());
2319  if (result == nullptr)
2320  throw error_already_set();
2321  if (d["self"].is_none())
2322  return function();
2323  Py_DECREF(result);
2324 #endif
2325 
2326  return override;
2327 }
2328 PYBIND11_NAMESPACE_END(detail)
2329 
2330 /** \rst
2331  Try to retrieve a python method by the provided name from the instance pointed to by the this_ptr.
2332 
2333  :this_ptr: The pointer to the object the overridden method should be retrieved for. This should be
2334  the first non-trampoline class encountered in the inheritance chain.
2335  :name: The name of the overridden Python method to retrieve.
2336  :return: The Python method by this name from the object or an empty function wrapper.
2337  \endrst */
2338 template <class T> function get_override(const T *this_ptr, const char *name) {
2339  auto tinfo = detail::get_type_info(typeid(T));
2340  return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
2341 }
2342 
2343 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
2344  do { \
2345  pybind11::gil_scoped_acquire gil; \
2346  pybind11::function override = pybind11::get_override(static_cast<const cname *>(this), name); \
2347  if (override) { \
2348  auto o = override(__VA_ARGS__); \
2349  if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
2350  static pybind11::detail::override_caster_t<ret_type> caster; \
2351  return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
2352  } \
2353  else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2354  } \
2355  } while (false)
2356 
2357 /** \rst
2358  Macro to populate the virtual method in the trampoline class. This macro tries to look up a method named 'fn'
2359  from the Python side, deals with the :ref:`gil` and necessary argument conversions to call this method and return
2360  the appropriate type. See :ref:`overriding_virtuals` for more information. This macro should be used when the method
2361  name in C is not the same as the method name in Python. For example with `__str__`.
2362 
2363  .. code-block:: cpp
2364 
2365  std::string toString() override {
2366  PYBIND11_OVERRIDE_NAME(
2367  std::string, // Return type (ret_type)
2368  Animal, // Parent class (cname)
2369  "__str__", // Name of method in Python (name)
2370  toString, // Name of function in C++ (fn)
2371  );
2372  }
2373 \endrst */
2374 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
2375  do { \
2376  PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2377  return cname::fn(__VA_ARGS__); \
2378  } while (false)
2379 
2380 /** \rst
2381  Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it
2382  throws if no override can be found.
2383 \endrst */
2384 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
2385  do { \
2386  PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2387  pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
2388  } while (false)
2389 
2390 /** \rst
2391  Macro to populate the virtual method in the trampoline class. This macro tries to look up the method
2392  from the Python side, deals with the :ref:`gil` and necessary argument conversions to call this method and return
2393  the appropriate type. This macro should be used if the method name in C and in Python are identical.
2394  See :ref:`overriding_virtuals` for more information.
2395 
2396  .. code-block:: cpp
2397 
2398  class PyAnimal : public Animal {
2399  public:
2400  // Inherit the constructors
2401  using Animal::Animal;
2402 
2403  // Trampoline (need one for each virtual function)
2404  std::string go(int n_times) override {
2405  PYBIND11_OVERRIDE_PURE(
2406  std::string, // Return type (ret_type)
2407  Animal, // Parent class (cname)
2408  go, // Name of function in C++ (must match Python name) (fn)
2409  n_times // Argument(s) (...)
2410  );
2411  }
2412  };
2413 \endrst */
2414 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
2415  PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2416 
2417 /** \rst
2418  Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`, except that it throws
2419  if no override can be found.
2420 \endrst */
2421 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
2422  PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2423 
2424 
2425 // Deprecated versions
2426 
2427 PYBIND11_DEPRECATED("get_type_overload has been deprecated")
2428 inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
2429  return detail::get_type_override(this_ptr, this_type, name);
2430 }
2431 
2432 template <class T>
2433 inline function get_overload(const T *this_ptr, const char *name) {
2434  return get_override(this_ptr, name);
2435 }
2436 
2437 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
2438  PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
2439 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
2440  PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
2441 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
2442  PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
2443 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
2444  PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
2445 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2446  PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
2447 
2449 
2450 #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
2451 # pragma warning(pop)
2452 #elif defined(__GNUG__) && !defined(__clang__)
2453 # pragma GCC diagnostic pop
2454 #endif
PYBIND11_INSTANCE_METHOD_CHECK
#define PYBIND11_INSTANCE_METHOD_CHECK
Definition: common.h:214
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:83
module_::import
static module_ import(const char *name)
Import and return a module or throws error_already_set.
Definition: pybind11.h:991
int_
Definition: pytypes.h:1126
class_::def_cast
class_ & def_cast(const detail::op_< id, ot, L, R > &op, const Extra &... extra)
Definition: pybind11.h:1339
enum_::Scalar
typename std::underlying_type< Type >::type Scalar
Definition: pybind11.h:1773
function_record::is_new_style_constructor
bool is_new_style_constructor
True if this is a new-style __init__ defined in detail/init.h
Definition: attr.h:175
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:499
test_multiple_inheritance.i
i
Definition: test_multiple_inheritance.py:22
module_::module_def
Definition: pybind11.h:1024
cpp_function::InitializingFunctionRecordDeleter
Definition: pybind11.h:117
error_scope
RAII wrapper that temporarily clears any Python error state.
Definition: common.h:785
class_::add_base
static void add_base(detail::type_record &)
Definition: pybind11.h:1312
class_::def_readonly
class_ & def_readonly(const char *name, const D C::*pm, const Extra &...extra)
Definition: pybind11.h:1405
module_::add_object
PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite=false)
Definition: pybind11.h:1013
exception::exception
exception()=default
PYBIND11_MODULE_LOCAL_ID
#define PYBIND11_MODULE_LOCAL_ID
Definition: internals.h:216
implicitly_convertible
void implicitly_convertible()
Definition: pybind11.h:1963
cpp_function::cpp_function
cpp_function()=default
attr.h
name
Annotation for function names.
Definition: attr.h:36
function_record
Internal data structure which holds metadata about a bound function (signature, overloads,...
Definition: attr.h:141
setattr
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:451
cast
T cast(const handle &handle)
Definition: cast.h:1769
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: common.h:16
internals
Definition: internals.h:96
base
Annotation indicating that a class derives from another given type.
Definition: attr.h:42
enum_
Binds C++ enumerations and enumeration classes to Python.
Definition: pybind11.h:1766
PYBIND11_INSTANCE_METHOD_GET_FUNCTION
#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION
Definition: common.h:215
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:257
get_type_override
function get_type_override(const void *this_ptr, const type_info *this_type, const char *name)
Definition: pybind11.h:2272
function_record::scope
handle scope
Python handle to the parent scope (a class or a module)
Definition: attr.h:211
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: common.h:17
get_thread_state_unchecked
PyThreadState * get_thread_state_unchecked()
Definition: cast.h:482
class.h
add_patient
void add_patient(PyObject *nurse, PyObject *patient)
Definition: class.h:362
PYBIND11_OBJECT
#define PYBIND11_OBJECT(Name, Parent, CheckFun)
Definition: pytypes.h:831
scope
Annotation for parent scope.
Definition: attr.h:30
error_already_set
Definition: pytypes.h:326
type_info
Definition: internals.h:128
kwargs
Definition: pytypes.h:1367
PYBIND11_NAMESPACE
#define PYBIND11_NAMESPACE
Definition: common.h:26
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:76
process_attributes::init
static void init(const Args &... args, function_record *r)
Definition: attr.h:517
function_record::nargs
std::uint16_t nargs
Number of arguments (including py::args and/or py::kwargs, if present)
Definition: attr.h:199
data
arr data(const arr &a, Ix... index)
Definition: test_numpy_array.cpp:82
enum_::value
enum_ & value(char const *name, Type value, const char *doc=nullptr)
Add an enumeration entry.
Definition: pybind11.h:1807
cpp_function::name
object name() const
Return the function name.
Definition: pybind11.h:114
class_::def
class_ & def(detail::initimpl::factory< Args... > &&init, const Extra &... extra)
Definition: pybind11.h:1357
staticmethod
Definition: pytypes.h:1398
cpp_function::strdup_guard::operator()
char * operator()(const char *s)
Definition: pybind11.h:244
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:1454
make_iterator
iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra)
Makes a python iterator from a first and past-the-end C++ InputIterator.
Definition: pybind11.h:1896
internals::registered_types_cpp
type_map< type_info * > registered_types_cpp
Definition: internals.h:97
instance::get_value_and_holder
value_and_holder get_value_and_holder(const type_info *find_type=nullptr, bool throw_if_missing=true)
Definition: cast.h:339
class_< Type >::holder_type
detail::exactly_one_t< is_holder, std::unique_ptr< type >, options... > holder_type
Definition: pybind11.h:1255
cpp_function::strdup_guard::release
void release()
Definition: pybind11.h:249
PYBIND11_DEPRECATED
#define PYBIND11_DEPRECATED(reason)
Definition: common.h:94
clean_type_id
PYBIND11_NOINLINE void clean_type_id(std::string &name)
Definition: typeid.h:32
PYBIND11_INSTANCE_METHOD_NEW
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_)
Include Python header, disable linking to pythonX_d.lib on Windows in debug mode.
Definition: common.h:213
class_::def
class_ & def(const char *name_, Func &&f, const Extra &... extra)
Definition: pybind11.h:1315
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:542
class_::def_readonly_static
class_ & def_readonly_static(const char *name, const D *pm, const Extra &...extra)
Definition: pybind11.h:1421
PYBIND11_THROW
#define PYBIND11_THROW
enum_base
Definition: pybind11.h:1621
cpp_function::strdup_guard::~strdup_guard
~strdup_guard()
Definition: pybind11.h:240
handle::inc_ref
const handle & inc_ref() const &
Definition: pytypes.h:192
void_t
typename void_t_impl< Ts... >::type void_t
Definition: common.h:538
module_::def
module_ & def(const char *name_, Func &&f, const Extra &... extra)
Definition: pybind11.h:961
cpp_function::cpp_function
cpp_function(Return(*f)(Args...), const Extra &... extra)
Construct a cpp_function from a vanilla function pointer.
Definition: pybind11.h:69
enum_base::value
PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc=nullptr)
Definition: pybind11.h:1741
PYBIND11_NOINLINE
#define PYBIND11_NOINLINE
Definition: common.h:88
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:405
cpp_function::unique_function_record
std::unique_ptr< detail::function_record, InitializingFunctionRecordDeleter > unique_function_record
Definition: pybind11.h:122
capsule
Definition: pytypes.h:1211
def
int def()
Definition: test_ABM.cpp:4
all_of
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... > > all_of
Definition: common.h:550
type
Definition: pytypes.h:915
get_overload
function get_overload(const T *this_ptr, const char *name)
Definition: pybind11.h:2433
_
constexpr descr< N - 1 > _(char const(&text)[N])
Definition: descr.h:54
getattr
object getattr(handle obj, handle name)
Definition: pytypes.h:421
class_::def_buffer
class_ & def_buffer(Func &&func)
Definition: pybind11.h:1369
value_and_holder
Definition: cast.h:223
handle::m_ptr
PyObject * m_ptr
Definition: pytypes.h:219
generic_type
Generic support for creating new Python heap types.
Definition: pybind11.h:1079
function_record::has_kwargs
bool has_kwargs
True if the function has a '**kwargs' argument.
Definition: attr.h:190
class_< Type >::type_alias
detail::exactly_one_t< is_subtype, void, options... > type_alias
Definition: pybind11.h:1253
class_::def_readwrite_static
class_ & def_readwrite_static(const char *name, D *pm, const Extra &...extra)
Definition: pybind11.h:1413
PYBIND11_TLS_GET_VALUE
#define PYBIND11_TLS_GET_VALUE(key)
Definition: internals.h:32
options.h
type_record::init_instance
void(* init_instance)(instance *, const void *)
Function pointer to class_<..>::init_instance.
Definition: attr.h:248
constexpr_sum
constexpr size_t constexpr_sum()
Compile-time integer sum.
Definition: common.h:589
type_record::name
const char * name
Name of the class.
Definition: attr.h:230
get_internals
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
Definition: internals.h:256
iterator
Definition: pytypes.h:854
cpp_function::initialize
void initialize(Func &&f, Return(*)(Args...), const Extra &... extra)
Special internal constructor for functors, lambda functions, etc.
Definition: pybind11.h:131
type_record::holder_size
size_t holder_size
How large is the type's holder?
Definition: attr.h:242
op_id
op_id
Enumeration with all supported operator types.
Definition: operators.h:25
error_already_set::restore
void restore()
Definition: pytypes.h:342
get_type_overload
function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name)
Definition: pybind11.h:2428
class_::def_readwrite
class_ & def_readwrite(const char *name, D C::*pm, const Extra &... extra)
Definition: pybind11.h:1396
is_method
Annotation for methods.
Definition: attr.h:21
enum_base::init
PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible)
Definition: pybind11.h:1624
class_::add_base
static void add_base(detail::type_record &rec)
Definition: pybind11.h:1305
class_::type
type_ type
Definition: pybind11.h:1252
weakref
Definition: pytypes.h:1173
object::PYBIND11_DEPRECATED
PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()") object(handle h
script.begin
begin
Definition: script.py:184
cpp_function::cpp_function
cpp_function(Return(Class::*f)(Arg...) const &, const Extra &... extra)
Definition: pybind11.h:108
conditional_t
typename std::conditional< B, T, F >::type conditional_t
Definition: common.h:505
class_::def_static
class_ & def_static(const char *name_, Func &&f, const Extra &... extra)
Definition: pybind11.h:1323
type_record::module_local
bool module_local
Is the class definition local to the module shared object?
Definition: attr.h:275
remove_reference_t
typename std::remove_reference< T >::type remove_reference_t
Definition: common.h:507
gil_scoped_release
Definition: pybind11.h:2256
enum_name
str enum_name(handle arg)
Definition: pybind11.h:1612
argument_record
Internal data structure which holds metadata about a keyword argument.
Definition: attr.h:129
type_record::default_holder
bool default_holder
Is the default (unique_ptr) holder type used?
Definition: attr.h:272
instance
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
Definition: common.h:437
function_call
Internal data associated with a single function call.
Definition: cast.h:1989
argument_record::name
const char * name
Argument name.
Definition: attr.h:130
sibling
Annotation indicating that a function is an overload associated with a given "sibling".
Definition: attr.h:39
cpp_function::InitializingFunctionRecordDeleter::operator()
void operator()(detail::function_record *rec)
Definition: pybind11.h:120
argument_record::convert
bool convert
True if the argument is allowed to convert when loading.
Definition: attr.h:133
object
Definition: pytypes.h:232
class_::def
class_ & def(detail::initimpl::pickle_factory< Args... > &&pf, const Extra &...extra)
Definition: pybind11.h:1363
doc
Annotation for documentation.
Definition: attr.h:33
registered_local_types_cpp
type_map< type_info * > & registered_local_types_cpp()
Works like internals.registered_types_cpp, but for module-local registered types:
Definition: internals.h:315
PYBIND11_ENUM_OP_CONV
#define PYBIND11_ENUM_OP_CONV(op, expr)
type_record::multiple_inheritance
bool multiple_inheritance
Multiple inheritance marker.
Definition: attr.h:263
list::size
size_t size() const
Definition: pytypes.h:1351
arg::name
const char * name
If non-null, this is a named kwargs argument.
Definition: cast.h:1905
PYBIND11_TLS_REPLACE_VALUE
#define PYBIND11_TLS_REPLACE_VALUE(key, value)
Definition: internals.h:36
class_
Definition: pybind11.h:1243
dict
Definition: pytypes.h:1299
get_fully_qualified_tp_name
std::string get_fully_qualified_tp_name(PyTypeObject *type)
Definition: class.h:27
function_record::is_method
bool is_method
True if this is a method.
Definition: attr.h:184
handle
Definition: pytypes.h:176
cpp_function::strdup_guard
Definition: pybind11.h:238
type_caster
Definition: cast.h:954
all_type_info_get_cache
std::pair< decltype(internals::registered_types_py)::iterator, bool > all_type_info_get_cache(PyTypeObject *type)
Definition: pybind11.h:1860
handle::cast
T cast() const
Definition: cast.h:1794
exception::operator()
void operator()(const char *message)
Definition: pybind11.h:2018
type::handle_of
static handle handle_of()
Definition: cast.h:2268
function_record::impl
handle(* impl)(function_call &)
Pointer to lambda function which converts arguments and performs the actual call.
Definition: attr.h:160
internals::inactive_override_cache
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
Definition: internals.h:100
function_call::init_self
handle init_self
If this is a call to an initializer, this argument contains self
Definition: cast.h:2009
enum_::export_values
enum_ & export_values()
Export enumeration entries into the parent scope.
Definition: pybind11.h:1801
generic_type::install_buffer_funcs
void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *), void *get_buffer_data)
Definition: pybind11.h:1145
init.h
return_value_policy_override::policy
static return_value_policy policy(return_value_policy p)
Definition: cast.h:1734
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:1471
get_override
function get_override(const T *this_ptr, const char *name)
Definition: pybind11.h:2338
type_record::bases
list bases
List of base classes of the newly created type.
Definition: attr.h:254
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:540
get_object_handle
PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type)
Definition: cast.h:470
object::release
handle release()
Definition: pytypes.h:249
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:1442
enum_base::enum_base
enum_base(handle base, handle parent)
Definition: pybind11.h:1622
iterator_state::it
Iterator it
Definition: pybind11.h:1881
function_record::nargs_kw_only
std::uint16_t nargs_kw_only
Number of trailing arguments (counted in nargs) that are keyword-only.
Definition: attr.h:202
pickle
detail::initimpl::pickle_factory< GetState, SetState > pickle(GetState &&g, SetState &&s)
Definition: pybind11.h:1606
get_function
handle get_function(handle value)
Definition: pytypes.h:468
class_::def
class_ & def(const detail::op_< id, ot, L, R > &op, const Extra &... extra)
Definition: pybind11.h:1333
type_record
Special data structure which (temporarily) holds metadata about a bound class.
Definition: attr.h:221
arg
Definition: cast.h:1895
process_attributes::postcall
static void postcall(function_call &call, handle fn_ret)
Definition: attr.h:529
conftest.capture
def capture(capsys)
Definition: conftest.py:124
function_record::nargs_pos_only
std::uint16_t nargs_pos_only
Number of leading arguments (counted in nargs) that are positional-only.
Definition: attr.h:205
function_record::is_constructor
bool is_constructor
True if name == 'init'.
Definition: attr.h:172
error_already_set::~error_already_set
~error_already_set() override
Definition: pybind11.h:2261
negation
Definition: common.h:529
policy
Definition: policy.py:1
class_::class_
class_(handle scope, const char *name, const Extra &... extra)
Definition: pybind11.h:1266
function_record::next
function_record * next
Pointer to next overload.
Definition: attr.h:217
class_::def
class_ & def(const detail::initimpl::constructor< Args... > &init, const Extra &... extra)
Definition: pybind11.h:1345
first
constexpr int first(int i)
Implementation details for constexpr functions.
Definition: common.h:596
cpp_function
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
Definition: pybind11.h:62
keep_alive_impl
void keep_alive_impl(handle nurse, handle patient)
Definition: pybind11.h:1819
enum_base::export_values
PYBIND11_NOINLINE void export_values()
Definition: pybind11.h:1753
gil_scoped_acquire
Definition: pybind11.h:2253
init
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
Definition: pybind11.h:1587
test_numpy_dtypes.scope
scope
Definition: test_numpy_dtypes.py:13
argument_record::none
bool none
True if None is allowed when loading.
Definition: attr.h:134
class_::def_buffer
class_ & def_buffer(Return(Class::*func)(Args...))
Definition: pybind11.h:1386
size_t
std::size_t size_t
Definition: common.h:354
function_call::args_ref
object args_ref
Definition: cast.h:2003
PYBIND11_EXPAND_SIDE_EFFECTS
#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)
Definition: common.h:721
type_record::operator_new
void *(* operator_new)(size_t)
The global operator new can be overridden with a class-specific variant.
Definition: attr.h:245
PYBIND11_TRY_NEXT_OVERLOAD
#define PYBIND11_TRY_NEXT_OVERLOAD
Definition: common.h:252
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:1477
class_::def_property
class_ & def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
Definition: pybind11.h:1458
function_record::has_args
bool has_args
True if the function has a '*args' argument.
Definition: attr.h:187
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: common.h:751
str
Definition: pytypes.h:946
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:1436
any_of
negation< all_of< negation< Ts >... > > any_of
Definition: common.h:551
exactly_one_t
typename exactly_one< Predicate, Default, Ts... >::type exactly_one_t
Definition: common.h:634
class_::def
class_ & def(const detail::initimpl::alias_constructor< Args... > &init, const Extra &... extra)
Definition: pybind11.h:1351
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:1135
function_record::is_operator
bool is_operator
True if this is an operator (add), etc.
Definition: attr.h:181
module_::def_submodule
module_ def_submodule(const char *name, const char *doc=nullptr)
Definition: pybind11.h:980
PYBIND11_OBJECT_DEFAULT
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
Definition: pytypes.h:839
iterator_state::first_or_done
bool first_or_done
Definition: pybind11.h:1883
move
detail::enable_if_t<!detail::move_never< T >::value, T > move(object &&obj)
Definition: cast.h:1798
Base
Definition: test_virtual_functions.cpp:152
PYBIND11_DESCR_CONSTEXPR
#define PYBIND11_DESCR_CONSTEXPR
Definition: descr.h:18
make_key_iterator
iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra)
Definition: pybind11.h:1927
internals::direct_conversions
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
Definition: internals.h:101
module_::reload
void reload()
Reload the module or throws error_already_set.
Definition: pybind11.h:999
function_record::args
std::vector< argument_record > args
List of registered keyword arguments.
Definition: attr.h:157
dict::contains
bool contains(T &&key) const
Definition: pytypes.h:1316
type_caster_generic::local_load
static PYBIND11_NOINLINE void * local_load(PyObject *src, const type_info *ti)
Definition: cast.h:636
handle::ptr
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:184
tuple::size
size_t size() const
Definition: pytypes.h:1282
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:1465
type_record::dealloc
void(* dealloc)(detail::value_and_holder &)
Function pointer to class_<..>::dealloc.
Definition: attr.h:251
module_
Wrapper for Python extension modules.
Definition: pybind11.h:941
PYBIND11_ENUM_OP_CONV_LHS
#define PYBIND11_ENUM_OP_CONV_LHS(op, expr)
enum_base::m_base
handle m_base
Definition: pybind11.h:1759
dict::empty
bool empty() const
Definition: pytypes.h:1312
argument_loader
Helper class which loads arguments for C++ functions called from Python.
Definition: cast.h:2015
PYBIND11_ENUM_OP_STRICT
#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)
class_::has_alias
constexpr static bool has_alias
Definition: pybind11.h:1254
void_type
Helper type to replace 'void' in some expressions.
Definition: common.h:580
args
Definition: pytypes.h:1366
buffer_info
Information record describing a Python buffer object.
Definition: buffer_info.h:40
return_value_policy
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
Definition: common.h:357
c_str
const char * c_str(Args &&...args)
Definition: internals.h:325
add_class_method
void add_class_method(object &cls, const char *name_, const cpp_function &cf)
Definition: pybind11.h:1214
enum_base::m_parent
handle m_parent
Definition: pybind11.h:1760
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:1429
tuple
Definition: pytypes.h:1276
is_pyobject
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
Definition: pytypes.h:48
options::show_function_signatures
static bool show_function_signatures()
Definition: options.h:45
handle::dec_ref
const handle & dec_ref() const &
Definition: pytypes.h:199
has_operator_delete_size
Definition: pybind11.h:1186
options::show_user_defined_docstrings
static bool show_user_defined_docstrings()
Definition: options.h:43
make_new_python_type
PyObject * make_new_python_type(const type_record &rec)
Definition: class.h:597
get_exception_object
exception< CppException > & get_exception_object()
Definition: pybind11.h:2028
type_record::type_align
size_t type_align
What is the alignment of the underlying C++ type?
Definition: attr.h:239
type_record::scope
handle scope
Handle to the parent scope.
Definition: attr.h:227
function
Definition: pytypes.h:1386
iterator_state::end
Sentinel end
Definition: pybind11.h:1882
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:125
internals::registered_types_py
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
Definition: internals.h:98
generic_type::initialize
void initialize(const type_record &rec)
Definition: pybind11.h:1083
type_record::type_size
size_t type_size
How large is the underlying C++ type?
Definition: attr.h:236
function_record::name
char * name
Function name.
Definition: attr.h:148
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:1448
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:1179
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:1163
script.end
end
Definition: script.py:188
PYBIND11_TLS_DELETE_VALUE
#define PYBIND11_TLS_DELETE_VALUE(key)
Definition: internals.h:34
class_::def_buffer
class_ & def_buffer(Return(Class::*func)(Args...) const)
Definition: pybind11.h:1391
function_call::args
std::vector< handle > args
Arguments passed to the function:
Definition: cast.h:1996
object::cast
T cast() const &
last
constexpr int last(int, int result)
Definition: common.h:600
conftest.doc
def doc()
Definition: conftest.py:165
process_attributes::precall
static void precall(function_call &call)
Definition: attr.h:525
globals
dict globals()
Definition: pybind11.h:1072
none
Definition: pytypes.h:1075
cpp_function::cpp_function
cpp_function(Return(Class::*f)(Arg...)&, const Extra &... extra)
Definition: pybind11.h:92
internals::registered_exception_translators
std::forward_list< void(*)(std::exception_ptr)> registered_exception_translators
Definition: internals.h:103
iterator_state
Definition: pybind11.h:1880
method_adaptor
auto method_adaptor(F &&f) -> decltype(std::forward< F >(f))
Definition: pybind11.h:1226
register_exception_translator
void register_exception_translator(ExceptionTranslator &&translator)
Definition: pybind11.h:1991
loader_life_support
Definition: cast.h:44
function_call::kwargs_ref
object kwargs_ref
Definition: cast.h:2003
all_type_info
const std::vector< detail::type_info * > & all_type_info(PyTypeObject *type)
Definition: cast.h:150
test_async.m
m
Definition: test_async.py:5
get_global_type_info
detail::type_info * get_global_type_info(const std::type_index &tp)
Definition: cast.h:181
init_alias
detail::initimpl::alias_constructor< Args... > init_alias()
Definition: pybind11.h:1590
options
Definition: options.h:16
test_callbacks.value
value
Definition: test_callbacks.py:126
exception
Definition: pybind11.h:2004
op_type
op_type
Definition: operators.h:34
register_instance
void register_instance(instance *self, void *valptr, const type_info *tinfo)
Definition: class.h:313
return_value_policy::automatic
@ automatic
function_call::args_convert
std::vector< bool > args_convert
The convert value the arguments should be loaded with.
Definition: cast.h:1999
register_exception
exception< CppException > & register_exception(handle scope, const char *name, handle base=PyExc_Exception)
Definition: pybind11.h:2038
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:99
return_value_policy::reference
@ reference
cpp_function::cpp_function
cpp_function(std::nullptr_t)
Definition: pybind11.h:65
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:1191
get_type_info
PYBIND11_NOINLINE detail::type_info * get_type_info(PyTypeObject *type)
Definition: cast.h:164
get_local_type_info
detail::type_info * get_local_type_info(const std::type_index &tp)
Definition: cast.h:173
module_::create_extension_module
static module_ create_extension_module(const char *name, const char *doc, module_def *def)
Definition: pybind11.h:1033
has_operator_delete
Definition: pybind11.h:1183
make_changelog.state
state
Definition: make_changelog.py:30
type_record::type
const std::type_info * type
Definition: attr.h:233
enum_::enum_
enum_(const handle &scope, const char *name, const Extra &... extra)
Definition: pybind11.h:1776
print
PYBIND11_NOINLINE void print(tuple args, dict kwargs)
Definition: pybind11.h:2056
setup.msg
msg
Definition: setup.py:47
exception::exception
exception(handle scope, const char *name, handle base=PyExc_Exception)
Definition: pybind11.h:2007
script.file
file
Definition: script.py:191
repr
str repr(handle h)
Definition: pytypes.h:1584