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


gtsam
Author(s):
autogenerated on Sat May 8 2021 02:43:44