pybind11.h 109 KB

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