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