netgen-mesher 6.2.2506.post35.dev0__cp314-cp314-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (340) hide show
  1. netgen/NgOCC.py +7 -0
  2. netgen/__init__.py +114 -0
  3. netgen/__init__.pyi +22 -0
  4. netgen/__main__.py +53 -0
  5. netgen/cmake/NetgenConfig.cmake +79 -0
  6. netgen/cmake/netgen-targets-release.cmake +69 -0
  7. netgen/cmake/netgen-targets.cmake +146 -0
  8. netgen/config/__init__.py +1 -0
  9. netgen/config/__init__.pyi +52 -0
  10. netgen/config/__main__.py +4 -0
  11. netgen/config/config.py +68 -0
  12. netgen/config/config.pyi +54 -0
  13. netgen/csg.py +25 -0
  14. netgen/geom2d.py +178 -0
  15. netgen/gui.py +82 -0
  16. netgen/include/core/archive.hpp +1256 -0
  17. netgen/include/core/array.hpp +1760 -0
  18. netgen/include/core/autodiff.hpp +1131 -0
  19. netgen/include/core/autodiffdiff.hpp +733 -0
  20. netgen/include/core/bitarray.hpp +240 -0
  21. netgen/include/core/concurrentqueue.h +3619 -0
  22. netgen/include/core/exception.hpp +145 -0
  23. netgen/include/core/flags.hpp +199 -0
  24. netgen/include/core/hashtable.hpp +1281 -0
  25. netgen/include/core/localheap.hpp +318 -0
  26. netgen/include/core/logging.hpp +117 -0
  27. netgen/include/core/memtracer.hpp +221 -0
  28. netgen/include/core/mpi4py_pycapi.h +245 -0
  29. netgen/include/core/mpi_wrapper.hpp +643 -0
  30. netgen/include/core/ng_mpi.hpp +94 -0
  31. netgen/include/core/ng_mpi_generated_declarations.hpp +155 -0
  32. netgen/include/core/ng_mpi_native.hpp +25 -0
  33. netgen/include/core/ngcore.hpp +32 -0
  34. netgen/include/core/ngcore_api.hpp +152 -0
  35. netgen/include/core/ngstream.hpp +115 -0
  36. netgen/include/core/paje_trace.hpp +279 -0
  37. netgen/include/core/profiler.hpp +382 -0
  38. netgen/include/core/python_ngcore.hpp +457 -0
  39. netgen/include/core/ranges.hpp +109 -0
  40. netgen/include/core/register_archive.hpp +100 -0
  41. netgen/include/core/signal.hpp +82 -0
  42. netgen/include/core/simd.hpp +160 -0
  43. netgen/include/core/simd_arm64.hpp +407 -0
  44. netgen/include/core/simd_avx.hpp +394 -0
  45. netgen/include/core/simd_avx512.hpp +285 -0
  46. netgen/include/core/simd_generic.hpp +1053 -0
  47. netgen/include/core/simd_math.hpp +178 -0
  48. netgen/include/core/simd_sse.hpp +289 -0
  49. netgen/include/core/statushandler.hpp +37 -0
  50. netgen/include/core/symboltable.hpp +153 -0
  51. netgen/include/core/table.hpp +810 -0
  52. netgen/include/core/taskmanager.hpp +1161 -0
  53. netgen/include/core/type_traits.hpp +65 -0
  54. netgen/include/core/utils.hpp +385 -0
  55. netgen/include/core/version.hpp +102 -0
  56. netgen/include/core/xbool.hpp +47 -0
  57. netgen/include/csg/algprim.hpp +563 -0
  58. netgen/include/csg/brick.hpp +150 -0
  59. netgen/include/csg/csg.hpp +43 -0
  60. netgen/include/csg/csgeom.hpp +389 -0
  61. netgen/include/csg/csgparser.hpp +101 -0
  62. netgen/include/csg/curve2d.hpp +67 -0
  63. netgen/include/csg/edgeflw.hpp +112 -0
  64. netgen/include/csg/explicitcurve2d.hpp +113 -0
  65. netgen/include/csg/extrusion.hpp +185 -0
  66. netgen/include/csg/gencyl.hpp +70 -0
  67. netgen/include/csg/geoml.hpp +16 -0
  68. netgen/include/csg/identify.hpp +213 -0
  69. netgen/include/csg/manifold.hpp +29 -0
  70. netgen/include/csg/meshsurf.hpp +46 -0
  71. netgen/include/csg/polyhedra.hpp +121 -0
  72. netgen/include/csg/revolution.hpp +180 -0
  73. netgen/include/csg/singularref.hpp +84 -0
  74. netgen/include/csg/solid.hpp +295 -0
  75. netgen/include/csg/specpoin.hpp +194 -0
  76. netgen/include/csg/spline3d.hpp +99 -0
  77. netgen/include/csg/splinesurface.hpp +85 -0
  78. netgen/include/csg/surface.hpp +394 -0
  79. netgen/include/csg/triapprox.hpp +63 -0
  80. netgen/include/csg/vscsg.hpp +34 -0
  81. netgen/include/general/autodiff.hpp +356 -0
  82. netgen/include/general/autoptr.hpp +39 -0
  83. netgen/include/general/gzstream.h +121 -0
  84. netgen/include/general/hashtabl.hpp +1692 -0
  85. netgen/include/general/myadt.hpp +48 -0
  86. netgen/include/general/mystring.hpp +226 -0
  87. netgen/include/general/netgenout.hpp +205 -0
  88. netgen/include/general/ngarray.hpp +797 -0
  89. netgen/include/general/ngbitarray.hpp +149 -0
  90. netgen/include/general/ngpython.hpp +74 -0
  91. netgen/include/general/optmem.hpp +44 -0
  92. netgen/include/general/parthreads.hpp +138 -0
  93. netgen/include/general/seti.hpp +50 -0
  94. netgen/include/general/sort.hpp +47 -0
  95. netgen/include/general/spbita2d.hpp +59 -0
  96. netgen/include/general/stack.hpp +114 -0
  97. netgen/include/general/table.hpp +280 -0
  98. netgen/include/general/template.hpp +509 -0
  99. netgen/include/geom2d/csg2d.hpp +750 -0
  100. netgen/include/geom2d/geometry2d.hpp +280 -0
  101. netgen/include/geom2d/spline2d.hpp +234 -0
  102. netgen/include/geom2d/vsgeom2d.hpp +28 -0
  103. netgen/include/gprim/adtree.hpp +1392 -0
  104. netgen/include/gprim/geom2d.hpp +858 -0
  105. netgen/include/gprim/geom3d.hpp +749 -0
  106. netgen/include/gprim/geomfuncs.hpp +212 -0
  107. netgen/include/gprim/geomobjects.hpp +544 -0
  108. netgen/include/gprim/geomops.hpp +404 -0
  109. netgen/include/gprim/geomtest3d.hpp +101 -0
  110. netgen/include/gprim/gprim.hpp +33 -0
  111. netgen/include/gprim/spline.hpp +778 -0
  112. netgen/include/gprim/splinegeometry.hpp +73 -0
  113. netgen/include/gprim/transform3d.hpp +216 -0
  114. netgen/include/include/acisgeom.hpp +3 -0
  115. netgen/include/include/csg.hpp +1 -0
  116. netgen/include/include/geometry2d.hpp +1 -0
  117. netgen/include/include/gprim.hpp +1 -0
  118. netgen/include/include/incopengl.hpp +62 -0
  119. netgen/include/include/inctcl.hpp +13 -0
  120. netgen/include/include/incvis.hpp +6 -0
  121. netgen/include/include/linalg.hpp +1 -0
  122. netgen/include/include/meshing.hpp +1 -0
  123. netgen/include/include/myadt.hpp +1 -0
  124. netgen/include/include/mydefs.hpp +70 -0
  125. netgen/include/include/mystdlib.h +59 -0
  126. netgen/include/include/netgen_config.hpp +27 -0
  127. netgen/include/include/netgen_version.hpp +9 -0
  128. netgen/include/include/nginterface_v2_impl.hpp +395 -0
  129. netgen/include/include/ngsimd.hpp +1 -0
  130. netgen/include/include/occgeom.hpp +1 -0
  131. netgen/include/include/opti.hpp +1 -0
  132. netgen/include/include/parallel.hpp +1 -0
  133. netgen/include/include/stlgeom.hpp +1 -0
  134. netgen/include/include/visual.hpp +1 -0
  135. netgen/include/interface/rw_medit.hpp +11 -0
  136. netgen/include/interface/writeuser.hpp +80 -0
  137. netgen/include/linalg/densemat.hpp +414 -0
  138. netgen/include/linalg/linalg.hpp +29 -0
  139. netgen/include/linalg/opti.hpp +142 -0
  140. netgen/include/linalg/polynomial.hpp +47 -0
  141. netgen/include/linalg/vector.hpp +217 -0
  142. netgen/include/meshing/adfront2.hpp +274 -0
  143. netgen/include/meshing/adfront3.hpp +332 -0
  144. netgen/include/meshing/basegeom.hpp +370 -0
  145. netgen/include/meshing/bcfunctions.hpp +53 -0
  146. netgen/include/meshing/bisect.hpp +72 -0
  147. netgen/include/meshing/boundarylayer.hpp +113 -0
  148. netgen/include/meshing/classifyhpel.hpp +1984 -0
  149. netgen/include/meshing/clusters.hpp +46 -0
  150. netgen/include/meshing/curvedelems.hpp +274 -0
  151. netgen/include/meshing/delaunay2d.hpp +73 -0
  152. netgen/include/meshing/fieldlines.hpp +103 -0
  153. netgen/include/meshing/findip.hpp +198 -0
  154. netgen/include/meshing/findip2.hpp +103 -0
  155. netgen/include/meshing/geomsearch.hpp +69 -0
  156. netgen/include/meshing/global.hpp +54 -0
  157. netgen/include/meshing/hpref_hex.hpp +330 -0
  158. netgen/include/meshing/hpref_prism.hpp +3405 -0
  159. netgen/include/meshing/hpref_pyramid.hpp +154 -0
  160. netgen/include/meshing/hpref_quad.hpp +2082 -0
  161. netgen/include/meshing/hpref_segm.hpp +122 -0
  162. netgen/include/meshing/hpref_tet.hpp +4230 -0
  163. netgen/include/meshing/hpref_trig.hpp +848 -0
  164. netgen/include/meshing/hprefinement.hpp +366 -0
  165. netgen/include/meshing/improve2.hpp +178 -0
  166. netgen/include/meshing/improve3.hpp +151 -0
  167. netgen/include/meshing/localh.hpp +223 -0
  168. netgen/include/meshing/meshclass.hpp +1076 -0
  169. netgen/include/meshing/meshfunc.hpp +47 -0
  170. netgen/include/meshing/meshing.hpp +63 -0
  171. netgen/include/meshing/meshing2.hpp +163 -0
  172. netgen/include/meshing/meshing3.hpp +123 -0
  173. netgen/include/meshing/meshtool.hpp +90 -0
  174. netgen/include/meshing/meshtype.hpp +1930 -0
  175. netgen/include/meshing/msghandler.hpp +62 -0
  176. netgen/include/meshing/paralleltop.hpp +172 -0
  177. netgen/include/meshing/python_mesh.hpp +206 -0
  178. netgen/include/meshing/ruler2.hpp +172 -0
  179. netgen/include/meshing/ruler3.hpp +211 -0
  180. netgen/include/meshing/soldata.hpp +141 -0
  181. netgen/include/meshing/specials.hpp +17 -0
  182. netgen/include/meshing/surfacegeom.hpp +73 -0
  183. netgen/include/meshing/topology.hpp +1003 -0
  184. netgen/include/meshing/validate.hpp +21 -0
  185. netgen/include/meshing/visual_interface.hpp +71 -0
  186. netgen/include/mydefs.hpp +70 -0
  187. netgen/include/nginterface.h +474 -0
  188. netgen/include/nginterface_v2.hpp +406 -0
  189. netgen/include/nglib.h +697 -0
  190. netgen/include/nglib_occ.h +50 -0
  191. netgen/include/occ/occ_edge.hpp +47 -0
  192. netgen/include/occ/occ_face.hpp +52 -0
  193. netgen/include/occ/occ_solid.hpp +23 -0
  194. netgen/include/occ/occ_utils.hpp +376 -0
  195. netgen/include/occ/occ_vertex.hpp +30 -0
  196. netgen/include/occ/occgeom.hpp +659 -0
  197. netgen/include/occ/occmeshsurf.hpp +168 -0
  198. netgen/include/occ/vsocc.hpp +33 -0
  199. netgen/include/pybind11/LICENSE +29 -0
  200. netgen/include/pybind11/attr.h +722 -0
  201. netgen/include/pybind11/buffer_info.h +208 -0
  202. netgen/include/pybind11/cast.h +2361 -0
  203. netgen/include/pybind11/chrono.h +228 -0
  204. netgen/include/pybind11/common.h +2 -0
  205. netgen/include/pybind11/complex.h +74 -0
  206. netgen/include/pybind11/conduit/README.txt +15 -0
  207. netgen/include/pybind11/conduit/pybind11_conduit_v1.h +116 -0
  208. netgen/include/pybind11/conduit/pybind11_platform_abi_id.h +87 -0
  209. netgen/include/pybind11/conduit/wrap_include_python_h.h +72 -0
  210. netgen/include/pybind11/critical_section.h +56 -0
  211. netgen/include/pybind11/detail/class.h +823 -0
  212. netgen/include/pybind11/detail/common.h +1348 -0
  213. netgen/include/pybind11/detail/cpp_conduit.h +75 -0
  214. netgen/include/pybind11/detail/descr.h +226 -0
  215. netgen/include/pybind11/detail/dynamic_raw_ptr_cast_if_possible.h +39 -0
  216. netgen/include/pybind11/detail/exception_translation.h +71 -0
  217. netgen/include/pybind11/detail/function_record_pyobject.h +191 -0
  218. netgen/include/pybind11/detail/init.h +538 -0
  219. netgen/include/pybind11/detail/internals.h +799 -0
  220. netgen/include/pybind11/detail/native_enum_data.h +209 -0
  221. netgen/include/pybind11/detail/pybind11_namespace_macros.h +82 -0
  222. netgen/include/pybind11/detail/struct_smart_holder.h +378 -0
  223. netgen/include/pybind11/detail/type_caster_base.h +1591 -0
  224. netgen/include/pybind11/detail/typeid.h +65 -0
  225. netgen/include/pybind11/detail/using_smart_holder.h +22 -0
  226. netgen/include/pybind11/detail/value_and_holder.h +90 -0
  227. netgen/include/pybind11/eigen/common.h +9 -0
  228. netgen/include/pybind11/eigen/matrix.h +723 -0
  229. netgen/include/pybind11/eigen/tensor.h +521 -0
  230. netgen/include/pybind11/eigen.h +12 -0
  231. netgen/include/pybind11/embed.h +320 -0
  232. netgen/include/pybind11/eval.h +161 -0
  233. netgen/include/pybind11/functional.h +147 -0
  234. netgen/include/pybind11/gil.h +199 -0
  235. netgen/include/pybind11/gil_safe_call_once.h +102 -0
  236. netgen/include/pybind11/gil_simple.h +37 -0
  237. netgen/include/pybind11/iostream.h +265 -0
  238. netgen/include/pybind11/native_enum.h +67 -0
  239. netgen/include/pybind11/numpy.h +2312 -0
  240. netgen/include/pybind11/operators.h +202 -0
  241. netgen/include/pybind11/options.h +92 -0
  242. netgen/include/pybind11/pybind11.h +3645 -0
  243. netgen/include/pybind11/pytypes.h +2680 -0
  244. netgen/include/pybind11/stl/filesystem.h +114 -0
  245. netgen/include/pybind11/stl.h +666 -0
  246. netgen/include/pybind11/stl_bind.h +858 -0
  247. netgen/include/pybind11/subinterpreter.h +299 -0
  248. netgen/include/pybind11/trampoline_self_life_support.h +65 -0
  249. netgen/include/pybind11/type_caster_pyobject_ptr.h +61 -0
  250. netgen/include/pybind11/typing.h +298 -0
  251. netgen/include/pybind11/warnings.h +75 -0
  252. netgen/include/stlgeom/meshstlsurface.hpp +67 -0
  253. netgen/include/stlgeom/stlgeom.hpp +491 -0
  254. netgen/include/stlgeom/stlline.hpp +193 -0
  255. netgen/include/stlgeom/stltool.hpp +331 -0
  256. netgen/include/stlgeom/stltopology.hpp +419 -0
  257. netgen/include/stlgeom/vsstl.hpp +58 -0
  258. netgen/include/visualization/meshdoc.hpp +42 -0
  259. netgen/include/visualization/mvdraw.hpp +325 -0
  260. netgen/include/visualization/vispar.hpp +128 -0
  261. netgen/include/visualization/visual.hpp +28 -0
  262. netgen/include/visualization/visual_api.hpp +10 -0
  263. netgen/include/visualization/vssolution.hpp +399 -0
  264. netgen/lib/libnggui.lib +0 -0
  265. netgen/lib/ngcore.lib +0 -0
  266. netgen/lib/nglib.lib +0 -0
  267. netgen/lib/togl.lib +0 -0
  268. netgen/libnggui.dll +0 -0
  269. netgen/libngguipy.lib +0 -0
  270. netgen/libngguipy.pyd +0 -0
  271. netgen/libngpy/_NgOCC.pyi +1545 -0
  272. netgen/libngpy/__init__.pyi +7 -0
  273. netgen/libngpy/_csg.pyi +259 -0
  274. netgen/libngpy/_geom2d.pyi +323 -0
  275. netgen/libngpy/_meshing.pyi +1111 -0
  276. netgen/libngpy/_stl.pyi +131 -0
  277. netgen/libngpy.lib +0 -0
  278. netgen/libngpy.pyd +0 -0
  279. netgen/meshing.py +65 -0
  280. netgen/ngcore.dll +0 -0
  281. netgen/nglib.dll +0 -0
  282. netgen/occ.py +52 -0
  283. netgen/read_gmsh.py +259 -0
  284. netgen/read_meshio.py +22 -0
  285. netgen/stl.py +2 -0
  286. netgen/togl.dll +0 -0
  287. netgen/version.py +2 -0
  288. netgen/webgui.py +529 -0
  289. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/boundarycondition.geo +16 -0
  290. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/boxcyl.geo +32 -0
  291. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/circle_on_cube.geo +27 -0
  292. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cone.geo +13 -0
  293. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cube.geo +16 -0
  294. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cubeandring.geo +55 -0
  295. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cubeandspheres.geo +21 -0
  296. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cubemcyl.geo +18 -0
  297. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cubemsphere.geo +19 -0
  298. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cylinder.geo +12 -0
  299. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cylsphere.geo +12 -0
  300. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/doc/ng4.pdf +0 -0
  301. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/ellipsoid.geo +8 -0
  302. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/ellipticcyl.geo +10 -0
  303. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/extrusion.geo +99 -0
  304. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/fichera.geo +24 -0
  305. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/frame.step +11683 -0
  306. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/hinge.stl +8486 -0
  307. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/lshape3d.geo +26 -0
  308. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/manyholes.geo +26 -0
  309. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/manyholes2.geo +26 -0
  310. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/matrix.geo +27 -0
  311. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/ortho.geo +11 -0
  312. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/part1.stl +2662 -0
  313. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/period.geo +33 -0
  314. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/py_tutorials/exportNeutral.py +26 -0
  315. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/py_tutorials/mesh.py +19 -0
  316. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/py_tutorials/shaft.geo +65 -0
  317. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/revolution.geo +18 -0
  318. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/screw.step +1694 -0
  319. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/sculpture.geo +13 -0
  320. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/shaft.geo +65 -0
  321. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/shell.geo +10 -0
  322. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/sphere.geo +8 -0
  323. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/sphereincube.geo +17 -0
  324. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/square.in2d +35 -0
  325. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/squarecircle.in2d +48 -0
  326. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/squarehole.in2d +47 -0
  327. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/torus.geo +8 -0
  328. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/trafo.geo +57 -0
  329. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/twobricks.geo +15 -0
  330. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/twocubes.geo +18 -0
  331. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/twocyl.geo +16 -0
  332. netgen_mesher-6.2.2506.post35.dev0.dist-info/METADATA +15 -0
  333. netgen_mesher-6.2.2506.post35.dev0.dist-info/RECORD +340 -0
  334. netgen_mesher-6.2.2506.post35.dev0.dist-info/WHEEL +5 -0
  335. netgen_mesher-6.2.2506.post35.dev0.dist-info/entry_points.txt +2 -0
  336. netgen_mesher-6.2.2506.post35.dev0.dist-info/licenses/AUTHORS +1 -0
  337. netgen_mesher-6.2.2506.post35.dev0.dist-info/licenses/LICENSE +504 -0
  338. netgen_mesher-6.2.2506.post35.dev0.dist-info/top_level.txt +2 -0
  339. pyngcore/__init__.py +1 -0
  340. pyngcore/pyngcore.cp314-win_amd64.pyd +0 -0
@@ -0,0 +1,2680 @@
1
+ /*
2
+ pybind11/pytypes.h: Convenience wrapper classes for basic Python types
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "detail/common.h"
13
+ #include "buffer_info.h"
14
+
15
+ #include <assert.h>
16
+ #include <cstddef>
17
+ #include <exception>
18
+ #include <frameobject.h>
19
+ #include <iterator>
20
+ #include <memory>
21
+ #include <string>
22
+ #include <type_traits>
23
+ #include <typeinfo>
24
+ #include <utility>
25
+
26
+ #if defined(PYBIND11_HAS_OPTIONAL)
27
+ # include <optional>
28
+ #endif
29
+
30
+ #ifdef PYBIND11_HAS_STRING_VIEW
31
+ # include <string_view>
32
+ #endif
33
+
34
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
35
+
36
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
37
+
38
+ /* A few forward declarations */
39
+ class handle;
40
+ class object;
41
+ class str;
42
+ class iterator;
43
+ class type;
44
+ struct arg;
45
+ struct arg_v;
46
+
47
+ PYBIND11_NAMESPACE_BEGIN(detail)
48
+ class args_proxy;
49
+ bool isinstance_generic(handle obj, const std::type_info &tp);
50
+
51
+ template <typename T>
52
+ bool isinstance_native_enum(handle obj, const std::type_info &tp);
53
+
54
+ // Accessor forward declarations
55
+ template <typename Policy>
56
+ class accessor;
57
+ namespace accessor_policies {
58
+ struct obj_attr;
59
+ struct str_attr;
60
+ struct generic_item;
61
+ struct sequence_item;
62
+ struct list_item;
63
+ struct tuple_item;
64
+ } // namespace accessor_policies
65
+ // PLEASE KEEP handle_type_name SPECIALIZATIONS IN SYNC.
66
+ using obj_attr_accessor = accessor<accessor_policies::obj_attr>;
67
+ using str_attr_accessor = accessor<accessor_policies::str_attr>;
68
+ using item_accessor = accessor<accessor_policies::generic_item>;
69
+ using sequence_accessor = accessor<accessor_policies::sequence_item>;
70
+ using list_accessor = accessor<accessor_policies::list_item>;
71
+ using tuple_accessor = accessor<accessor_policies::tuple_item>;
72
+
73
+ /// Tag and check to identify a class which implements the Python object API
74
+ class pyobject_tag {};
75
+ template <typename T>
76
+ using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
77
+
78
+ /** \rst
79
+ A mixin class which adds common functions to `handle`, `object` and various accessors.
80
+ The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``.
81
+ \endrst */
82
+ template <typename Derived>
83
+ class object_api : public pyobject_tag {
84
+ object_api() = default;
85
+ const Derived &derived() const { return static_cast<const Derived &>(*this); }
86
+ friend Derived;
87
+
88
+ public:
89
+ /** \rst
90
+ Return an iterator equivalent to calling ``iter()`` in Python. The object
91
+ must be a collection which supports the iteration protocol.
92
+ \endrst */
93
+ iterator begin() const;
94
+ /// Return a sentinel which ends iteration.
95
+ iterator end() const;
96
+
97
+ /** \rst
98
+ Return an internal functor to invoke the object's sequence protocol. Casting
99
+ the returned ``detail::item_accessor`` instance to a `handle` or `object`
100
+ subclass causes a corresponding call to ``__getitem__``. Assigning a `handle`
101
+ or `object` subclass causes a call to ``__setitem__``.
102
+ \endrst */
103
+ item_accessor operator[](handle key) const;
104
+ /// See above (the only difference is that the key's reference is stolen)
105
+ item_accessor operator[](object &&key) const;
106
+ /// See above (the only difference is that the key is provided as a string literal)
107
+ item_accessor operator[](const char *key) const;
108
+
109
+ /** \rst
110
+ Return an internal functor to access the object's attributes. Casting the
111
+ returned ``detail::obj_attr_accessor`` instance to a `handle` or `object`
112
+ subclass causes a corresponding call to ``getattr``. Assigning a `handle`
113
+ or `object` subclass causes a call to ``setattr``.
114
+ \endrst */
115
+ obj_attr_accessor attr(handle key) const;
116
+ /// See above (the only difference is that the key's reference is stolen)
117
+ obj_attr_accessor attr(object &&key) const;
118
+ /// See above (the only difference is that the key is provided as a string literal)
119
+ str_attr_accessor attr(const char *key) const;
120
+
121
+ /** \rst
122
+ Similar to the above attr functions with the difference that the templated Type
123
+ is used to set the `__annotations__` dict value to the corresponding key. Worth noting
124
+ that attr_with_type_hint is implemented in cast.h.
125
+ \endrst */
126
+ template <typename T>
127
+ obj_attr_accessor attr_with_type_hint(handle key) const;
128
+ /// See above (the only difference is that the key is provided as a string literal)
129
+ template <typename T>
130
+ str_attr_accessor attr_with_type_hint(const char *key) const;
131
+
132
+ /** \rst
133
+ Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple``
134
+ or ``list`` for a function call. Applying another * to the result yields
135
+ ** unpacking, e.g. to unpack a dict as function keyword arguments.
136
+ See :ref:`calling_python_functions`.
137
+ \endrst */
138
+ args_proxy operator*() const;
139
+
140
+ /// Check if the given item is contained within this object, i.e. ``item in obj``.
141
+ template <typename T>
142
+ bool contains(T &&item) const;
143
+
144
+ /** \rst
145
+ Assuming the Python object is a function or implements the ``__call__``
146
+ protocol, ``operator()`` invokes the underlying function, passing an
147
+ arbitrary set of parameters. The result is returned as a `object` and
148
+ may need to be converted back into a Python object using `handle::cast()`.
149
+
150
+ When some of the arguments cannot be converted to Python objects, the
151
+ function will throw a `cast_error` exception. When the Python function
152
+ call fails, a `error_already_set` exception is thrown.
153
+ \endrst */
154
+ template <return_value_policy policy = return_value_policy::automatic_reference,
155
+ typename... Args>
156
+ object operator()(Args &&...args) const;
157
+ template <return_value_policy policy = return_value_policy::automatic_reference,
158
+ typename... Args>
159
+ PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)")
160
+ object call(Args &&...args) const;
161
+
162
+ /// Equivalent to ``obj is other`` in Python.
163
+ bool is(object_api const &other) const { return derived().ptr() == other.derived().ptr(); }
164
+ /// Equivalent to ``obj is None`` in Python.
165
+ bool is_none() const { return derived().ptr() == Py_None; }
166
+ /// Equivalent to obj == other in Python
167
+ bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); }
168
+ bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); }
169
+ bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); }
170
+ bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); }
171
+ bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); }
172
+ bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); }
173
+
174
+ object operator-() const;
175
+ object operator~() const;
176
+ object operator+(object_api const &other) const;
177
+ object operator+=(object_api const &other);
178
+ object operator-(object_api const &other) const;
179
+ object operator-=(object_api const &other);
180
+ object operator*(object_api const &other) const;
181
+ object operator*=(object_api const &other);
182
+ object operator/(object_api const &other) const;
183
+ object operator/=(object_api const &other);
184
+ object operator|(object_api const &other) const;
185
+ object operator|=(object_api const &other);
186
+ object operator&(object_api const &other) const;
187
+ object operator&=(object_api const &other);
188
+ object operator^(object_api const &other) const;
189
+ object operator^=(object_api const &other);
190
+ object operator<<(object_api const &other) const;
191
+ object operator<<=(object_api const &other);
192
+ object operator>>(object_api const &other) const;
193
+ object operator>>=(object_api const &other);
194
+
195
+ PYBIND11_DEPRECATED("Use py::str(obj) instead")
196
+ pybind11::str str() const;
197
+
198
+ /// Get or set the object's docstring, i.e. ``obj.__doc__``.
199
+ str_attr_accessor doc() const;
200
+
201
+ /// Get or set the object's annotations, i.e. ``obj.__annotations__``.
202
+ object annotations() const;
203
+
204
+ /// Return the object's current reference count
205
+ ssize_t ref_count() const {
206
+ #ifdef PYPY_VERSION
207
+ // PyPy uses the top few bits for REFCNT_FROM_PYPY & REFCNT_FROM_PYPY_LIGHT
208
+ // Following pybind11 2.12.1 and older behavior and removing this part
209
+ return static_cast<ssize_t>(static_cast<int>(Py_REFCNT(derived().ptr())));
210
+ #else
211
+ return Py_REFCNT(derived().ptr());
212
+ #endif
213
+ }
214
+
215
+ PYBIND11_DEPRECATED("Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()")
216
+ handle get_type() const;
217
+
218
+ private:
219
+ bool rich_compare(object_api const &other, int value) const;
220
+ };
221
+
222
+ template <typename T>
223
+ using is_pyobj_ptr_or_nullptr_t = detail::any_of<std::is_same<T, PyObject *>,
224
+ std::is_same<T, PyObject *const>,
225
+ std::is_same<T, std::nullptr_t>>;
226
+
227
+ PYBIND11_NAMESPACE_END(detail)
228
+
229
+ #if !defined(PYBIND11_HANDLE_REF_DEBUG) && !defined(NDEBUG)
230
+ # define PYBIND11_HANDLE_REF_DEBUG
231
+ #endif
232
+
233
+ /** \rst
234
+ Holds a reference to a Python object (no reference counting)
235
+
236
+ The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a
237
+ ``PyObject *`` in Python's C API). It does not perform any automatic reference
238
+ counting and merely provides a basic C++ interface to various Python API functions.
239
+
240
+ .. seealso::
241
+ The `object` class inherits from `handle` and adds automatic reference
242
+ counting features.
243
+ \endrst */
244
+ class handle : public detail::object_api<handle> {
245
+ public:
246
+ /// The default constructor creates a handle with a ``nullptr``-valued pointer
247
+ handle() = default;
248
+
249
+ /// Enable implicit conversion from ``PyObject *`` and ``nullptr``.
250
+ /// Not using ``handle(PyObject *ptr)`` to avoid implicit conversion from ``0``.
251
+ template <typename T,
252
+ detail::enable_if_t<detail::is_pyobj_ptr_or_nullptr_t<T>::value, int> = 0>
253
+ // NOLINTNEXTLINE(google-explicit-constructor)
254
+ handle(T ptr) : m_ptr(ptr) {}
255
+
256
+ /// Enable implicit conversion through ``T::operator PyObject *()``.
257
+ template <
258
+ typename T,
259
+ detail::enable_if_t<detail::all_of<detail::none_of<std::is_base_of<handle, T>,
260
+ detail::is_pyobj_ptr_or_nullptr_t<T>>,
261
+ std::is_convertible<T, PyObject *>>::value,
262
+ int>
263
+ = 0>
264
+ // NOLINTNEXTLINE(google-explicit-constructor)
265
+ handle(T &obj) : m_ptr(obj) {}
266
+
267
+ /// Return the underlying ``PyObject *`` pointer
268
+ PyObject *ptr() const { return m_ptr; }
269
+ PyObject *&ptr() { return m_ptr; }
270
+
271
+ /** \rst
272
+ Manually increase the reference count of the Python object. Usually, it is
273
+ preferable to use the `object` class which derives from `handle` and calls
274
+ this function automatically. Returns a reference to itself.
275
+ \endrst */
276
+ const handle &inc_ref() const & {
277
+ #ifdef PYBIND11_HANDLE_REF_DEBUG
278
+ inc_ref_counter(1);
279
+ #endif
280
+ #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
281
+ if (m_ptr != nullptr && PyGILState_Check() == 0) {
282
+ throw_gilstate_error("pybind11::handle::inc_ref()");
283
+ }
284
+ #endif
285
+ Py_XINCREF(m_ptr);
286
+ return *this;
287
+ }
288
+
289
+ /** \rst
290
+ Manually decrease the reference count of the Python object. Usually, it is
291
+ preferable to use the `object` class which derives from `handle` and calls
292
+ this function automatically. Returns a reference to itself.
293
+ \endrst */
294
+ const handle &dec_ref() const & {
295
+ #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
296
+ if (m_ptr != nullptr && PyGILState_Check() == 0) {
297
+ throw_gilstate_error("pybind11::handle::dec_ref()");
298
+ }
299
+ #endif
300
+ Py_XDECREF(m_ptr);
301
+ return *this;
302
+ }
303
+
304
+ /** \rst
305
+ Attempt to cast the Python object into the given C++ type. A `cast_error`
306
+ will be throw upon failure.
307
+ \endrst */
308
+ template <typename T>
309
+ T cast() const;
310
+ /// Return ``true`` when the `handle` wraps a valid Python object
311
+ explicit operator bool() const { return m_ptr != nullptr; }
312
+ /** \rst
313
+ Deprecated: Check that the underlying pointers are the same.
314
+ Equivalent to ``obj1 is obj2`` in Python.
315
+ \endrst */
316
+ PYBIND11_DEPRECATED("Use obj1.is(obj2) instead")
317
+ bool operator==(const handle &h) const { return m_ptr == h.m_ptr; }
318
+ PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead")
319
+ bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }
320
+ PYBIND11_DEPRECATED("Use handle::operator bool() instead")
321
+ bool check() const { return m_ptr != nullptr; }
322
+
323
+ protected:
324
+ PyObject *m_ptr = nullptr;
325
+
326
+ private:
327
+ #ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
328
+ void throw_gilstate_error(const std::string &function_name) const {
329
+ fprintf(
330
+ stderr,
331
+ "%s is being called while the GIL is either not held or invalid. Please see "
332
+ "https://pybind11.readthedocs.io/en/stable/advanced/"
333
+ "misc.html#common-sources-of-global-interpreter-lock-errors for debugging advice.\n"
334
+ "If you are convinced there is no bug in your code, you can #define "
335
+ "PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF "
336
+ "to disable this check. In that case you have to ensure this #define is consistently "
337
+ "used for all translation units linked into a given pybind11 extension, otherwise "
338
+ "there will be ODR violations.",
339
+ function_name.c_str());
340
+ if (Py_TYPE(m_ptr)->tp_name != nullptr) {
341
+ fprintf(stderr,
342
+ " The failing %s call was triggered on a %s object.",
343
+ function_name.c_str(),
344
+ Py_TYPE(m_ptr)->tp_name);
345
+ }
346
+ fprintf(stderr, "\n");
347
+ fflush(stderr);
348
+ throw std::runtime_error(function_name + " PyGILState_Check() failure.");
349
+ }
350
+ #endif
351
+
352
+ #ifdef PYBIND11_HANDLE_REF_DEBUG
353
+ static std::size_t inc_ref_counter(std::size_t add) {
354
+ thread_local std::size_t counter = 0;
355
+ counter += add;
356
+ return counter;
357
+ }
358
+
359
+ public:
360
+ static std::size_t inc_ref_counter() { return inc_ref_counter(0); }
361
+ #endif
362
+ };
363
+
364
+ inline void set_error(const handle &type, const char *message) {
365
+ PyErr_SetString(type.ptr(), message);
366
+ }
367
+
368
+ inline void set_error(const handle &type, const handle &value) {
369
+ PyErr_SetObject(type.ptr(), value.ptr());
370
+ }
371
+
372
+ /** \rst
373
+ Holds a reference to a Python object (with reference counting)
374
+
375
+ Like `handle`, the `object` class is a thin wrapper around an arbitrary Python
376
+ object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it
377
+ optionally increases the object's reference count upon construction, and it
378
+ *always* decreases the reference count when the `object` instance goes out of
379
+ scope and is destructed. When using `object` instances consistently, it is much
380
+ easier to get reference counting right at the first attempt.
381
+ \endrst */
382
+ class object : public handle {
383
+ public:
384
+ object() = default;
385
+ PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()")
386
+ object(handle h, bool is_borrowed) : handle(h) {
387
+ if (is_borrowed) {
388
+ inc_ref();
389
+ }
390
+ }
391
+ /// Copy constructor; always increases the reference count
392
+ object(const object &o) : handle(o) { inc_ref(); }
393
+ /// Move constructor; steals the object from ``other`` and preserves its reference count
394
+ object(object &&other) noexcept : handle(other) { other.m_ptr = nullptr; }
395
+ /// Destructor; automatically calls `handle::dec_ref()`
396
+ ~object() { dec_ref(); }
397
+
398
+ /** \rst
399
+ Resets the internal pointer to ``nullptr`` without decreasing the
400
+ object's reference count. The function returns a raw handle to the original
401
+ Python object.
402
+ \endrst */
403
+ handle release() {
404
+ PyObject *tmp = m_ptr;
405
+ m_ptr = nullptr;
406
+ return handle(tmp);
407
+ }
408
+
409
+ object &operator=(const object &other) {
410
+ // Skip inc_ref and dec_ref if both objects are the same
411
+ if (!this->is(other)) {
412
+ other.inc_ref();
413
+ // Use temporary variable to ensure `*this` remains valid while
414
+ // `Py_XDECREF` executes, in case `*this` is accessible from Python.
415
+ handle temp(m_ptr);
416
+ m_ptr = other.m_ptr;
417
+ temp.dec_ref();
418
+ }
419
+ return *this;
420
+ }
421
+
422
+ object &operator=(object &&other) noexcept {
423
+ if (this != &other) {
424
+ handle temp(m_ptr);
425
+ m_ptr = other.m_ptr;
426
+ other.m_ptr = nullptr;
427
+ temp.dec_ref();
428
+ }
429
+ return *this;
430
+ }
431
+
432
+ #define PYBIND11_INPLACE_OP(iop) \
433
+ object iop(object_api const &other) { return operator=(handle::iop(other)); }
434
+
435
+ PYBIND11_INPLACE_OP(operator+=)
436
+ PYBIND11_INPLACE_OP(operator-=)
437
+ PYBIND11_INPLACE_OP(operator*=)
438
+ PYBIND11_INPLACE_OP(operator/=)
439
+ PYBIND11_INPLACE_OP(operator|=)
440
+ PYBIND11_INPLACE_OP(operator&=)
441
+ PYBIND11_INPLACE_OP(operator^=)
442
+ PYBIND11_INPLACE_OP(operator<<=)
443
+ PYBIND11_INPLACE_OP(operator>>=)
444
+ #undef PYBIND11_INPLACE_OP
445
+
446
+ // Calling cast() on an object lvalue just copies (via handle::cast)
447
+ template <typename T>
448
+ T cast() const &;
449
+ // Calling on an object rvalue does a move, if needed and/or possible
450
+ template <typename T>
451
+ T cast() &&;
452
+
453
+ protected:
454
+ // Tags for choosing constructors from raw PyObject *
455
+ struct borrowed_t {};
456
+ struct stolen_t {};
457
+
458
+ /// @cond BROKEN
459
+ template <typename T>
460
+ friend T reinterpret_borrow(handle);
461
+ template <typename T>
462
+ friend T reinterpret_steal(handle);
463
+ /// @endcond
464
+
465
+ public:
466
+ // Only accessible from derived classes and the reinterpret_* functions
467
+ object(handle h, borrowed_t) : handle(h) { inc_ref(); }
468
+ object(handle h, stolen_t) : handle(h) {}
469
+ };
470
+
471
+ /** \rst
472
+ Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference.
473
+ The target type ``T`` must be `object` or one of its derived classes. The function
474
+ doesn't do any conversions or checks. It's up to the user to make sure that the
475
+ target type is correct.
476
+
477
+ .. code-block:: cpp
478
+
479
+ PyObject *p = PyList_GetItem(obj, index);
480
+ py::object o = reinterpret_borrow<py::object>(p);
481
+ // or
482
+ py::tuple t = reinterpret_borrow<py::tuple>(p); // <-- `p` must be already be a `tuple`
483
+ \endrst */
484
+ template <typename T>
485
+ T reinterpret_borrow(handle h) {
486
+ return {h, object::borrowed_t{}};
487
+ }
488
+
489
+ /** \rst
490
+ Like `reinterpret_borrow`, but steals the reference.
491
+
492
+ .. code-block:: cpp
493
+
494
+ PyObject *p = PyObject_Str(obj);
495
+ py::str s = reinterpret_steal<py::str>(p); // <-- `p` must be already be a `str`
496
+ \endrst */
497
+ template <typename T>
498
+ T reinterpret_steal(handle h) {
499
+ return {h, object::stolen_t{}};
500
+ }
501
+
502
+ PYBIND11_NAMESPACE_BEGIN(detail)
503
+
504
+ // Equivalent to obj.__class__.__name__ (or obj.__name__ if obj is a class).
505
+ inline const char *obj_class_name(PyObject *obj) {
506
+ if (PyType_Check(obj)) {
507
+ return reinterpret_cast<PyTypeObject *>(obj)->tp_name;
508
+ }
509
+ return Py_TYPE(obj)->tp_name;
510
+ }
511
+
512
+ std::string error_string();
513
+
514
+ // The code in this struct is very unusual, to minimize the chances of
515
+ // masking bugs (elsewhere) by errors during the error handling (here).
516
+ // This is meant to be a lifeline for troubleshooting long-running processes
517
+ // that crash under conditions that are virtually impossible to reproduce.
518
+ // Low-level implementation alternatives are preferred to higher-level ones
519
+ // that might raise cascading exceptions. Last-ditch-kind-of attempts are made
520
+ // to report as much of the original error as possible, even if there are
521
+ // secondary issues obtaining some of the details.
522
+ struct error_fetch_and_normalize {
523
+ // This comment only applies to Python <= 3.11:
524
+ // Immediate normalization is long-established behavior (starting with
525
+ // https://github.com/pybind/pybind11/commit/135ba8deafb8bf64a15b24d1513899eb600e2011
526
+ // from Sep 2016) and safest. Normalization could be deferred, but this could mask
527
+ // errors elsewhere, the performance gain is very minor in typical situations
528
+ // (usually the dominant bottleneck is EH unwinding), and the implementation here
529
+ // would be more complex.
530
+ // Starting with Python 3.12, PyErr_Fetch() normalizes exceptions immediately.
531
+ // Any errors during normalization are tracked under __notes__.
532
+ explicit error_fetch_and_normalize(const char *called) {
533
+ PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
534
+ if (!m_type) {
535
+ pybind11_fail("Internal error: " + std::string(called)
536
+ + " called while "
537
+ "Python error indicator not set.");
538
+ }
539
+ const char *exc_type_name_orig = detail::obj_class_name(m_type.ptr());
540
+ if (exc_type_name_orig == nullptr) {
541
+ pybind11_fail("Internal error: " + std::string(called)
542
+ + " failed to obtain the name "
543
+ "of the original active exception type.");
544
+ }
545
+ m_lazy_error_string = exc_type_name_orig;
546
+ #if PY_VERSION_HEX >= 0x030C0000
547
+ // The presence of __notes__ is likely due to exception normalization
548
+ // errors, although that is not necessarily true, therefore insert a
549
+ // hint only:
550
+ if (PyObject_HasAttrString(m_value.ptr(), "__notes__")) {
551
+ m_lazy_error_string += "[WITH __notes__]";
552
+ }
553
+ #else
554
+ // PyErr_NormalizeException() may change the exception type if there are cascading
555
+ // failures. This can potentially be extremely confusing.
556
+ PyErr_NormalizeException(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
557
+ if (m_type.ptr() == nullptr) {
558
+ pybind11_fail("Internal error: " + std::string(called)
559
+ + " failed to normalize the "
560
+ "active exception.");
561
+ }
562
+ const char *exc_type_name_norm = detail::obj_class_name(m_type.ptr());
563
+ if (exc_type_name_norm == nullptr) {
564
+ pybind11_fail("Internal error: " + std::string(called)
565
+ + " failed to obtain the name "
566
+ "of the normalized active exception type.");
567
+ }
568
+ if (exc_type_name_norm != m_lazy_error_string) {
569
+ std::string msg = std::string(called)
570
+ + ": MISMATCH of original and normalized "
571
+ "active exception types: ";
572
+ msg += "ORIGINAL ";
573
+ msg += m_lazy_error_string;
574
+ msg += " REPLACED BY ";
575
+ msg += exc_type_name_norm;
576
+ msg += ": " + format_value_and_trace();
577
+ pybind11_fail(msg);
578
+ }
579
+ #endif
580
+ }
581
+
582
+ error_fetch_and_normalize(const error_fetch_and_normalize &) = delete;
583
+ error_fetch_and_normalize(error_fetch_and_normalize &&) = delete;
584
+
585
+ std::string format_value_and_trace() const {
586
+ std::string result;
587
+ std::string message_error_string;
588
+ if (m_value) {
589
+ auto value_str = reinterpret_steal<object>(PyObject_Str(m_value.ptr()));
590
+ constexpr const char *message_unavailable_exc
591
+ = "<MESSAGE UNAVAILABLE DUE TO ANOTHER EXCEPTION>";
592
+ if (!value_str) {
593
+ message_error_string = detail::error_string();
594
+ result = message_unavailable_exc;
595
+ } else {
596
+ // Not using `value_str.cast<std::string>()`, to not potentially throw a secondary
597
+ // error_already_set that will then result in process termination (#4288).
598
+ auto value_bytes = reinterpret_steal<object>(
599
+ PyUnicode_AsEncodedString(value_str.ptr(), "utf-8", "backslashreplace"));
600
+ if (!value_bytes) {
601
+ message_error_string = detail::error_string();
602
+ result = message_unavailable_exc;
603
+ } else {
604
+ char *buffer = nullptr;
605
+ Py_ssize_t length = 0;
606
+ if (PyBytes_AsStringAndSize(value_bytes.ptr(), &buffer, &length) == -1) {
607
+ message_error_string = detail::error_string();
608
+ result = message_unavailable_exc;
609
+ } else {
610
+ result = std::string(buffer, static_cast<std::size_t>(length));
611
+ }
612
+ }
613
+ }
614
+ #if PY_VERSION_HEX >= 0x030B0000
615
+ auto notes
616
+ = reinterpret_steal<object>(PyObject_GetAttrString(m_value.ptr(), "__notes__"));
617
+ if (!notes) {
618
+ PyErr_Clear(); // No notes is good news.
619
+ } else {
620
+ auto len_notes = PyList_Size(notes.ptr());
621
+ if (len_notes < 0) {
622
+ result += "\nFAILURE obtaining len(__notes__): " + detail::error_string();
623
+ } else {
624
+ result += "\n__notes__ (len=" + std::to_string(len_notes) + "):";
625
+ for (ssize_t i = 0; i < len_notes; i++) {
626
+ PyObject *note = PyList_GET_ITEM(notes.ptr(), i);
627
+ auto note_bytes = reinterpret_steal<object>(
628
+ PyUnicode_AsEncodedString(note, "utf-8", "backslashreplace"));
629
+ if (!note_bytes) {
630
+ result += "\nFAILURE obtaining __notes__[" + std::to_string(i)
631
+ + "]: " + detail::error_string();
632
+ } else {
633
+ char *buffer = nullptr;
634
+ Py_ssize_t length = 0;
635
+ if (PyBytes_AsStringAndSize(note_bytes.ptr(), &buffer, &length)
636
+ == -1) {
637
+ result += "\nFAILURE formatting __notes__[" + std::to_string(i)
638
+ + "]: " + detail::error_string();
639
+ } else {
640
+ result += '\n';
641
+ result += std::string(buffer, static_cast<std::size_t>(length));
642
+ }
643
+ }
644
+ }
645
+ }
646
+ }
647
+ #endif
648
+ } else {
649
+ result = "<MESSAGE UNAVAILABLE>";
650
+ }
651
+ if (result.empty()) {
652
+ result = "<EMPTY MESSAGE>";
653
+ }
654
+
655
+ bool have_trace = false;
656
+ if (m_trace) {
657
+ #if !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON)
658
+ auto *tb = reinterpret_cast<PyTracebackObject *>(m_trace.ptr());
659
+
660
+ // Get the deepest trace possible.
661
+ while (tb->tb_next) {
662
+ tb = tb->tb_next;
663
+ }
664
+
665
+ PyFrameObject *frame = tb->tb_frame;
666
+ Py_XINCREF(frame);
667
+ result += "\n\nAt:\n";
668
+ while (frame) {
669
+ # if PY_VERSION_HEX >= 0x030900B1
670
+ PyCodeObject *f_code = PyFrame_GetCode(frame);
671
+ # else
672
+ PyCodeObject *f_code = frame->f_code;
673
+ Py_INCREF(f_code);
674
+ # endif
675
+ int lineno = PyFrame_GetLineNumber(frame);
676
+ result += " ";
677
+ result += handle(f_code->co_filename).cast<std::string>();
678
+ result += '(';
679
+ result += std::to_string(lineno);
680
+ result += "): ";
681
+ result += handle(f_code->co_name).cast<std::string>();
682
+ result += '\n';
683
+ Py_DECREF(f_code);
684
+ # if PY_VERSION_HEX >= 0x030900B1
685
+ auto *b_frame = PyFrame_GetBack(frame);
686
+ # else
687
+ auto *b_frame = frame->f_back;
688
+ Py_XINCREF(b_frame);
689
+ # endif
690
+ Py_DECREF(frame);
691
+ frame = b_frame;
692
+ }
693
+
694
+ have_trace = true;
695
+ #endif //! defined(PYPY_VERSION)
696
+ }
697
+
698
+ if (!message_error_string.empty()) {
699
+ if (!have_trace) {
700
+ result += '\n';
701
+ }
702
+ result += "\nMESSAGE UNAVAILABLE DUE TO EXCEPTION: " + message_error_string;
703
+ }
704
+
705
+ return result;
706
+ }
707
+
708
+ std::string const &error_string() const {
709
+ if (!m_lazy_error_string_completed) {
710
+ m_lazy_error_string += ": " + format_value_and_trace();
711
+ m_lazy_error_string_completed = true;
712
+ }
713
+ return m_lazy_error_string;
714
+ }
715
+
716
+ void restore() {
717
+ if (m_restore_called) {
718
+ pybind11_fail("Internal error: pybind11::detail::error_fetch_and_normalize::restore() "
719
+ "called a second time. ORIGINAL ERROR: "
720
+ + error_string());
721
+ }
722
+ PyErr_Restore(m_type.inc_ref().ptr(), m_value.inc_ref().ptr(), m_trace.inc_ref().ptr());
723
+ m_restore_called = true;
724
+ }
725
+
726
+ bool matches(handle exc) const {
727
+ return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0);
728
+ }
729
+
730
+ // Not protecting these for simplicity.
731
+ object m_type, m_value, m_trace;
732
+
733
+ private:
734
+ // Only protecting invariants.
735
+ mutable std::string m_lazy_error_string;
736
+ mutable bool m_lazy_error_string_completed = false;
737
+ mutable bool m_restore_called = false;
738
+ };
739
+
740
+ inline std::string error_string() {
741
+ return error_fetch_and_normalize("pybind11::detail::error_string").error_string();
742
+ }
743
+
744
+ PYBIND11_NAMESPACE_END(detail)
745
+
746
+ /// Fetch and hold an error which was already set in Python. An instance of this is typically
747
+ /// thrown to propagate python-side errors back through C++ which can either be caught manually or
748
+ /// else falls back to the function dispatcher (which then raises the captured error back to
749
+ /// python).
750
+ class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::exception {
751
+ public:
752
+ /// Fetches the current Python exception (using PyErr_Fetch()), which will clear the
753
+ /// current Python error indicator.
754
+ error_already_set()
755
+ : m_fetched_error{new detail::error_fetch_and_normalize("pybind11::error_already_set"),
756
+ m_fetched_error_deleter} {}
757
+
758
+ /// The what() result is built lazily on demand.
759
+ /// WARNING: This member function needs to acquire the Python GIL. This can lead to
760
+ /// crashes (undefined behavior) if the Python interpreter is finalizing.
761
+ const char *what() const noexcept override;
762
+
763
+ /// Restores the currently-held Python error (which will clear the Python error indicator first
764
+ /// if already set).
765
+ /// NOTE: This member function will always restore the normalized exception, which may or may
766
+ /// not be the original Python exception.
767
+ /// WARNING: The GIL must be held when this member function is called!
768
+ void restore() { m_fetched_error->restore(); }
769
+
770
+ /// If it is impossible to raise the currently-held error, such as in a destructor, we can
771
+ /// write it out using Python's unraisable hook (`sys.unraisablehook`). The error context
772
+ /// should be some object whose `repr()` helps identify the location of the error. Python
773
+ /// already knows the type and value of the error, so there is no need to repeat that.
774
+ void discard_as_unraisable(object err_context) {
775
+ restore();
776
+ PyErr_WriteUnraisable(err_context.ptr());
777
+ }
778
+ /// An alternate version of `discard_as_unraisable()`, where a string provides information on
779
+ /// the location of the error. For example, `__func__` could be helpful.
780
+ /// WARNING: The GIL must be held when this member function is called!
781
+ void discard_as_unraisable(const char *err_context) {
782
+ discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context)));
783
+ }
784
+
785
+ // Does nothing; provided for backwards compatibility.
786
+ PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated")
787
+ void clear() {}
788
+
789
+ /// Check if the currently trapped error type matches the given Python exception class (or a
790
+ /// subclass thereof). May also be passed a tuple to search for any exception class matches in
791
+ /// the given tuple.
792
+ bool matches(handle exc) const { return m_fetched_error->matches(exc); }
793
+
794
+ const object &type() const { return m_fetched_error->m_type; }
795
+ const object &value() const { return m_fetched_error->m_value; }
796
+ const object &trace() const { return m_fetched_error->m_trace; }
797
+
798
+ private:
799
+ std::shared_ptr<detail::error_fetch_and_normalize> m_fetched_error;
800
+
801
+ /// WARNING: This custom deleter needs to acquire the Python GIL. This can lead to
802
+ /// crashes (undefined behavior) if the Python interpreter is finalizing.
803
+ static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr);
804
+ };
805
+
806
+ /// Replaces the current Python error indicator with the chosen error, performing a
807
+ /// 'raise from' to indicate that the chosen error was caused by the original error.
808
+ inline void raise_from(PyObject *type, const char *message) {
809
+ // Based on _PyErr_FormatVFromCause:
810
+ // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405
811
+ // See https://github.com/pybind/pybind11/pull/2112 for details.
812
+ PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr;
813
+
814
+ assert(PyErr_Occurred());
815
+ PyErr_Fetch(&exc, &val, &tb);
816
+ PyErr_NormalizeException(&exc, &val, &tb);
817
+ if (tb != nullptr) {
818
+ PyException_SetTraceback(val, tb);
819
+ Py_DECREF(tb);
820
+ }
821
+ Py_DECREF(exc);
822
+ assert(!PyErr_Occurred());
823
+
824
+ PyErr_SetString(type, message);
825
+
826
+ PyErr_Fetch(&exc, &val2, &tb);
827
+ PyErr_NormalizeException(&exc, &val2, &tb);
828
+ Py_INCREF(val);
829
+ PyException_SetCause(val2, val);
830
+ PyException_SetContext(val2, val);
831
+ PyErr_Restore(exc, val2, tb);
832
+ }
833
+
834
+ /// Sets the current Python error indicator with the chosen error, performing a 'raise from'
835
+ /// from the error contained in error_already_set to indicate that the chosen error was
836
+ /// caused by the original error.
837
+ inline void raise_from(error_already_set &err, PyObject *type, const char *message) {
838
+ err.restore();
839
+ raise_from(type, message);
840
+ }
841
+
842
+ /** \defgroup python_builtins const_name
843
+ Unless stated otherwise, the following C++ functions behave the same
844
+ as their Python counterparts.
845
+ */
846
+
847
+ /** \ingroup python_builtins
848
+ \rst
849
+ Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of
850
+ `object` or a class which was exposed to Python as ``py::class_<T>``.
851
+ \endrst */
852
+ template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0>
853
+ bool isinstance(handle obj) {
854
+ return T::check_(obj);
855
+ }
856
+
857
+ template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0>
858
+ bool isinstance(handle obj) {
859
+ return detail::isinstance_native_enum<T>(obj, typeid(T))
860
+ || detail::isinstance_generic(obj, typeid(T));
861
+ }
862
+
863
+ template <>
864
+ inline bool isinstance<handle>(handle) = delete;
865
+ template <>
866
+ inline bool isinstance<object>(handle obj) {
867
+ return obj.ptr() != nullptr;
868
+ }
869
+
870
+ /// \ingroup python_builtins
871
+ /// Return true if ``obj`` is an instance of the ``type``.
872
+ inline bool isinstance(handle obj, handle type) {
873
+ const auto result = PyObject_IsInstance(obj.ptr(), type.ptr());
874
+ if (result == -1) {
875
+ throw error_already_set();
876
+ }
877
+ return result != 0;
878
+ }
879
+
880
+ /// \addtogroup python_builtins
881
+ /// @{
882
+ inline bool hasattr(handle obj, handle name) {
883
+ return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1;
884
+ }
885
+
886
+ inline bool hasattr(handle obj, const char *name) {
887
+ return PyObject_HasAttrString(obj.ptr(), name) == 1;
888
+ }
889
+
890
+ inline void delattr(handle obj, handle name) {
891
+ if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) {
892
+ throw error_already_set();
893
+ }
894
+ }
895
+
896
+ inline void delattr(handle obj, const char *name) {
897
+ if (PyObject_DelAttrString(obj.ptr(), name) != 0) {
898
+ throw error_already_set();
899
+ }
900
+ }
901
+
902
+ inline object getattr(handle obj, handle name) {
903
+ PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr());
904
+ if (!result) {
905
+ throw error_already_set();
906
+ }
907
+ return reinterpret_steal<object>(result);
908
+ }
909
+
910
+ inline object getattr(handle obj, const char *name) {
911
+ PyObject *result = PyObject_GetAttrString(obj.ptr(), name);
912
+ if (!result) {
913
+ throw error_already_set();
914
+ }
915
+ return reinterpret_steal<object>(result);
916
+ }
917
+
918
+ inline object getattr(handle obj, handle name, handle default_) {
919
+ if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) {
920
+ return reinterpret_steal<object>(result);
921
+ }
922
+ PyErr_Clear();
923
+ return reinterpret_borrow<object>(default_);
924
+ }
925
+
926
+ inline object getattr(handle obj, const char *name, handle default_) {
927
+ if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) {
928
+ return reinterpret_steal<object>(result);
929
+ }
930
+ PyErr_Clear();
931
+ return reinterpret_borrow<object>(default_);
932
+ }
933
+
934
+ inline void setattr(handle obj, handle name, handle value) {
935
+ if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) {
936
+ throw error_already_set();
937
+ }
938
+ }
939
+
940
+ inline void setattr(handle obj, const char *name, handle value) {
941
+ if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) {
942
+ throw error_already_set();
943
+ }
944
+ }
945
+
946
+ inline ssize_t hash(handle obj) {
947
+ auto h = PyObject_Hash(obj.ptr());
948
+ if (h == -1) {
949
+ throw error_already_set();
950
+ }
951
+ return h;
952
+ }
953
+
954
+ /// @} python_builtins
955
+
956
+ PYBIND11_NAMESPACE_BEGIN(detail)
957
+ inline handle get_function(handle value) {
958
+ if (value) {
959
+ if (PyInstanceMethod_Check(value.ptr())) {
960
+ value = PyInstanceMethod_GET_FUNCTION(value.ptr());
961
+ } else if (PyMethod_Check(value.ptr())) {
962
+ value = PyMethod_GET_FUNCTION(value.ptr());
963
+ }
964
+ }
965
+ return value;
966
+ }
967
+
968
+ // Reimplementation of python's dict helper functions to ensure that exceptions
969
+ // aren't swallowed (see #2862)
970
+
971
+ // copied from cpython _PyDict_GetItemStringWithError
972
+ inline PyObject *dict_getitemstring(PyObject *v, const char *key) {
973
+ PyObject *kv = nullptr, *rv = nullptr;
974
+ kv = PyUnicode_FromString(key);
975
+ if (kv == nullptr) {
976
+ throw error_already_set();
977
+ }
978
+
979
+ rv = PyDict_GetItemWithError(v, kv);
980
+ Py_DECREF(kv);
981
+ if (rv == nullptr && PyErr_Occurred()) {
982
+ throw error_already_set();
983
+ }
984
+ return rv;
985
+ }
986
+
987
+ inline PyObject *dict_getitem(PyObject *v, PyObject *key) {
988
+ PyObject *rv = PyDict_GetItemWithError(v, key);
989
+ if (rv == nullptr && PyErr_Occurred()) {
990
+ throw error_already_set();
991
+ }
992
+ return rv;
993
+ }
994
+
995
+ inline PyObject *dict_getitemstringref(PyObject *v, const char *key) {
996
+ #if PY_VERSION_HEX >= 0x030D0000
997
+ PyObject *rv;
998
+ if (PyDict_GetItemStringRef(v, key, &rv) < 0) {
999
+ throw error_already_set();
1000
+ }
1001
+ return rv;
1002
+ #else
1003
+ PyObject *rv = dict_getitemstring(v, key);
1004
+ if (rv == nullptr && PyErr_Occurred()) {
1005
+ throw error_already_set();
1006
+ }
1007
+ Py_XINCREF(rv);
1008
+ return rv;
1009
+ #endif
1010
+ }
1011
+
1012
+ // Helper aliases/functions to support implicit casting of values given to python
1013
+ // accessors/methods. When given a pyobject, this simply returns the pyobject as-is; for other C++
1014
+ // type, the value goes through pybind11::cast(obj) to convert it to an `object`.
1015
+ template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0>
1016
+ auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) {
1017
+ return std::forward<T>(o);
1018
+ }
1019
+ // The following casting version is implemented in cast.h:
1020
+ template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0>
1021
+ object object_or_cast(T &&o);
1022
+ // Match a PyObject*, which we want to convert directly to handle via its converting constructor
1023
+ inline handle object_or_cast(PyObject *ptr) { return ptr; }
1024
+
1025
+ PYBIND11_WARNING_PUSH
1026
+ PYBIND11_WARNING_DISABLE_MSVC(4522) // warning C4522: multiple assignment operators specified
1027
+ template <typename Policy>
1028
+ class accessor : public object_api<accessor<Policy>> {
1029
+ using key_type = typename Policy::key_type;
1030
+
1031
+ public:
1032
+ accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) {}
1033
+ accessor(const accessor &) = default;
1034
+ accessor(accessor &&) noexcept = default;
1035
+
1036
+ // accessor overload required to override default assignment operator (templates are not
1037
+ // allowed to replace default compiler-generated assignments).
1038
+ void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); }
1039
+ void operator=(const accessor &a) & { operator=(handle(a)); }
1040
+
1041
+ template <typename T>
1042
+ void operator=(T &&value) && {
1043
+ Policy::set(obj, key, object_or_cast(std::forward<T>(value)));
1044
+ }
1045
+ template <typename T>
1046
+ void operator=(T &&value) & {
1047
+ get_cache() = ensure_object(object_or_cast(std::forward<T>(value)));
1048
+ }
1049
+
1050
+ template <typename T = Policy>
1051
+ PYBIND11_DEPRECATED(
1052
+ "Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
1053
+ explicit
1054
+ operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value
1055
+ || std::is_same<T, accessor_policies::obj_attr>::value,
1056
+ bool>() const {
1057
+ return hasattr(obj, key);
1058
+ }
1059
+ template <typename T = Policy>
1060
+ PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
1061
+ explicit
1062
+ operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const {
1063
+ return obj.contains(key);
1064
+ }
1065
+
1066
+ // NOLINTNEXTLINE(google-explicit-constructor)
1067
+ operator object() const { return get_cache(); }
1068
+ PyObject *ptr() const { return get_cache().ptr(); }
1069
+ template <typename T>
1070
+ T cast() const {
1071
+ return get_cache().template cast<T>();
1072
+ }
1073
+
1074
+ private:
1075
+ static object ensure_object(object &&o) { return std::move(o); }
1076
+ static object ensure_object(handle h) { return reinterpret_borrow<object>(h); }
1077
+
1078
+ object &get_cache() const {
1079
+ if (!cache) {
1080
+ cache = Policy::get(obj, key);
1081
+ }
1082
+ return cache;
1083
+ }
1084
+
1085
+ private:
1086
+ handle obj;
1087
+ key_type key;
1088
+ mutable object cache;
1089
+ };
1090
+ PYBIND11_WARNING_POP
1091
+
1092
+ PYBIND11_NAMESPACE_BEGIN(accessor_policies)
1093
+ struct obj_attr {
1094
+ using key_type = object;
1095
+ static object get(handle obj, handle key) { return getattr(obj, key); }
1096
+ static void set(handle obj, handle key, handle val) { setattr(obj, key, val); }
1097
+ };
1098
+
1099
+ struct str_attr {
1100
+ using key_type = const char *;
1101
+ static object get(handle obj, const char *key) { return getattr(obj, key); }
1102
+ static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); }
1103
+ };
1104
+
1105
+ struct generic_item {
1106
+ using key_type = object;
1107
+
1108
+ static object get(handle obj, handle key) {
1109
+ PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr());
1110
+ if (!result) {
1111
+ throw error_already_set();
1112
+ }
1113
+ return reinterpret_steal<object>(result);
1114
+ }
1115
+
1116
+ static void set(handle obj, handle key, handle val) {
1117
+ if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) {
1118
+ throw error_already_set();
1119
+ }
1120
+ }
1121
+ };
1122
+
1123
+ struct sequence_item {
1124
+ using key_type = size_t;
1125
+
1126
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1127
+ static object get(handle obj, const IdxType &index) {
1128
+ PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index));
1129
+ if (!result) {
1130
+ throw error_already_set();
1131
+ }
1132
+ return reinterpret_steal<object>(result);
1133
+ }
1134
+
1135
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1136
+ static void set(handle obj, const IdxType &index, handle val) {
1137
+ // PySequence_SetItem does not steal a reference to 'val'
1138
+ if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) {
1139
+ throw error_already_set();
1140
+ }
1141
+ }
1142
+ };
1143
+
1144
+ struct list_item {
1145
+ using key_type = size_t;
1146
+
1147
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1148
+ static object get(handle obj, const IdxType &index) {
1149
+ PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index));
1150
+ if (!result) {
1151
+ throw error_already_set();
1152
+ }
1153
+ return reinterpret_borrow<object>(result);
1154
+ }
1155
+
1156
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1157
+ static void set(handle obj, const IdxType &index, handle val) {
1158
+ // PyList_SetItem steals a reference to 'val'
1159
+ if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
1160
+ throw error_already_set();
1161
+ }
1162
+ }
1163
+ };
1164
+
1165
+ struct tuple_item {
1166
+ using key_type = size_t;
1167
+
1168
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1169
+ static object get(handle obj, const IdxType &index) {
1170
+ PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index));
1171
+ if (!result) {
1172
+ throw error_already_set();
1173
+ }
1174
+ return reinterpret_borrow<object>(result);
1175
+ }
1176
+
1177
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1178
+ static void set(handle obj, const IdxType &index, handle val) {
1179
+ // PyTuple_SetItem steals a reference to 'val'
1180
+ if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
1181
+ throw error_already_set();
1182
+ }
1183
+ }
1184
+ };
1185
+ PYBIND11_NAMESPACE_END(accessor_policies)
1186
+
1187
+ /// STL iterator template used for tuple, list, sequence and dict
1188
+ template <typename Policy>
1189
+ class generic_iterator : public Policy {
1190
+ using It = generic_iterator;
1191
+
1192
+ public:
1193
+ using difference_type = ssize_t;
1194
+ using iterator_category = typename Policy::iterator_category;
1195
+ using value_type = typename Policy::value_type;
1196
+ using reference = typename Policy::reference;
1197
+ using pointer = typename Policy::pointer;
1198
+
1199
+ generic_iterator() = default;
1200
+ generic_iterator(handle seq, ssize_t index) : Policy(seq, index) {}
1201
+
1202
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1203
+ reference operator*() const { return Policy::dereference(); }
1204
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1205
+ reference operator[](difference_type n) const { return *(*this + n); }
1206
+ pointer operator->() const { return **this; }
1207
+
1208
+ It &operator++() {
1209
+ Policy::increment();
1210
+ return *this;
1211
+ }
1212
+ It operator++(int) {
1213
+ auto copy = *this;
1214
+ Policy::increment();
1215
+ return copy;
1216
+ }
1217
+ It &operator--() {
1218
+ Policy::decrement();
1219
+ return *this;
1220
+ }
1221
+ It operator--(int) {
1222
+ auto copy = *this;
1223
+ Policy::decrement();
1224
+ return copy;
1225
+ }
1226
+ It &operator+=(difference_type n) {
1227
+ Policy::advance(n);
1228
+ return *this;
1229
+ }
1230
+ It &operator-=(difference_type n) {
1231
+ Policy::advance(-n);
1232
+ return *this;
1233
+ }
1234
+
1235
+ friend It operator+(const It &a, difference_type n) {
1236
+ auto copy = a;
1237
+ return copy += n;
1238
+ }
1239
+ friend It operator+(difference_type n, const It &b) { return b + n; }
1240
+ friend It operator-(const It &a, difference_type n) {
1241
+ auto copy = a;
1242
+ return copy -= n;
1243
+ }
1244
+ friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); }
1245
+
1246
+ friend bool operator==(const It &a, const It &b) { return a.equal(b); }
1247
+ friend bool operator!=(const It &a, const It &b) { return !(a == b); }
1248
+ friend bool operator<(const It &a, const It &b) { return b - a > 0; }
1249
+ friend bool operator>(const It &a, const It &b) { return b < a; }
1250
+ friend bool operator>=(const It &a, const It &b) { return !(a < b); }
1251
+ friend bool operator<=(const It &a, const It &b) { return !(a > b); }
1252
+ };
1253
+
1254
+ PYBIND11_NAMESPACE_BEGIN(iterator_policies)
1255
+ /// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers
1256
+ template <typename T>
1257
+ struct arrow_proxy {
1258
+ T value;
1259
+
1260
+ // NOLINTNEXTLINE(google-explicit-constructor)
1261
+ arrow_proxy(T &&value) noexcept : value(std::move(value)) {}
1262
+ T *operator->() const { return &value; }
1263
+ };
1264
+
1265
+ /// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS``
1266
+ class sequence_fast_readonly {
1267
+ protected:
1268
+ using iterator_category = std::random_access_iterator_tag;
1269
+ using value_type = handle;
1270
+ using reference = const handle; // PR #3263
1271
+ using pointer = arrow_proxy<const handle>;
1272
+
1273
+ sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) {}
1274
+ sequence_fast_readonly() = default;
1275
+
1276
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1277
+ reference dereference() const { return *ptr; }
1278
+ void increment() { ++ptr; }
1279
+ void decrement() { --ptr; }
1280
+ void advance(ssize_t n) { ptr += n; }
1281
+ bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; }
1282
+ ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; }
1283
+
1284
+ private:
1285
+ PyObject **ptr;
1286
+ };
1287
+
1288
+ /// Full read and write access using the sequence protocol: see ``detail::sequence_accessor``
1289
+ class sequence_slow_readwrite {
1290
+ protected:
1291
+ using iterator_category = std::random_access_iterator_tag;
1292
+ using value_type = object;
1293
+ using reference = sequence_accessor;
1294
+ using pointer = arrow_proxy<const sequence_accessor>;
1295
+
1296
+ sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) {}
1297
+ sequence_slow_readwrite() = default;
1298
+
1299
+ reference dereference() const { return {obj, static_cast<size_t>(index)}; }
1300
+ void increment() { ++index; }
1301
+ void decrement() { --index; }
1302
+ void advance(ssize_t n) { index += n; }
1303
+ bool equal(const sequence_slow_readwrite &b) const { return index == b.index; }
1304
+ ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; }
1305
+
1306
+ private:
1307
+ handle obj;
1308
+ ssize_t index;
1309
+ };
1310
+
1311
+ /// Python's dictionary protocol permits this to be a forward iterator
1312
+ class dict_readonly {
1313
+ protected:
1314
+ using iterator_category = std::forward_iterator_tag;
1315
+ using value_type = std::pair<handle, handle>;
1316
+ using reference = const value_type; // PR #3263
1317
+ using pointer = arrow_proxy<const value_type>;
1318
+
1319
+ dict_readonly() = default;
1320
+ dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }
1321
+
1322
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1323
+ reference dereference() const { return {key, value}; }
1324
+ void increment() {
1325
+ if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) {
1326
+ pos = -1;
1327
+ }
1328
+ }
1329
+ bool equal(const dict_readonly &b) const { return pos == b.pos; }
1330
+
1331
+ private:
1332
+ handle obj;
1333
+ PyObject *key = nullptr, *value = nullptr;
1334
+ ssize_t pos = -1;
1335
+ };
1336
+ PYBIND11_NAMESPACE_END(iterator_policies)
1337
+
1338
+ #if !defined(PYPY_VERSION)
1339
+ using tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
1340
+ using list_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
1341
+ #else
1342
+ using tuple_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
1343
+ using list_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
1344
+ #endif
1345
+
1346
+ using sequence_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
1347
+ using dict_iterator = generic_iterator<iterator_policies::dict_readonly>;
1348
+
1349
+ inline bool PyIterable_Check(PyObject *obj) {
1350
+ PyObject *iter = PyObject_GetIter(obj);
1351
+ if (iter) {
1352
+ Py_DECREF(iter);
1353
+ return true;
1354
+ }
1355
+ PyErr_Clear();
1356
+ return false;
1357
+ }
1358
+
1359
+ inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
1360
+ inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }
1361
+
1362
+ #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
1363
+ inline bool PyUnicode_Check_Permissive(PyObject *o) {
1364
+ return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o);
1365
+ }
1366
+ # define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive
1367
+ #else
1368
+ # define PYBIND11_STR_CHECK_FUN PyUnicode_Check
1369
+ #endif
1370
+
1371
+ inline bool PyStaticMethod_Check(PyObject *o) { return Py_TYPE(o) == &PyStaticMethod_Type; }
1372
+
1373
+ class kwargs_proxy : public handle {
1374
+ public:
1375
+ explicit kwargs_proxy(handle h) : handle(h) {}
1376
+ };
1377
+
1378
+ class args_proxy : public handle {
1379
+ public:
1380
+ explicit args_proxy(handle h) : handle(h) {}
1381
+ kwargs_proxy operator*() const { return kwargs_proxy(*this); }
1382
+ };
1383
+
1384
+ /// Python argument categories (using PEP 448 terms)
1385
+ template <typename T>
1386
+ using is_keyword = std::is_base_of<arg, T>;
1387
+ template <typename T>
1388
+ using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking
1389
+ template <typename T>
1390
+ using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking
1391
+ template <typename T>
1392
+ using is_positional = satisfies_none_of<T, is_keyword, is_s_unpacking, is_ds_unpacking>;
1393
+ template <typename T>
1394
+ using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>;
1395
+
1396
+ // Call argument collector forward declarations
1397
+ template <return_value_policy policy = return_value_policy::automatic_reference>
1398
+ class simple_collector;
1399
+ template <return_value_policy policy = return_value_policy::automatic_reference>
1400
+ class unpacking_collector;
1401
+
1402
+ inline object get_scope_module(handle scope) {
1403
+ if (scope) {
1404
+ if (hasattr(scope, "__module__")) {
1405
+ return scope.attr("__module__");
1406
+ }
1407
+ if (hasattr(scope, "__name__")) {
1408
+ return scope.attr("__name__");
1409
+ }
1410
+ }
1411
+ return object();
1412
+ }
1413
+
1414
+ PYBIND11_NAMESPACE_END(detail)
1415
+
1416
+ // TODO: After the deprecated constructors are removed, this macro can be simplified by
1417
+ // inheriting ctors: `using Parent::Parent`. It's not an option right now because
1418
+ // the `using` statement triggers the parent deprecation warning even if the ctor
1419
+ // isn't even used.
1420
+ #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1421
+ public: \
1422
+ PYBIND11_DEPRECATED("Use reinterpret_borrow<" #Name ">() or reinterpret_steal<" #Name ">()") \
1423
+ Name(handle h, bool is_borrowed) \
1424
+ : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {} \
1425
+ Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {} \
1426
+ Name(handle h, stolen_t) : Parent(h, stolen_t{}) {} \
1427
+ PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
1428
+ bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \
1429
+ static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \
1430
+ template <typename Policy_> /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1431
+ Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) {}
1432
+
1433
+ #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1434
+ PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1435
+ /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
1436
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1437
+ Name(const object &o) \
1438
+ : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1439
+ if (!m_ptr) \
1440
+ throw ::pybind11::error_already_set(); \
1441
+ } \
1442
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1443
+ Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
1444
+ if (!m_ptr) \
1445
+ throw ::pybind11::error_already_set(); \
1446
+ }
1447
+
1448
+ #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \
1449
+ PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
1450
+ Name() = default;
1451
+
1452
+ #define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \
1453
+ ::pybind11::type_error("Object of type '" \
1454
+ + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) \
1455
+ + "' is not an instance of '" #Name "'")
1456
+
1457
+ #define PYBIND11_OBJECT(Name, Parent, CheckFun) \
1458
+ PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
1459
+ /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
1460
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1461
+ Name(const object &o) : Parent(o) { \
1462
+ if (m_ptr && !check_(m_ptr)) \
1463
+ throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1464
+ } \
1465
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
1466
+ Name(object &&o) : Parent(std::move(o)) { \
1467
+ if (m_ptr && !check_(m_ptr)) \
1468
+ throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
1469
+ }
1470
+
1471
+ #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
1472
+ PYBIND11_OBJECT(Name, Parent, CheckFun) \
1473
+ Name() = default;
1474
+
1475
+ /// \addtogroup pytypes
1476
+ /// @{
1477
+
1478
+ /** \rst
1479
+ Wraps a Python iterator so that it can also be used as a C++ input iterator
1480
+
1481
+ Caveat: copying an iterator does not (and cannot) clone the internal
1482
+ state of the Python iterable. This also applies to the post-increment
1483
+ operator. This iterator should only be used to retrieve the current
1484
+ value using ``operator*()``.
1485
+ \endrst */
1486
+ class iterator : public object {
1487
+ public:
1488
+ using iterator_category = std::input_iterator_tag;
1489
+ using difference_type = ssize_t;
1490
+ using value_type = handle;
1491
+ using reference = const handle; // PR #3263
1492
+ using pointer = const handle *;
1493
+
1494
+ PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)
1495
+
1496
+ iterator &operator++() {
1497
+ init();
1498
+ advance();
1499
+ return *this;
1500
+ }
1501
+
1502
+ iterator operator++(int) {
1503
+ // Note: We must call init() first so that rv.value is
1504
+ // the same as this->value just before calling advance().
1505
+ // Otherwise, dereferencing the returned iterator may call
1506
+ // advance() again and return the 3rd item instead of the 1st.
1507
+ init();
1508
+ auto rv = *this;
1509
+ advance();
1510
+ return rv;
1511
+ }
1512
+
1513
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
1514
+ reference operator*() const {
1515
+ init();
1516
+ return value;
1517
+ }
1518
+
1519
+ pointer operator->() const {
1520
+ init();
1521
+ return &value;
1522
+ }
1523
+
1524
+ /** \rst
1525
+ The value which marks the end of the iteration. ``it == iterator::sentinel()``
1526
+ is equivalent to catching ``StopIteration`` in Python.
1527
+
1528
+ .. code-block:: cpp
1529
+
1530
+ void foo(py::iterator it) {
1531
+ while (it != py::iterator::sentinel()) {
1532
+ // use `*it`
1533
+ ++it;
1534
+ }
1535
+ }
1536
+ \endrst */
1537
+ static iterator sentinel() { return {}; }
1538
+
1539
+ friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); }
1540
+ friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); }
1541
+
1542
+ private:
1543
+ void init() const {
1544
+ if (m_ptr && !value.ptr()) {
1545
+ auto &self = const_cast<iterator &>(*this);
1546
+ self.advance();
1547
+ }
1548
+ }
1549
+
1550
+ void advance() {
1551
+ value = reinterpret_steal<object>(PyIter_Next(m_ptr));
1552
+ if (value.ptr() == nullptr && PyErr_Occurred()) {
1553
+ throw error_already_set();
1554
+ }
1555
+ }
1556
+
1557
+ private:
1558
+ object value = {};
1559
+ };
1560
+
1561
+ class type : public object {
1562
+ public:
1563
+ PYBIND11_OBJECT(type, object, PyType_Check)
1564
+
1565
+ /// Return a type handle from a handle or an object
1566
+ static handle handle_of(handle h) { return handle((PyObject *) Py_TYPE(h.ptr())); }
1567
+
1568
+ /// Return a type object from a handle or an object
1569
+ static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); }
1570
+
1571
+ // Defined in pybind11/cast.h
1572
+ /// Convert C++ type to handle if previously registered. Does not convert
1573
+ /// standard types, like int, float. etc. yet.
1574
+ /// See https://github.com/pybind/pybind11/issues/2486
1575
+ template <typename T>
1576
+ static handle handle_of();
1577
+
1578
+ /// Convert C++ type to type if previously registered. Does not convert
1579
+ /// standard types, like int, float. etc. yet.
1580
+ /// See https://github.com/pybind/pybind11/issues/2486
1581
+ template <typename T>
1582
+ static type of() {
1583
+ return type(type::handle_of<T>(), borrowed_t{});
1584
+ }
1585
+ };
1586
+
1587
+ class iterable : public object {
1588
+ public:
1589
+ PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check)
1590
+ };
1591
+
1592
+ class bytes;
1593
+
1594
+ class str : public object {
1595
+ public:
1596
+ PYBIND11_OBJECT_CVT(str, object, PYBIND11_STR_CHECK_FUN, raw_str)
1597
+
1598
+ template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1599
+ str(const char *c, const SzType &n)
1600
+ : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1601
+ if (!m_ptr) {
1602
+ if (PyErr_Occurred()) {
1603
+ throw error_already_set();
1604
+ }
1605
+ pybind11_fail("Could not allocate string object!");
1606
+ }
1607
+ }
1608
+
1609
+ // 'explicit' is explicitly omitted from the following constructors to allow implicit
1610
+ // conversion to py::str from C++ string-like objects
1611
+ // NOLINTNEXTLINE(google-explicit-constructor)
1612
+ str(const char *c = "") : object(PyUnicode_FromString(c), stolen_t{}) {
1613
+ if (!m_ptr) {
1614
+ if (PyErr_Occurred()) {
1615
+ throw error_already_set();
1616
+ }
1617
+ pybind11_fail("Could not allocate string object!");
1618
+ }
1619
+ }
1620
+
1621
+ // NOLINTNEXTLINE(google-explicit-constructor)
1622
+ str(const std::string &s) : str(s.data(), s.size()) {}
1623
+
1624
+ #ifdef PYBIND11_HAS_STRING_VIEW
1625
+ // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
1626
+ template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>
1627
+ // NOLINTNEXTLINE(google-explicit-constructor)
1628
+ str(T s) : str(s.data(), s.size()) {}
1629
+
1630
+ # ifdef PYBIND11_HAS_U8STRING
1631
+ // reinterpret_cast here is safe (C++20 guarantees char8_t has the same size/alignment as char)
1632
+ // NOLINTNEXTLINE(google-explicit-constructor)
1633
+ str(std::u8string_view s) : str(reinterpret_cast<const char *>(s.data()), s.size()) {}
1634
+ # endif
1635
+
1636
+ #endif
1637
+
1638
+ explicit str(const bytes &b);
1639
+
1640
+ /** \rst
1641
+ Return a string representation of the object. This is analogous to
1642
+ the ``str()`` function in Python.
1643
+ \endrst */
1644
+ explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) {
1645
+ if (!m_ptr) {
1646
+ throw error_already_set();
1647
+ }
1648
+ }
1649
+
1650
+ // NOLINTNEXTLINE(google-explicit-constructor)
1651
+ operator std::string() const {
1652
+ object temp = *this;
1653
+ if (PyUnicode_Check(m_ptr)) {
1654
+ temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
1655
+ if (!temp) {
1656
+ throw error_already_set();
1657
+ }
1658
+ }
1659
+ char *buffer = nullptr;
1660
+ ssize_t length = 0;
1661
+ if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {
1662
+ throw error_already_set();
1663
+ }
1664
+ return std::string(buffer, (size_t) length);
1665
+ }
1666
+
1667
+ template <typename... Args>
1668
+ str format(Args &&...args) const {
1669
+ return attr("format")(std::forward<Args>(args)...);
1670
+ }
1671
+
1672
+ private:
1673
+ /// Return string representation -- always returns a new reference, even if already a str
1674
+ static PyObject *raw_str(PyObject *op) {
1675
+ PyObject *str_value = PyObject_Str(op);
1676
+ return str_value;
1677
+ }
1678
+ };
1679
+ /// @} pytypes
1680
+
1681
+ inline namespace literals {
1682
+ /** \rst
1683
+ String literal version of `str`
1684
+ \endrst */
1685
+ inline str
1686
+ #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
1687
+ operator"" _s // gcc 4.8.5 insists on having a space (hard error).
1688
+ #else
1689
+ operator""_s // clang 17 generates a deprecation warning if there is a space.
1690
+ #endif
1691
+ (const char *s, size_t size) {
1692
+ return {s, size};
1693
+ }
1694
+ } // namespace literals
1695
+
1696
+ /// \addtogroup pytypes
1697
+ /// @{
1698
+ class bytes : public object {
1699
+ public:
1700
+ PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK)
1701
+
1702
+ // Allow implicit conversion:
1703
+ // NOLINTNEXTLINE(google-explicit-constructor)
1704
+ bytes(const char *c = "") : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) {
1705
+ if (!m_ptr) {
1706
+ pybind11_fail("Could not allocate bytes object!");
1707
+ }
1708
+ }
1709
+
1710
+ template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1711
+ bytes(const char *c, const SzType &n)
1712
+ : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, ssize_t_cast(n)), stolen_t{}) {
1713
+ if (!m_ptr) {
1714
+ pybind11_fail("Could not allocate bytes object!");
1715
+ }
1716
+ }
1717
+
1718
+ // Allow implicit conversion:
1719
+ // NOLINTNEXTLINE(google-explicit-constructor)
1720
+ bytes(const std::string &s) : bytes(s.data(), s.size()) {}
1721
+
1722
+ explicit bytes(const pybind11::str &s);
1723
+
1724
+ // NOLINTNEXTLINE(google-explicit-constructor)
1725
+ operator std::string() const { return string_op<std::string>(); }
1726
+
1727
+ #ifdef PYBIND11_HAS_STRING_VIEW
1728
+ // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
1729
+ template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>
1730
+ // NOLINTNEXTLINE(google-explicit-constructor)
1731
+ bytes(T s) : bytes(s.data(), s.size()) {}
1732
+
1733
+ // Obtain a string view that views the current `bytes` buffer value. Note that this is only
1734
+ // valid so long as the `bytes` instance remains alive and so generally should not outlive the
1735
+ // lifetime of the `bytes` instance.
1736
+ // NOLINTNEXTLINE(google-explicit-constructor)
1737
+ operator std::string_view() const { return string_op<std::string_view>(); }
1738
+ #endif
1739
+ private:
1740
+ template <typename T>
1741
+ T string_op() const {
1742
+ char *buffer = nullptr;
1743
+ ssize_t length = 0;
1744
+ if (PyBytes_AsStringAndSize(m_ptr, &buffer, &length) != 0) {
1745
+ throw error_already_set();
1746
+ }
1747
+ return {buffer, static_cast<size_t>(length)};
1748
+ }
1749
+ };
1750
+ // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1751
+ // are included in the doxygen group; close here and reopen after as a workaround
1752
+ /// @} pytypes
1753
+
1754
+ inline bytes::bytes(const pybind11::str &s) {
1755
+ object temp = s;
1756
+ if (PyUnicode_Check(s.ptr())) {
1757
+ temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));
1758
+ if (!temp) {
1759
+ throw error_already_set();
1760
+ }
1761
+ }
1762
+ char *buffer = nullptr;
1763
+ ssize_t length = 0;
1764
+ if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {
1765
+ throw error_already_set();
1766
+ }
1767
+ auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));
1768
+ if (!obj) {
1769
+ pybind11_fail("Could not allocate bytes object!");
1770
+ }
1771
+ m_ptr = obj.release().ptr();
1772
+ }
1773
+
1774
+ inline str::str(const bytes &b) {
1775
+ char *buffer = nullptr;
1776
+ ssize_t length = 0;
1777
+ if (PyBytes_AsStringAndSize(b.ptr(), &buffer, &length) != 0) {
1778
+ throw error_already_set();
1779
+ }
1780
+ auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, length));
1781
+ if (!obj) {
1782
+ if (PyErr_Occurred()) {
1783
+ throw error_already_set();
1784
+ }
1785
+ pybind11_fail("Could not allocate string object!");
1786
+ }
1787
+ m_ptr = obj.release().ptr();
1788
+ }
1789
+
1790
+ /// \addtogroup pytypes
1791
+ /// @{
1792
+ class bytearray : public object {
1793
+ public:
1794
+ PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject)
1795
+
1796
+ template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1797
+ bytearray(const char *c, const SzType &n)
1798
+ : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1799
+ if (!m_ptr) {
1800
+ pybind11_fail("Could not allocate bytearray object!");
1801
+ }
1802
+ }
1803
+
1804
+ bytearray() : bytearray("", 0) {}
1805
+
1806
+ explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) {}
1807
+
1808
+ size_t size() const { return static_cast<size_t>(PyByteArray_Size(m_ptr)); }
1809
+
1810
+ explicit operator std::string() const {
1811
+ char *buffer = PyByteArray_AS_STRING(m_ptr);
1812
+ ssize_t size = PyByteArray_GET_SIZE(m_ptr);
1813
+ return std::string(buffer, static_cast<size_t>(size));
1814
+ }
1815
+ };
1816
+ // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1817
+ // are included in the doxygen group; close here and reopen after as a workaround
1818
+ /// @} pytypes
1819
+
1820
+ /// \addtogroup pytypes
1821
+ /// @{
1822
+ class none : public object {
1823
+ public:
1824
+ PYBIND11_OBJECT(none, object, detail::PyNone_Check)
1825
+ none() : object(Py_None, borrowed_t{}) {}
1826
+ };
1827
+
1828
+ class ellipsis : public object {
1829
+ public:
1830
+ PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check)
1831
+ ellipsis() : object(Py_Ellipsis, borrowed_t{}) {}
1832
+ };
1833
+
1834
+ class bool_ : public object {
1835
+ public:
1836
+ PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool)
1837
+ bool_() : object(Py_False, borrowed_t{}) {}
1838
+ // Allow implicit conversion from and to `bool`:
1839
+ // NOLINTNEXTLINE(google-explicit-constructor)
1840
+ bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) {}
1841
+ // NOLINTNEXTLINE(google-explicit-constructor)
1842
+ operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; }
1843
+
1844
+ private:
1845
+ /// Return the truth value of an object -- always returns a new reference
1846
+ static PyObject *raw_bool(PyObject *op) {
1847
+ const auto value = PyObject_IsTrue(op);
1848
+ if (value == -1) {
1849
+ return nullptr;
1850
+ }
1851
+ return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr();
1852
+ }
1853
+ };
1854
+
1855
+ PYBIND11_NAMESPACE_BEGIN(detail)
1856
+ // Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1;
1857
+ // otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned).
1858
+ // (The distinction is critically important when casting a returned -1 error value to some other
1859
+ // unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes).
1860
+ template <typename Unsigned>
1861
+ Unsigned as_unsigned(PyObject *o) {
1862
+ if (sizeof(Unsigned) <= sizeof(unsigned long)) {
1863
+ unsigned long v = PyLong_AsUnsignedLong(o);
1864
+ return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1865
+ }
1866
+ unsigned long long v = PyLong_AsUnsignedLongLong(o);
1867
+ return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1868
+ }
1869
+ PYBIND11_NAMESPACE_END(detail)
1870
+
1871
+ class int_ : public object {
1872
+ public:
1873
+ PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long)
1874
+ int_() : object(PyLong_FromLong(0), stolen_t{}) {}
1875
+ // Allow implicit conversion from C++ integral types:
1876
+ template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1877
+ // NOLINTNEXTLINE(google-explicit-constructor)
1878
+ int_(T value) {
1879
+ if (sizeof(T) <= sizeof(long)) {
1880
+ if (std::is_signed<T>::value) {
1881
+ m_ptr = PyLong_FromLong((long) value);
1882
+ } else {
1883
+ m_ptr = PyLong_FromUnsignedLong((unsigned long) value);
1884
+ }
1885
+ } else {
1886
+ if (std::is_signed<T>::value) {
1887
+ m_ptr = PyLong_FromLongLong((long long) value);
1888
+ } else {
1889
+ m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value);
1890
+ }
1891
+ }
1892
+ if (!m_ptr) {
1893
+ pybind11_fail("Could not allocate int object!");
1894
+ }
1895
+ }
1896
+
1897
+ template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1898
+ // NOLINTNEXTLINE(google-explicit-constructor)
1899
+ operator T() const {
1900
+ return std::is_unsigned<T>::value ? detail::as_unsigned<T>(m_ptr)
1901
+ : sizeof(T) <= sizeof(long) ? (T) PyLong_AsLong(m_ptr)
1902
+ : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
1903
+ }
1904
+ };
1905
+
1906
+ class float_ : public object {
1907
+ public:
1908
+ PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)
1909
+ // Allow implicit conversion from float/double:
1910
+ // NOLINTNEXTLINE(google-explicit-constructor)
1911
+ float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1912
+ if (!m_ptr) {
1913
+ pybind11_fail("Could not allocate float object!");
1914
+ }
1915
+ }
1916
+ // NOLINTNEXTLINE(google-explicit-constructor)
1917
+ float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1918
+ if (!m_ptr) {
1919
+ pybind11_fail("Could not allocate float object!");
1920
+ }
1921
+ }
1922
+ // NOLINTNEXTLINE(google-explicit-constructor)
1923
+ operator float() const { return (float) PyFloat_AsDouble(m_ptr); }
1924
+ // NOLINTNEXTLINE(google-explicit-constructor)
1925
+ operator double() const { return (double) PyFloat_AsDouble(m_ptr); }
1926
+ };
1927
+
1928
+ class weakref : public object {
1929
+ public:
1930
+ PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref)
1931
+ explicit weakref(handle obj, handle callback = {})
1932
+ : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) {
1933
+ if (!m_ptr) {
1934
+ if (PyErr_Occurred()) {
1935
+ throw error_already_set();
1936
+ }
1937
+ pybind11_fail("Could not allocate weak reference!");
1938
+ }
1939
+ }
1940
+
1941
+ private:
1942
+ static PyObject *raw_weakref(PyObject *o) { return PyWeakref_NewRef(o, nullptr); }
1943
+ };
1944
+
1945
+ class slice : public object {
1946
+ public:
1947
+ PYBIND11_OBJECT(slice, object, PySlice_Check)
1948
+ slice(handle start, handle stop, handle step)
1949
+ : object(PySlice_New(start.ptr(), stop.ptr(), step.ptr()), stolen_t{}) {
1950
+ if (!m_ptr) {
1951
+ pybind11_fail("Could not allocate slice object!");
1952
+ }
1953
+ }
1954
+ slice() : slice(none(), none(), none()) {}
1955
+
1956
+ #ifdef PYBIND11_HAS_OPTIONAL
1957
+ slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t> step)
1958
+ : slice(index_to_object(start), index_to_object(stop), index_to_object(step)) {}
1959
+ #else
1960
+ slice(ssize_t start_, ssize_t stop_, ssize_t step_)
1961
+ : slice(int_(start_), int_(stop_), int_(step_)) {}
1962
+ #endif
1963
+
1964
+ bool
1965
+ compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const {
1966
+ return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1967
+ (ssize_t) length,
1968
+ (ssize_t *) start,
1969
+ (ssize_t *) stop,
1970
+ (ssize_t *) step,
1971
+ (ssize_t *) slicelength)
1972
+ == 0;
1973
+ }
1974
+ bool compute(
1975
+ ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const {
1976
+ return PySlice_GetIndicesEx(
1977
+ (PYBIND11_SLICE_OBJECT *) m_ptr, length, start, stop, step, slicelength)
1978
+ == 0;
1979
+ }
1980
+
1981
+ private:
1982
+ template <typename T>
1983
+ static object index_to_object(T index) {
1984
+ return index ? object(int_(*index)) : object(none());
1985
+ }
1986
+ };
1987
+
1988
+ class capsule : public object {
1989
+ public:
1990
+ PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact)
1991
+ PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()")
1992
+ capsule(PyObject *ptr, bool is_borrowed)
1993
+ : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) {}
1994
+
1995
+ explicit capsule(const void *value,
1996
+ const char *name = nullptr,
1997
+ PyCapsule_Destructor destructor = nullptr)
1998
+ : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) {
1999
+ if (!m_ptr) {
2000
+ throw error_already_set();
2001
+ }
2002
+ }
2003
+
2004
+ PYBIND11_DEPRECATED("Please use the ctor with value, name, destructor args")
2005
+ capsule(const void *value, PyCapsule_Destructor destructor)
2006
+ : object(PyCapsule_New(const_cast<void *>(value), nullptr, destructor), stolen_t{}) {
2007
+ if (!m_ptr) {
2008
+ throw error_already_set();
2009
+ }
2010
+ }
2011
+
2012
+ /// Capsule name is nullptr.
2013
+ capsule(const void *value, void (*destructor)(void *)) {
2014
+ initialize_with_void_ptr_destructor(value, nullptr, destructor);
2015
+ }
2016
+
2017
+ capsule(const void *value, const char *name, void (*destructor)(void *)) {
2018
+ initialize_with_void_ptr_destructor(value, name, destructor);
2019
+ }
2020
+
2021
+ explicit capsule(void (*destructor)()) {
2022
+ m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) {
2023
+ const char *name = get_name_in_error_scope(o);
2024
+ auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, name));
2025
+ if (destructor == nullptr) {
2026
+ throw error_already_set();
2027
+ }
2028
+ destructor();
2029
+ });
2030
+
2031
+ if (!m_ptr) {
2032
+ throw error_already_set();
2033
+ }
2034
+ }
2035
+
2036
+ template <typename T>
2037
+ operator T *() const { // NOLINT(google-explicit-constructor)
2038
+ return get_pointer<T>();
2039
+ }
2040
+
2041
+ /// Get the pointer the capsule holds.
2042
+ template <typename T = void>
2043
+ T *get_pointer() const {
2044
+ const auto *name = this->name();
2045
+ T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));
2046
+ if (!result) {
2047
+ throw error_already_set();
2048
+ }
2049
+ return result;
2050
+ }
2051
+
2052
+ /// Replaces a capsule's pointer *without* calling the destructor on the existing one.
2053
+ void set_pointer(const void *value) {
2054
+ if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0) {
2055
+ throw error_already_set();
2056
+ }
2057
+ }
2058
+
2059
+ const char *name() const {
2060
+ const char *name = PyCapsule_GetName(m_ptr);
2061
+ if ((name == nullptr) && PyErr_Occurred()) {
2062
+ throw error_already_set();
2063
+ }
2064
+ return name;
2065
+ }
2066
+
2067
+ /// Replaces a capsule's name *without* calling the destructor on the existing one.
2068
+ void set_name(const char *new_name) {
2069
+ if (PyCapsule_SetName(m_ptr, new_name) != 0) {
2070
+ throw error_already_set();
2071
+ }
2072
+ }
2073
+
2074
+ private:
2075
+ static const char *get_name_in_error_scope(PyObject *o) {
2076
+ error_scope error_guard;
2077
+
2078
+ const char *name = PyCapsule_GetName(o);
2079
+ if ((name == nullptr) && PyErr_Occurred()) {
2080
+ // write out and consume error raised by call to PyCapsule_GetName
2081
+ PyErr_WriteUnraisable(o);
2082
+ }
2083
+
2084
+ return name;
2085
+ }
2086
+
2087
+ void initialize_with_void_ptr_destructor(const void *value,
2088
+ const char *name,
2089
+ void (*destructor)(void *)) {
2090
+ m_ptr = PyCapsule_New(const_cast<void *>(value), name, [](PyObject *o) {
2091
+ // guard if destructor called while err indicator is set
2092
+ error_scope error_guard;
2093
+ auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o));
2094
+ if (destructor == nullptr && PyErr_Occurred()) {
2095
+ throw error_already_set();
2096
+ }
2097
+ const char *name = get_name_in_error_scope(o);
2098
+ void *ptr = PyCapsule_GetPointer(o, name);
2099
+ if (ptr == nullptr) {
2100
+ throw error_already_set();
2101
+ }
2102
+
2103
+ if (destructor != nullptr) {
2104
+ destructor(ptr);
2105
+ }
2106
+ });
2107
+
2108
+ if (!m_ptr || PyCapsule_SetContext(m_ptr, reinterpret_cast<void *>(destructor)) != 0) {
2109
+ throw error_already_set();
2110
+ }
2111
+ }
2112
+ };
2113
+
2114
+ class tuple : public object {
2115
+ public:
2116
+ PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple)
2117
+ template <typename SzType = ssize_t,
2118
+ detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
2119
+ // Some compilers generate link errors when using `const SzType &` here:
2120
+ explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) {
2121
+ if (!m_ptr) {
2122
+ pybind11_fail("Could not allocate tuple object!");
2123
+ }
2124
+ }
2125
+ size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
2126
+ bool empty() const { return size() == 0; }
2127
+ detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }
2128
+ template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
2129
+ detail::item_accessor operator[](T &&o) const {
2130
+ return object::operator[](std::forward<T>(o));
2131
+ }
2132
+ detail::tuple_iterator begin() const { return {*this, 0}; }
2133
+ detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }
2134
+ };
2135
+
2136
+ // We need to put this into a separate function because the Intel compiler
2137
+ // fails to compile enable_if_t<all_of<is_keyword_or_ds<Args>...>::value> part below
2138
+ // (tested with ICC 2021.1 Beta 20200827).
2139
+ template <typename... Args>
2140
+ constexpr bool args_are_all_keyword_or_ds() {
2141
+ return detail::all_of<detail::is_keyword_or_ds<Args>...>::value;
2142
+ }
2143
+
2144
+ class dict : public object {
2145
+ public:
2146
+ PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)
2147
+ dict() : object(PyDict_New(), stolen_t{}) {
2148
+ if (!m_ptr) {
2149
+ pybind11_fail("Could not allocate dict object!");
2150
+ }
2151
+ }
2152
+ template <typename... Args,
2153
+ typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>,
2154
+ // MSVC workaround: it can't compile an out-of-line definition, so defer the
2155
+ // collector
2156
+ typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
2157
+ explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) {}
2158
+
2159
+ size_t size() const { return (size_t) PyDict_Size(m_ptr); }
2160
+ bool empty() const { return size() == 0; }
2161
+ detail::dict_iterator begin() const { return {*this, 0}; }
2162
+ detail::dict_iterator end() const { return {}; }
2163
+ void clear() /* py-non-const */ { PyDict_Clear(ptr()); }
2164
+ template <typename T>
2165
+ bool contains(T &&key) const {
2166
+ auto result = PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr());
2167
+ if (result == -1) {
2168
+ throw error_already_set();
2169
+ }
2170
+ return result == 1;
2171
+ }
2172
+
2173
+ private:
2174
+ /// Call the `dict` Python type -- always returns a new reference
2175
+ static PyObject *raw_dict(PyObject *op) {
2176
+ if (PyDict_Check(op)) {
2177
+ return handle(op).inc_ref().ptr();
2178
+ }
2179
+ return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
2180
+ }
2181
+ };
2182
+
2183
+ class sequence : public object {
2184
+ public:
2185
+ PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)
2186
+ size_t size() const {
2187
+ ssize_t result = PySequence_Size(m_ptr);
2188
+ if (result == -1) {
2189
+ throw error_already_set();
2190
+ }
2191
+ return (size_t) result;
2192
+ }
2193
+ bool empty() const { return size() == 0; }
2194
+ detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
2195
+ template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
2196
+ detail::item_accessor operator[](T &&o) const {
2197
+ return object::operator[](std::forward<T>(o));
2198
+ }
2199
+ detail::sequence_iterator begin() const { return {*this, 0}; }
2200
+ detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; }
2201
+ };
2202
+
2203
+ class list : public object {
2204
+ public:
2205
+ PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
2206
+ template <typename SzType = ssize_t,
2207
+ detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
2208
+ // Some compilers generate link errors when using `const SzType &` here:
2209
+ explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) {
2210
+ if (!m_ptr) {
2211
+ pybind11_fail("Could not allocate list object!");
2212
+ }
2213
+ }
2214
+ size_t size() const { return (size_t) PyList_Size(m_ptr); }
2215
+ bool empty() const { return size() == 0; }
2216
+ detail::list_accessor operator[](size_t index) const { return {*this, index}; }
2217
+ template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
2218
+ detail::item_accessor operator[](T &&o) const {
2219
+ return object::operator[](std::forward<T>(o));
2220
+ }
2221
+ detail::list_iterator begin() const { return {*this, 0}; }
2222
+ detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
2223
+ template <typename T>
2224
+ void append(T &&val) /* py-non-const */ {
2225
+ if (PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) != 0) {
2226
+ throw error_already_set();
2227
+ }
2228
+ }
2229
+ template <typename IdxType,
2230
+ typename ValType,
2231
+ detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
2232
+ void insert(const IdxType &index, ValType &&val) /* py-non-const */ {
2233
+ if (PyList_Insert(m_ptr,
2234
+ ssize_t_cast(index),
2235
+ detail::object_or_cast(std::forward<ValType>(val)).ptr())
2236
+ != 0) {
2237
+ throw error_already_set();
2238
+ }
2239
+ }
2240
+ void clear() /* py-non-const */ {
2241
+ if (PyList_SetSlice(m_ptr, 0, PyList_Size(m_ptr), nullptr) == -1) {
2242
+ throw error_already_set();
2243
+ }
2244
+ }
2245
+ };
2246
+
2247
+ class args : public tuple {
2248
+ PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check)
2249
+ };
2250
+ class kwargs : public dict {
2251
+ PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check)
2252
+ };
2253
+
2254
+ // Subclasses of args and kwargs to support type hinting
2255
+ // as defined in PEP 484. See #5357 for more info.
2256
+ template <typename T>
2257
+ class Args : public args {
2258
+ using args::args;
2259
+ };
2260
+
2261
+ template <typename T>
2262
+ class KWArgs : public kwargs {
2263
+ using kwargs::kwargs;
2264
+ };
2265
+
2266
+ class anyset : public object {
2267
+ public:
2268
+ PYBIND11_OBJECT(anyset, object, PyAnySet_Check)
2269
+ size_t size() const { return static_cast<size_t>(PySet_Size(m_ptr)); }
2270
+ bool empty() const { return size() == 0; }
2271
+ template <typename T>
2272
+ bool contains(T &&val) const {
2273
+ auto result = PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
2274
+ if (result == -1) {
2275
+ throw error_already_set();
2276
+ }
2277
+ return result == 1;
2278
+ }
2279
+ };
2280
+
2281
+ class set : public anyset {
2282
+ public:
2283
+ PYBIND11_OBJECT_CVT(set, anyset, PySet_Check, PySet_New)
2284
+ set() : anyset(PySet_New(nullptr), stolen_t{}) {
2285
+ if (!m_ptr) {
2286
+ pybind11_fail("Could not allocate set object!");
2287
+ }
2288
+ }
2289
+ template <typename T>
2290
+ bool add(T &&val) /* py-non-const */ {
2291
+ return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
2292
+ }
2293
+ void clear() /* py-non-const */ { PySet_Clear(m_ptr); }
2294
+ };
2295
+
2296
+ class frozenset : public anyset {
2297
+ public:
2298
+ PYBIND11_OBJECT_CVT(frozenset, anyset, PyFrozenSet_Check, PyFrozenSet_New)
2299
+ };
2300
+
2301
+ class function : public object {
2302
+ public:
2303
+ PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)
2304
+ handle cpp_function() const {
2305
+ handle fun = detail::get_function(m_ptr);
2306
+ if (fun && PyCFunction_Check(fun.ptr())) {
2307
+ return fun;
2308
+ }
2309
+ return handle();
2310
+ }
2311
+ bool is_cpp_function() const { return (bool) cpp_function(); }
2312
+ };
2313
+
2314
+ class staticmethod : public object {
2315
+ public:
2316
+ PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)
2317
+ };
2318
+
2319
+ class buffer : public object {
2320
+ public:
2321
+ PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)
2322
+
2323
+ buffer_info request(bool writable = false) const {
2324
+ int flags = PyBUF_STRIDES | PyBUF_FORMAT;
2325
+ if (writable) {
2326
+ flags |= PyBUF_WRITABLE;
2327
+ }
2328
+ auto *view = new Py_buffer();
2329
+ if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
2330
+ delete view;
2331
+ throw error_already_set();
2332
+ }
2333
+ return buffer_info(view);
2334
+ }
2335
+ };
2336
+
2337
+ class memoryview : public object {
2338
+ public:
2339
+ PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
2340
+
2341
+ /** \rst
2342
+ Creates ``memoryview`` from ``buffer_info``.
2343
+
2344
+ ``buffer_info`` must be created from ``buffer::request()``. Otherwise
2345
+ throws an exception.
2346
+
2347
+ For creating a ``memoryview`` from objects that support buffer protocol,
2348
+ use ``memoryview(const object& obj)`` instead of this constructor.
2349
+ \endrst */
2350
+ explicit memoryview(const buffer_info &info) {
2351
+ if (!info.view()) {
2352
+ pybind11_fail("Prohibited to create memoryview without Py_buffer");
2353
+ }
2354
+ // Note: PyMemoryView_FromBuffer never increments obj reference.
2355
+ m_ptr = (info.view()->obj) ? PyMemoryView_FromObject(info.view()->obj)
2356
+ : PyMemoryView_FromBuffer(info.view());
2357
+ if (!m_ptr) {
2358
+ pybind11_fail("Unable to create memoryview from buffer descriptor");
2359
+ }
2360
+ }
2361
+
2362
+ /** \rst
2363
+ Creates ``memoryview`` from static buffer.
2364
+
2365
+ This method is meant for providing a ``memoryview`` for C/C++ buffer not
2366
+ managed by Python. The caller is responsible for managing the lifetime
2367
+ of ``ptr`` and ``format``, which MUST outlive the memoryview constructed
2368
+ here.
2369
+
2370
+ See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
2371
+
2372
+ .. _PyMemoryView_FromBuffer:
2373
+ https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer
2374
+
2375
+ :param ptr: Pointer to the buffer.
2376
+ :param itemsize: Byte size of an element.
2377
+ :param format: Pointer to the null-terminated format string. For
2378
+ homogeneous Buffers, this should be set to
2379
+ ``format_descriptor<T>::value``.
2380
+ :param shape: Shape of the tensor (1 entry per dimension).
2381
+ :param strides: Number of bytes between adjacent entries (for each
2382
+ per dimension).
2383
+ :param readonly: Flag to indicate if the underlying storage may be
2384
+ written to.
2385
+ \endrst */
2386
+ static memoryview from_buffer(void *ptr,
2387
+ ssize_t itemsize,
2388
+ const char *format,
2389
+ detail::any_container<ssize_t> shape,
2390
+ detail::any_container<ssize_t> strides,
2391
+ bool readonly = false);
2392
+
2393
+ static memoryview from_buffer(const void *ptr,
2394
+ ssize_t itemsize,
2395
+ const char *format,
2396
+ detail::any_container<ssize_t> shape,
2397
+ detail::any_container<ssize_t> strides) {
2398
+ return memoryview::from_buffer(
2399
+ const_cast<void *>(ptr), itemsize, format, std::move(shape), std::move(strides), true);
2400
+ }
2401
+
2402
+ template <typename T>
2403
+ static memoryview from_buffer(T *ptr,
2404
+ detail::any_container<ssize_t> shape,
2405
+ detail::any_container<ssize_t> strides,
2406
+ bool readonly = false) {
2407
+ return memoryview::from_buffer(reinterpret_cast<void *>(ptr),
2408
+ sizeof(T),
2409
+ format_descriptor<T>::value,
2410
+ std::move(shape),
2411
+ std::move(strides),
2412
+ readonly);
2413
+ }
2414
+
2415
+ template <typename T>
2416
+ static memoryview from_buffer(const T *ptr,
2417
+ detail::any_container<ssize_t> shape,
2418
+ detail::any_container<ssize_t> strides) {
2419
+ return memoryview::from_buffer(
2420
+ const_cast<T *>(ptr), std::move(shape), std::move(strides), true);
2421
+ }
2422
+
2423
+ /** \rst
2424
+ Creates ``memoryview`` from static memory.
2425
+
2426
+ This method is meant for providing a ``memoryview`` for C/C++ buffer not
2427
+ managed by Python. The caller is responsible for managing the lifetime
2428
+ of ``mem``, which MUST outlive the memoryview constructed here.
2429
+
2430
+ See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
2431
+
2432
+ .. _PyMemoryView_FromMemory:
2433
+ https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory
2434
+ \endrst */
2435
+ static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) {
2436
+ PyObject *ptr = PyMemoryView_FromMemory(
2437
+ reinterpret_cast<char *>(mem), size, (readonly) ? PyBUF_READ : PyBUF_WRITE);
2438
+ if (!ptr) {
2439
+ pybind11_fail("Could not allocate memoryview object!");
2440
+ }
2441
+ return memoryview(object(ptr, stolen_t{}));
2442
+ }
2443
+
2444
+ static memoryview from_memory(const void *mem, ssize_t size) {
2445
+ return memoryview::from_memory(const_cast<void *>(mem), size, true);
2446
+ }
2447
+
2448
+ #ifdef PYBIND11_HAS_STRING_VIEW
2449
+ static memoryview from_memory(std::string_view mem) {
2450
+ return from_memory(const_cast<char *>(mem.data()), static_cast<ssize_t>(mem.size()), true);
2451
+ }
2452
+ #endif
2453
+ };
2454
+
2455
+ /// @cond DUPLICATE
2456
+ inline memoryview memoryview::from_buffer(void *ptr,
2457
+ ssize_t itemsize,
2458
+ const char *format,
2459
+ detail::any_container<ssize_t> shape,
2460
+ detail::any_container<ssize_t> strides,
2461
+ bool readonly) {
2462
+ size_t ndim = shape->size();
2463
+ if (ndim != strides->size()) {
2464
+ pybind11_fail("memoryview: shape length doesn't match strides length");
2465
+ }
2466
+ ssize_t size = ndim != 0u ? 1 : 0;
2467
+ for (size_t i = 0; i < ndim; ++i) {
2468
+ size *= (*shape)[i];
2469
+ }
2470
+ Py_buffer view;
2471
+ view.buf = ptr;
2472
+ view.obj = nullptr;
2473
+ view.len = size * itemsize;
2474
+ view.readonly = static_cast<int>(readonly);
2475
+ view.itemsize = itemsize;
2476
+ view.format = const_cast<char *>(format);
2477
+ view.ndim = static_cast<int>(ndim);
2478
+ view.shape = shape->data();
2479
+ view.strides = strides->data();
2480
+ view.suboffsets = nullptr;
2481
+ view.internal = nullptr;
2482
+ PyObject *obj = PyMemoryView_FromBuffer(&view);
2483
+ if (!obj) {
2484
+ throw error_already_set();
2485
+ }
2486
+ return memoryview(object(obj, stolen_t{}));
2487
+ }
2488
+ /// @endcond
2489
+ /// @} pytypes
2490
+
2491
+ /// \addtogroup python_builtins
2492
+ /// @{
2493
+
2494
+ /// Get the length of a Python object.
2495
+ inline size_t len(handle h) {
2496
+ ssize_t result = PyObject_Length(h.ptr());
2497
+ if (result < 0) {
2498
+ throw error_already_set();
2499
+ }
2500
+ return (size_t) result;
2501
+ }
2502
+
2503
+ /// Get the length hint of a Python object.
2504
+ /// Returns 0 when this cannot be determined.
2505
+ inline size_t len_hint(handle h) {
2506
+ ssize_t result = PyObject_LengthHint(h.ptr(), 0);
2507
+ if (result < 0) {
2508
+ // Sometimes a length can't be determined at all (eg generators)
2509
+ // In which case simply return 0
2510
+ PyErr_Clear();
2511
+ return 0;
2512
+ }
2513
+ return (size_t) result;
2514
+ }
2515
+
2516
+ inline str repr(handle h) {
2517
+ PyObject *str_value = PyObject_Repr(h.ptr());
2518
+ if (!str_value) {
2519
+ throw error_already_set();
2520
+ }
2521
+ return reinterpret_steal<str>(str_value);
2522
+ }
2523
+
2524
+ inline iterator iter(handle obj) {
2525
+ PyObject *result = PyObject_GetIter(obj.ptr());
2526
+ if (!result) {
2527
+ throw error_already_set();
2528
+ }
2529
+ return reinterpret_steal<iterator>(result);
2530
+ }
2531
+ /// @} python_builtins
2532
+
2533
+ PYBIND11_NAMESPACE_BEGIN(detail)
2534
+ template <typename D>
2535
+ iterator object_api<D>::begin() const {
2536
+ return iter(derived());
2537
+ }
2538
+ template <typename D>
2539
+ iterator object_api<D>::end() const {
2540
+ return iterator::sentinel();
2541
+ }
2542
+ template <typename D>
2543
+ item_accessor object_api<D>::operator[](handle key) const {
2544
+ return {derived(), reinterpret_borrow<object>(key)};
2545
+ }
2546
+ template <typename D>
2547
+ item_accessor object_api<D>::operator[](object &&key) const {
2548
+ return {derived(), std::move(key)};
2549
+ }
2550
+ template <typename D>
2551
+ item_accessor object_api<D>::operator[](const char *key) const {
2552
+ return {derived(), pybind11::str(key)};
2553
+ }
2554
+ template <typename D>
2555
+ obj_attr_accessor object_api<D>::attr(handle key) const {
2556
+ return {derived(), reinterpret_borrow<object>(key)};
2557
+ }
2558
+ template <typename D>
2559
+ obj_attr_accessor object_api<D>::attr(object &&key) const {
2560
+ return {derived(), std::move(key)};
2561
+ }
2562
+ template <typename D>
2563
+ str_attr_accessor object_api<D>::attr(const char *key) const {
2564
+ return {derived(), key};
2565
+ }
2566
+ template <typename D>
2567
+ args_proxy object_api<D>::operator*() const {
2568
+ return args_proxy(derived().ptr());
2569
+ }
2570
+ template <typename D>
2571
+ template <typename T>
2572
+ bool object_api<D>::contains(T &&item) const {
2573
+ return attr("__contains__")(std::forward<T>(item)).template cast<bool>();
2574
+ }
2575
+
2576
+ template <typename D>
2577
+ pybind11::str object_api<D>::str() const {
2578
+ return pybind11::str(derived());
2579
+ }
2580
+
2581
+ template <typename D>
2582
+ str_attr_accessor object_api<D>::doc() const {
2583
+ return attr("__doc__");
2584
+ }
2585
+
2586
+ template <typename D>
2587
+ object object_api<D>::annotations() const {
2588
+ // This is needed again because of the lazy annotations added in 3.14+
2589
+ #if PY_VERSION_HEX < 0x030A0000 || PY_VERSION_HEX >= 0x030E0000
2590
+ // https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older
2591
+ if (!hasattr(derived(), "__annotations__")) {
2592
+ setattr(derived(), "__annotations__", dict());
2593
+ }
2594
+ return attr("__annotations__");
2595
+ #else
2596
+ return getattr(derived(), "__annotations__", dict());
2597
+ #endif
2598
+ }
2599
+
2600
+ template <typename D>
2601
+ handle object_api<D>::get_type() const {
2602
+ return type::handle_of(derived());
2603
+ }
2604
+
2605
+ template <typename D>
2606
+ bool object_api<D>::rich_compare(object_api const &other, int value) const {
2607
+ int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
2608
+ if (rv == -1) {
2609
+ throw error_already_set();
2610
+ }
2611
+ return rv == 1;
2612
+ }
2613
+
2614
+ #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
2615
+ template <typename D> \
2616
+ object object_api<D>::op() const { \
2617
+ object result = reinterpret_steal<object>(fn(derived().ptr())); \
2618
+ if (!result.ptr()) \
2619
+ throw error_already_set(); \
2620
+ return result; \
2621
+ }
2622
+
2623
+ #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
2624
+ template <typename D> \
2625
+ object object_api<D>::op(object_api const &other) const { \
2626
+ object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
2627
+ if (!result.ptr()) \
2628
+ throw error_already_set(); \
2629
+ return result; \
2630
+ }
2631
+
2632
+ #define PYBIND11_MATH_OPERATOR_BINARY_INPLACE(iop, fn) \
2633
+ template <typename D> \
2634
+ object object_api<D>::iop(object_api const &other) { \
2635
+ object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
2636
+ if (!result.ptr()) \
2637
+ throw error_already_set(); \
2638
+ return result; \
2639
+ }
2640
+
2641
+ PYBIND11_MATH_OPERATOR_UNARY(operator~, PyNumber_Invert)
2642
+ PYBIND11_MATH_OPERATOR_UNARY(operator-, PyNumber_Negative)
2643
+ PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)
2644
+ PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator+=, PyNumber_InPlaceAdd)
2645
+ PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)
2646
+ PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator-=, PyNumber_InPlaceSubtract)
2647
+ PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)
2648
+ PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator*=, PyNumber_InPlaceMultiply)
2649
+ PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)
2650
+ PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator/=, PyNumber_InPlaceTrueDivide)
2651
+ PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)
2652
+ PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator|=, PyNumber_InPlaceOr)
2653
+ PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)
2654
+ PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator&=, PyNumber_InPlaceAnd)
2655
+ PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)
2656
+ PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator^=, PyNumber_InPlaceXor)
2657
+ PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)
2658
+ PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator<<=, PyNumber_InPlaceLshift)
2659
+ PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)
2660
+ PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator>>=, PyNumber_InPlaceRshift)
2661
+
2662
+ #undef PYBIND11_MATH_OPERATOR_UNARY
2663
+ #undef PYBIND11_MATH_OPERATOR_BINARY
2664
+ #undef PYBIND11_MATH_OPERATOR_BINARY_INPLACE
2665
+
2666
+ // Meant to return a Python str, but this is not checked.
2667
+ inline object get_module_name_if_available(handle scope) {
2668
+ if (scope) {
2669
+ if (hasattr(scope, "__module__")) {
2670
+ return scope.attr("__module__");
2671
+ }
2672
+ if (hasattr(scope, "__name__")) {
2673
+ return scope.attr("__name__");
2674
+ }
2675
+ }
2676
+ return object();
2677
+ }
2678
+
2679
+ PYBIND11_NAMESPACE_END(detail)
2680
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)