xcoll 0.4.0__py3-none-any.whl → 0.5.1__py3-none-any.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.

Potentially problematic release.


This version of xcoll might be problematic. Click here for more details.

Files changed (324) hide show
  1. xcoll/__init__.py +2 -1
  2. xcoll/beam_elements/__init__.py +9 -2
  3. xcoll/beam_elements/absorber.py +2 -2
  4. xcoll/beam_elements/base.py +105 -67
  5. xcoll/beam_elements/blowup.py +198 -0
  6. xcoll/beam_elements/{collimators_src → elements_src}/black_absorber.h +21 -3
  7. xcoll/beam_elements/{collimators_src → elements_src}/black_crystal.h +20 -2
  8. xcoll/beam_elements/elements_src/blowup.h +42 -0
  9. xcoll/beam_elements/elements_src/emittance_monitor.h +109 -0
  10. xcoll/beam_elements/{collimators_src → elements_src}/everest_block.h +19 -2
  11. xcoll/beam_elements/{collimators_src → elements_src}/everest_collimator.h +19 -3
  12. xcoll/beam_elements/{collimators_src → elements_src}/everest_crystal.h +30 -9
  13. xcoll/beam_elements/everest.py +5 -6
  14. xcoll/beam_elements/monitor.py +428 -0
  15. xcoll/colldb.py +103 -74
  16. xcoll/general.py +4 -4
  17. xcoll/initial_distribution.py +18 -6
  18. xcoll/install.py +3 -1
  19. xcoll/interaction_record/interaction_record.py +127 -81
  20. xcoll/interaction_record/interaction_record_src/interaction_record.h +43 -43
  21. xcoll/line_tools.py +8 -9
  22. xcoll/lossmap.py +48 -38
  23. xcoll/scattering_routines/everest/amorphous.h +4 -11
  24. xcoll/scattering_routines/everest/channeling.h +3 -8
  25. xcoll/scattering_routines/everest/everest.h +4 -1
  26. xcoll/scattering_routines/everest/jaw.h +4 -3
  27. xcoll/scattering_routines/everest/materials.py +35 -15
  28. xcoll/scattering_routines/everest/multiple_coulomb_scattering.h +2 -2
  29. xcoll/scattering_routines/everest/nuclear_interaction.h +1 -1
  30. xcoll/scattering_routines/everest/properties.h +6 -1
  31. xcoll/scattering_routines/fluka/flukaio/lib/libFlukaIO64.a +0 -0
  32. xcoll/scattering_routines/geant4/collimasim/.git +1 -0
  33. xcoll/scattering_routines/geant4/collimasim/.gitignore +12 -0
  34. xcoll/scattering_routines/geant4/collimasim/.gitmodules +3 -0
  35. xcoll/scattering_routines/geant4/collimasim/CMakeLists.txt +26 -0
  36. xcoll/scattering_routines/geant4/collimasim/README.md +21 -0
  37. xcoll/scattering_routines/geant4/collimasim/docs/Makefile +20 -0
  38. xcoll/scattering_routines/geant4/collimasim/docs/make.bat +35 -0
  39. xcoll/scattering_routines/geant4/collimasim/docs/source/collimasim.rst +10 -0
  40. xcoll/scattering_routines/geant4/collimasim/docs/source/conf.py +59 -0
  41. xcoll/scattering_routines/geant4/collimasim/docs/source/index.rst +26 -0
  42. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.appveyor.yml +37 -0
  43. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.clang-format +19 -0
  44. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.clang-tidy +65 -0
  45. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.cmake-format.yaml +73 -0
  46. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.git +1 -0
  47. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/CODEOWNERS +9 -0
  48. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/CONTRIBUTING.md +386 -0
  49. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/ISSUE_TEMPLATE/bug-report.yml +45 -0
  50. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/ISSUE_TEMPLATE/config.yml +8 -0
  51. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/dependabot.yml +16 -0
  52. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/labeler.yml +8 -0
  53. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/labeler_merged.yml +3 -0
  54. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/pull_request_template.md +19 -0
  55. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/workflows/ci.yml +969 -0
  56. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/workflows/configure.yml +84 -0
  57. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/workflows/format.yml +48 -0
  58. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/workflows/labeler.yml +16 -0
  59. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.github/workflows/pip.yml +103 -0
  60. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.gitignore +45 -0
  61. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.pre-commit-config.yaml +151 -0
  62. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/.readthedocs.yml +3 -0
  63. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/CMakeLists.txt +297 -0
  64. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/LICENSE +29 -0
  65. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/MANIFEST.in +6 -0
  66. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/README.rst +180 -0
  67. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/Doxyfile +23 -0
  68. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/Makefile +192 -0
  69. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/_static/theme_overrides.css +11 -0
  70. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/cast/chrono.rst +81 -0
  71. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/cast/custom.rst +93 -0
  72. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/cast/eigen.rst +310 -0
  73. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/cast/functional.rst +109 -0
  74. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/cast/index.rst +43 -0
  75. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/cast/overview.rst +171 -0
  76. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/cast/stl.rst +251 -0
  77. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/cast/strings.rst +305 -0
  78. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/classes.rst +1297 -0
  79. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/embedding.rst +262 -0
  80. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/exceptions.rst +396 -0
  81. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/functions.rst +568 -0
  82. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/misc.rst +337 -0
  83. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/pycpp/index.rst +13 -0
  84. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/pycpp/numpy.rst +463 -0
  85. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/pycpp/object.rst +286 -0
  86. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/pycpp/utilities.rst +155 -0
  87. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/advanced/smart_ptrs.rst +174 -0
  88. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/basics.rst +308 -0
  89. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/benchmark.py +91 -0
  90. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/benchmark.rst +95 -0
  91. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/changelog.rst +2050 -0
  92. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/classes.rst +542 -0
  93. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/cmake/index.rst +8 -0
  94. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/compiling.rst +648 -0
  95. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/conf.py +381 -0
  96. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/faq.rst +343 -0
  97. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/index.rst +48 -0
  98. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/installing.rst +105 -0
  99. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/limitations.rst +72 -0
  100. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/pybind11-logo.png +0 -0
  101. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/pybind11_vs_boost_python1.png +0 -0
  102. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/pybind11_vs_boost_python1.svg +427 -0
  103. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/pybind11_vs_boost_python2.png +0 -0
  104. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/pybind11_vs_boost_python2.svg +427 -0
  105. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/reference.rst +130 -0
  106. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/release.rst +96 -0
  107. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/requirements.txt +8 -0
  108. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/docs/upgrade.rst +548 -0
  109. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/attr.h +605 -0
  110. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/buffer_info.h +144 -0
  111. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/cast.h +1432 -0
  112. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/chrono.h +213 -0
  113. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/common.h +2 -0
  114. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/complex.h +65 -0
  115. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/detail/class.h +709 -0
  116. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/detail/common.h +1021 -0
  117. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/detail/descr.h +104 -0
  118. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/detail/init.h +346 -0
  119. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/detail/internals.h +467 -0
  120. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/detail/type_caster_base.h +978 -0
  121. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/detail/typeid.h +55 -0
  122. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/eigen.h +606 -0
  123. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/embed.h +284 -0
  124. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/eval.h +163 -0
  125. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/functional.h +121 -0
  126. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/gil.h +193 -0
  127. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/iostream.h +275 -0
  128. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/numpy.h +1741 -0
  129. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/operators.h +163 -0
  130. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/options.h +65 -0
  131. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/pybind11.h +2497 -0
  132. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/pytypes.h +1879 -0
  133. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/stl/filesystem.h +103 -0
  134. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/stl.h +375 -0
  135. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/include/pybind11/stl_bind.h +747 -0
  136. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/noxfile.py +88 -0
  137. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/pybind11/__init__.py +11 -0
  138. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/pybind11/__main__.py +52 -0
  139. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/pybind11/_version.py +12 -0
  140. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/pybind11/_version.pyi +6 -0
  141. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/pybind11/commands.py +21 -0
  142. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/pybind11/py.typed +0 -0
  143. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/pybind11/setup_helpers.py +482 -0
  144. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/pybind11/setup_helpers.pyi +63 -0
  145. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/pyproject.toml +41 -0
  146. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/setup.cfg +56 -0
  147. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/setup.py +155 -0
  148. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/CMakeLists.txt +503 -0
  149. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/conftest.py +208 -0
  150. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/constructor_stats.h +275 -0
  151. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/cross_module_gil_utils.cpp +73 -0
  152. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/env.py +33 -0
  153. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/extra_python_package/pytest.ini +0 -0
  154. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/extra_python_package/test_files.py +279 -0
  155. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/extra_setuptools/pytest.ini +0 -0
  156. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/extra_setuptools/test_setuphelper.py +143 -0
  157. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/local_bindings.h +85 -0
  158. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/object.h +179 -0
  159. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/pybind11_cross_module_tests.cpp +151 -0
  160. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/pybind11_tests.cpp +91 -0
  161. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/pybind11_tests.h +85 -0
  162. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/pytest.ini +19 -0
  163. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/requirements.txt +12 -0
  164. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_async.cpp +26 -0
  165. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_async.py +25 -0
  166. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_buffers.cpp +216 -0
  167. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_buffers.py +163 -0
  168. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_builtin_casters.cpp +286 -0
  169. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_builtin_casters.py +536 -0
  170. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_call_policies.cpp +107 -0
  171. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_call_policies.py +248 -0
  172. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_callbacks.cpp +227 -0
  173. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_callbacks.py +202 -0
  174. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_chrono.cpp +84 -0
  175. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_chrono.py +210 -0
  176. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_class.cpp +550 -0
  177. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_class.py +473 -0
  178. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_cmake_build/CMakeLists.txt +84 -0
  179. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_cmake_build/embed.cpp +21 -0
  180. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_cmake_build/installed_embed/CMakeLists.txt +28 -0
  181. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_cmake_build/installed_function/CMakeLists.txt +39 -0
  182. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_cmake_build/installed_target/CMakeLists.txt +46 -0
  183. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_cmake_build/main.cpp +6 -0
  184. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_cmake_build/subdirectory_embed/CMakeLists.txt +41 -0
  185. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_cmake_build/subdirectory_function/CMakeLists.txt +35 -0
  186. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_cmake_build/subdirectory_target/CMakeLists.txt +41 -0
  187. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_cmake_build/test.py +10 -0
  188. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_constants_and_functions.cpp +165 -0
  189. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_constants_and_functions.py +53 -0
  190. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_copy_move.cpp +238 -0
  191. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_copy_move.py +126 -0
  192. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_custom_type_casters.cpp +141 -0
  193. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_custom_type_casters.py +117 -0
  194. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_custom_type_setup.cpp +41 -0
  195. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_custom_type_setup.py +50 -0
  196. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_docstring_options.cpp +69 -0
  197. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_docstring_options.py +42 -0
  198. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_eigen.cpp +348 -0
  199. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_eigen.py +771 -0
  200. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_embed/CMakeLists.txt +47 -0
  201. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_embed/catch.cpp +22 -0
  202. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_embed/external_module.cpp +23 -0
  203. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_embed/test_interpreter.cpp +326 -0
  204. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_embed/test_interpreter.py +15 -0
  205. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_enum.cpp +148 -0
  206. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_enum.py +272 -0
  207. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_eval.cpp +119 -0
  208. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_eval.py +51 -0
  209. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_eval_call.py +5 -0
  210. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_exceptions.cpp +285 -0
  211. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_exceptions.h +12 -0
  212. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_exceptions.py +265 -0
  213. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_factory_constructors.cpp +397 -0
  214. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_factory_constructors.py +520 -0
  215. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_gil_scoped.cpp +49 -0
  216. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_gil_scoped.py +94 -0
  217. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_iostream.cpp +125 -0
  218. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_iostream.py +331 -0
  219. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_kwargs_and_defaults.cpp +153 -0
  220. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_kwargs_and_defaults.py +284 -0
  221. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_local_bindings.cpp +107 -0
  222. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_local_bindings.py +257 -0
  223. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_methods_and_attributes.cpp +412 -0
  224. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_methods_and_attributes.py +517 -0
  225. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_modules.cpp +102 -0
  226. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_modules.py +92 -0
  227. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_multiple_inheritance.cpp +233 -0
  228. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_multiple_inheritance.py +360 -0
  229. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_numpy_array.cpp +472 -0
  230. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_numpy_array.py +593 -0
  231. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_numpy_dtypes.cpp +524 -0
  232. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_numpy_dtypes.py +441 -0
  233. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_numpy_vectorize.cpp +103 -0
  234. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_numpy_vectorize.py +267 -0
  235. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_opaque_types.cpp +73 -0
  236. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_opaque_types.py +59 -0
  237. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_operator_overloading.cpp +235 -0
  238. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_operator_overloading.py +146 -0
  239. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_pickling.cpp +189 -0
  240. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_pickling.py +82 -0
  241. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_pytypes.cpp +560 -0
  242. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_pytypes.py +651 -0
  243. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_sequences_and_iterators.cpp +500 -0
  244. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_sequences_and_iterators.py +253 -0
  245. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_smart_ptr.cpp +452 -0
  246. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_smart_ptr.py +318 -0
  247. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_stl.cpp +342 -0
  248. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_stl.py +291 -0
  249. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_stl_binders.cpp +131 -0
  250. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_stl_binders.py +318 -0
  251. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_tagbased_polymorphic.cpp +144 -0
  252. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_tagbased_polymorphic.py +29 -0
  253. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_thread.cpp +66 -0
  254. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_thread.py +44 -0
  255. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_union.cpp +22 -0
  256. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_union.py +9 -0
  257. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_virtual_functions.cpp +510 -0
  258. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/test_virtual_functions.py +408 -0
  259. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/valgrind-numpy-scipy.supp +140 -0
  260. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tests/valgrind-python.supp +117 -0
  261. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/FindCatch.cmake +70 -0
  262. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/FindEigen3.cmake +86 -0
  263. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/FindPythonLibsNew.cmake +257 -0
  264. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/check-style.sh +44 -0
  265. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/cmake_uninstall.cmake.in +23 -0
  266. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/libsize.py +39 -0
  267. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/make_changelog.py +64 -0
  268. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/pybind11Common.cmake +402 -0
  269. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/pybind11Config.cmake.in +233 -0
  270. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/pybind11NewTools.cmake +276 -0
  271. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/pybind11Tools.cmake +214 -0
  272. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/pyproject.toml +3 -0
  273. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/setup_global.py.in +65 -0
  274. xcoll/scattering_routines/geant4/collimasim/lib/pybind11/tools/setup_main.py.in +41 -0
  275. xcoll/scattering_routines/geant4/collimasim/pyproject.toml +8 -0
  276. xcoll/scattering_routines/geant4/collimasim/setup.py +144 -0
  277. xcoll/scattering_routines/geant4/collimasim/src/collimasim/BDSPyATInterface.cpp +403 -0
  278. xcoll/scattering_routines/geant4/collimasim/src/collimasim/BDSPyATInterface.hh +100 -0
  279. xcoll/scattering_routines/geant4/collimasim/src/collimasim/BDSXtrackInterface.cpp +763 -0
  280. xcoll/scattering_routines/geant4/collimasim/src/collimasim/BDSXtrackInterface.hh +118 -0
  281. xcoll/scattering_routines/geant4/collimasim/src/collimasim/__init__.py +8 -0
  282. xcoll/scattering_routines/geant4/collimasim/src/collimasim/bindings.cpp +63 -0
  283. xcoll/scattering_routines/geant4/collimasim/src/collimasim/pyCollimatorPass.py +142 -0
  284. xcoll/scattering_routines/geant4/collimasim/src/collimasim/xtrack_collimator.py +556 -0
  285. xcoll/scattering_routines/geant4/collimasim/src/collimasim.egg-info/PKG-INFO +6 -0
  286. xcoll/scattering_routines/geant4/collimasim/src/collimasim.egg-info/SOURCES.txt +24 -0
  287. xcoll/scattering_routines/geant4/collimasim/src/collimasim.egg-info/dependency_links.txt +1 -0
  288. xcoll/scattering_routines/geant4/collimasim/src/collimasim.egg-info/not-zip-safe +1 -0
  289. xcoll/scattering_routines/geant4/collimasim/src/collimasim.egg-info/top_level.txt +1 -0
  290. xcoll/scattering_routines/geant4/collimasim/tests/README.md +25 -0
  291. xcoll/scattering_routines/geant4/collimasim/tests/resources/CollDB_forions.dat +25 -0
  292. xcoll/scattering_routines/geant4/collimasim/tests/resources/CollDB_new_example.dat +18 -0
  293. xcoll/scattering_routines/geant4/collimasim/tests/resources/CollDB_old_example.dat +68 -0
  294. xcoll/scattering_routines/geant4/collimasim/tests/resources/CollDB_testing.dat +15 -0
  295. xcoll/scattering_routines/geant4/collimasim/tests/resources/CollDB_yaml_example.yaml +110 -0
  296. xcoll/scattering_routines/geant4/collimasim/tests/resources/collgaps.dat +7 -0
  297. xcoll/scattering_routines/geant4/collimasim/tests/resources/collgaps_pyat_test.dat +3 -0
  298. xcoll/scattering_routines/geant4/collimasim/tests/resources/collonly_twiss_file_example.tfs +54 -0
  299. xcoll/scattering_routines/geant4/collimasim/tests/resources/settings.gmad +3 -0
  300. xcoll/scattering_routines/geant4/collimasim/tests/resources/settings_black_absorber.gmad +3 -0
  301. xcoll/scattering_routines/geant4/collimasim/tests/resources/settings_ions.gmad +5 -0
  302. xcoll/scattering_routines/geant4/collimasim/tests/resources/twiss_file_testing.tfs +51 -0
  303. xcoll/scattering_routines/geant4/collimasim/tests/test_pyat.py +65 -0
  304. xcoll/scattering_routines/geant4/collimasim/tests/test_pyat_passmethod.py +59 -0
  305. xcoll/scattering_routines/geant4/collimasim/tests/test_pyat_tracking.py +102 -0
  306. xcoll/scattering_routines/geant4/collimasim/tests/test_xtrack.py +75 -0
  307. xcoll/scattering_routines/geant4/collimasim/tests/test_xtrack_angle.py +74 -0
  308. xcoll/scattering_routines/geant4/collimasim/tests/test_xtrack_colldb_load.py +84 -0
  309. xcoll/scattering_routines/geant4/collimasim/tests/test_xtrack_interaction.py +159 -0
  310. xcoll/scattering_routines/geant4/collimasim/tests/test_xtrack_interaction_ion.py +99 -0
  311. xcoll/scattering_routines/geant4/collimasim/tests/test_xtrack_ions.py +78 -0
  312. xcoll/scattering_routines/geant4/collimasim/tests/test_xtrack_lost_energy.py +88 -0
  313. xcoll/scattering_routines/geant4/collimasim/tests/test_xtrack_tilt.py +80 -0
  314. xcoll/scattering_routines/geant4/collimasim/tests/test_xtrack_tracking.py +97 -0
  315. xcoll/scattering_routines/geant4/collimasim/tests/test_xtrack_tracking_ions.py +96 -0
  316. xcoll/scattering_routines/geometry/collimator_geometry.h +9 -10
  317. xcoll/scattering_routines/geometry/crystal_geometry.h +9 -6
  318. {xcoll-0.4.0.dist-info → xcoll-0.5.1.dist-info}/METADATA +1 -1
  319. xcoll-0.5.1.dist-info/RECORD +413 -0
  320. xcoll/scattering_routines/fluka/build_fluka_input.py +0 -58
  321. xcoll-0.4.0.dist-info/RECORD +0 -126
  322. {xcoll-0.4.0.dist-info → xcoll-0.5.1.dist-info}/LICENSE +0 -0
  323. {xcoll-0.4.0.dist-info → xcoll-0.5.1.dist-info}/NOTICE +0 -0
  324. {xcoll-0.4.0.dist-info → xcoll-0.5.1.dist-info}/WHEEL +0 -0
@@ -0,0 +1,1879 @@
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
+ #include <utility>
15
+ #include <type_traits>
16
+
17
+ #if defined(PYBIND11_HAS_OPTIONAL)
18
+ # include <optional>
19
+ #endif
20
+
21
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
22
+
23
+ /* A few forward declarations */
24
+ class handle; class object;
25
+ class str; class iterator;
26
+ class type;
27
+ struct arg; struct arg_v;
28
+
29
+ PYBIND11_NAMESPACE_BEGIN(detail)
30
+ class args_proxy;
31
+ bool isinstance_generic(handle obj, const std::type_info &tp);
32
+
33
+ // Accessor forward declarations
34
+ template <typename Policy> class accessor;
35
+ namespace accessor_policies {
36
+ struct obj_attr;
37
+ struct str_attr;
38
+ struct generic_item;
39
+ struct sequence_item;
40
+ struct list_item;
41
+ struct tuple_item;
42
+ } // namespace accessor_policies
43
+ using obj_attr_accessor = accessor<accessor_policies::obj_attr>;
44
+ using str_attr_accessor = accessor<accessor_policies::str_attr>;
45
+ using item_accessor = accessor<accessor_policies::generic_item>;
46
+ using sequence_accessor = accessor<accessor_policies::sequence_item>;
47
+ using list_accessor = accessor<accessor_policies::list_item>;
48
+ using tuple_accessor = accessor<accessor_policies::tuple_item>;
49
+
50
+ /// Tag and check to identify a class which implements the Python object API
51
+ class pyobject_tag { };
52
+ template <typename T> using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
53
+
54
+ /** \rst
55
+ A mixin class which adds common functions to `handle`, `object` and various accessors.
56
+ The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``.
57
+ \endrst */
58
+ template <typename Derived>
59
+ class object_api : public pyobject_tag {
60
+ const Derived &derived() const { return static_cast<const Derived &>(*this); }
61
+
62
+ public:
63
+ /** \rst
64
+ Return an iterator equivalent to calling ``iter()`` in Python. The object
65
+ must be a collection which supports the iteration protocol.
66
+ \endrst */
67
+ iterator begin() const;
68
+ /// Return a sentinel which ends iteration.
69
+ iterator end() const;
70
+
71
+ /** \rst
72
+ Return an internal functor to invoke the object's sequence protocol. Casting
73
+ the returned ``detail::item_accessor`` instance to a `handle` or `object`
74
+ subclass causes a corresponding call to ``__getitem__``. Assigning a `handle`
75
+ or `object` subclass causes a call to ``__setitem__``.
76
+ \endrst */
77
+ item_accessor operator[](handle key) const;
78
+ /// See above (the only difference is that they key is provided as a string literal)
79
+ item_accessor operator[](const char *key) const;
80
+
81
+ /** \rst
82
+ Return an internal functor to access the object's attributes. Casting the
83
+ returned ``detail::obj_attr_accessor`` instance to a `handle` or `object`
84
+ subclass causes a corresponding call to ``getattr``. Assigning a `handle`
85
+ or `object` subclass causes a call to ``setattr``.
86
+ \endrst */
87
+ obj_attr_accessor attr(handle key) const;
88
+ /// See above (the only difference is that they key is provided as a string literal)
89
+ str_attr_accessor attr(const char *key) const;
90
+
91
+ /** \rst
92
+ Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple``
93
+ or ``list`` for a function call. Applying another * to the result yields
94
+ ** unpacking, e.g. to unpack a dict as function keyword arguments.
95
+ See :ref:`calling_python_functions`.
96
+ \endrst */
97
+ args_proxy operator*() const;
98
+
99
+ /// Check if the given item is contained within this object, i.e. ``item in obj``.
100
+ template <typename T> bool contains(T &&item) const;
101
+
102
+ /** \rst
103
+ Assuming the Python object is a function or implements the ``__call__``
104
+ protocol, ``operator()`` invokes the underlying function, passing an
105
+ arbitrary set of parameters. The result is returned as a `object` and
106
+ may need to be converted back into a Python object using `handle::cast()`.
107
+
108
+ When some of the arguments cannot be converted to Python objects, the
109
+ function will throw a `cast_error` exception. When the Python function
110
+ call fails, a `error_already_set` exception is thrown.
111
+ \endrst */
112
+ template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
113
+ object operator()(Args &&...args) const;
114
+ template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
115
+ PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)")
116
+ object call(Args&&... args) const;
117
+
118
+ /// Equivalent to ``obj is other`` in Python.
119
+ bool is(object_api const& other) const { return derived().ptr() == other.derived().ptr(); }
120
+ /// Equivalent to ``obj is None`` in Python.
121
+ bool is_none() const { return derived().ptr() == Py_None; }
122
+ /// Equivalent to obj == other in Python
123
+ bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); }
124
+ bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); }
125
+ bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); }
126
+ bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); }
127
+ bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); }
128
+ bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); }
129
+
130
+ object operator-() const;
131
+ object operator~() const;
132
+ object operator+(object_api const &other) const;
133
+ object operator+=(object_api const &other) const;
134
+ object operator-(object_api const &other) const;
135
+ object operator-=(object_api const &other) const;
136
+ object operator*(object_api const &other) const;
137
+ object operator*=(object_api const &other) const;
138
+ object operator/(object_api const &other) const;
139
+ object operator/=(object_api const &other) const;
140
+ object operator|(object_api const &other) const;
141
+ object operator|=(object_api const &other) const;
142
+ object operator&(object_api const &other) const;
143
+ object operator&=(object_api const &other) const;
144
+ object operator^(object_api const &other) const;
145
+ object operator^=(object_api const &other) const;
146
+ object operator<<(object_api const &other) const;
147
+ object operator<<=(object_api const &other) const;
148
+ object operator>>(object_api const &other) const;
149
+ object operator>>=(object_api const &other) const;
150
+
151
+ PYBIND11_DEPRECATED("Use py::str(obj) instead")
152
+ pybind11::str str() const;
153
+
154
+ /// Get or set the object's docstring, i.e. ``obj.__doc__``.
155
+ str_attr_accessor doc() const;
156
+
157
+ /// Return the object's current reference count
158
+ int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); }
159
+
160
+ // TODO PYBIND11_DEPRECATED("Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()")
161
+ handle get_type() const;
162
+
163
+ private:
164
+ bool rich_compare(object_api const &other, int value) const;
165
+ };
166
+
167
+ PYBIND11_NAMESPACE_END(detail)
168
+
169
+ /** \rst
170
+ Holds a reference to a Python object (no reference counting)
171
+
172
+ The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a
173
+ ``PyObject *`` in Python's C API). It does not perform any automatic reference
174
+ counting and merely provides a basic C++ interface to various Python API functions.
175
+
176
+ .. seealso::
177
+ The `object` class inherits from `handle` and adds automatic reference
178
+ counting features.
179
+ \endrst */
180
+ class handle : public detail::object_api<handle> {
181
+ public:
182
+ /// The default constructor creates a handle with a ``nullptr``-valued pointer
183
+ handle() = default;
184
+ /// Creates a ``handle`` from the given raw Python object pointer
185
+ // NOLINTNEXTLINE(google-explicit-constructor)
186
+ handle(PyObject *ptr) : m_ptr(ptr) { } // Allow implicit conversion from PyObject*
187
+
188
+ /// Return the underlying ``PyObject *`` pointer
189
+ PyObject *ptr() const { return m_ptr; }
190
+ PyObject *&ptr() { return m_ptr; }
191
+
192
+ /** \rst
193
+ Manually increase the reference count of the Python object. Usually, it is
194
+ preferable to use the `object` class which derives from `handle` and calls
195
+ this function automatically. Returns a reference to itself.
196
+ \endrst */
197
+ const handle& inc_ref() const & { Py_XINCREF(m_ptr); return *this; }
198
+
199
+ /** \rst
200
+ Manually decrease the reference count of the Python object. Usually, it is
201
+ preferable to use the `object` class which derives from `handle` and calls
202
+ this function automatically. Returns a reference to itself.
203
+ \endrst */
204
+ const handle& dec_ref() const & { Py_XDECREF(m_ptr); return *this; }
205
+
206
+ /** \rst
207
+ Attempt to cast the Python object into the given C++ type. A `cast_error`
208
+ will be throw upon failure.
209
+ \endrst */
210
+ template <typename T> T cast() const;
211
+ /// Return ``true`` when the `handle` wraps a valid Python object
212
+ explicit operator bool() const { return m_ptr != nullptr; }
213
+ /** \rst
214
+ Deprecated: Check that the underlying pointers are the same.
215
+ Equivalent to ``obj1 is obj2`` in Python.
216
+ \endrst */
217
+ PYBIND11_DEPRECATED("Use obj1.is(obj2) instead")
218
+ bool operator==(const handle &h) const { return m_ptr == h.m_ptr; }
219
+ PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead")
220
+ bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }
221
+ PYBIND11_DEPRECATED("Use handle::operator bool() instead")
222
+ bool check() const { return m_ptr != nullptr; }
223
+ protected:
224
+ PyObject *m_ptr = nullptr;
225
+ };
226
+
227
+ /** \rst
228
+ Holds a reference to a Python object (with reference counting)
229
+
230
+ Like `handle`, the `object` class is a thin wrapper around an arbitrary Python
231
+ object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it
232
+ optionally increases the object's reference count upon construction, and it
233
+ *always* decreases the reference count when the `object` instance goes out of
234
+ scope and is destructed. When using `object` instances consistently, it is much
235
+ easier to get reference counting right at the first attempt.
236
+ \endrst */
237
+ class object : public handle {
238
+ public:
239
+ object() = default;
240
+ PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()")
241
+ object(handle h, bool is_borrowed) : handle(h) { if (is_borrowed) inc_ref(); }
242
+ /// Copy constructor; always increases the reference count
243
+ object(const object &o) : handle(o) { inc_ref(); }
244
+ /// Move constructor; steals the object from ``other`` and preserves its reference count
245
+ object(object &&other) noexcept { m_ptr = other.m_ptr; other.m_ptr = nullptr; }
246
+ /// Destructor; automatically calls `handle::dec_ref()`
247
+ ~object() { dec_ref(); }
248
+
249
+ /** \rst
250
+ Resets the internal pointer to ``nullptr`` without decreasing the
251
+ object's reference count. The function returns a raw handle to the original
252
+ Python object.
253
+ \endrst */
254
+ handle release() {
255
+ PyObject *tmp = m_ptr;
256
+ m_ptr = nullptr;
257
+ return handle(tmp);
258
+ }
259
+
260
+ object& operator=(const object &other) {
261
+ other.inc_ref();
262
+ // Use temporary variable to ensure `*this` remains valid while
263
+ // `Py_XDECREF` executes, in case `*this` is accessible from Python.
264
+ handle temp(m_ptr);
265
+ m_ptr = other.m_ptr;
266
+ temp.dec_ref();
267
+ return *this;
268
+ }
269
+
270
+ object& operator=(object &&other) noexcept {
271
+ if (this != &other) {
272
+ handle temp(m_ptr);
273
+ m_ptr = other.m_ptr;
274
+ other.m_ptr = nullptr;
275
+ temp.dec_ref();
276
+ }
277
+ return *this;
278
+ }
279
+
280
+ // Calling cast() on an object lvalue just copies (via handle::cast)
281
+ template <typename T> T cast() const &;
282
+ // Calling on an object rvalue does a move, if needed and/or possible
283
+ template <typename T> T cast() &&;
284
+
285
+ protected:
286
+ // Tags for choosing constructors from raw PyObject *
287
+ struct borrowed_t { };
288
+ struct stolen_t { };
289
+
290
+ #ifndef DOXYGEN_SHOULD_SKIP_THIS // Issue in breathe 4.26.1
291
+ template <typename T> friend T reinterpret_borrow(handle);
292
+ template <typename T> friend T reinterpret_steal(handle);
293
+ #endif
294
+
295
+ public:
296
+ // Only accessible from derived classes and the reinterpret_* functions
297
+ object(handle h, borrowed_t) : handle(h) { inc_ref(); }
298
+ object(handle h, stolen_t) : handle(h) { }
299
+ };
300
+
301
+ /** \rst
302
+ Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference.
303
+ The target type ``T`` must be `object` or one of its derived classes. The function
304
+ doesn't do any conversions or checks. It's up to the user to make sure that the
305
+ target type is correct.
306
+
307
+ .. code-block:: cpp
308
+
309
+ PyObject *p = PyList_GetItem(obj, index);
310
+ py::object o = reinterpret_borrow<py::object>(p);
311
+ // or
312
+ py::tuple t = reinterpret_borrow<py::tuple>(p); // <-- `p` must be already be a `tuple`
313
+ \endrst */
314
+ template <typename T> T reinterpret_borrow(handle h) { return {h, object::borrowed_t{}}; }
315
+
316
+ /** \rst
317
+ Like `reinterpret_borrow`, but steals the reference.
318
+
319
+ .. code-block:: cpp
320
+
321
+ PyObject *p = PyObject_Str(obj);
322
+ py::str s = reinterpret_steal<py::str>(p); // <-- `p` must be already be a `str`
323
+ \endrst */
324
+ template <typename T> T reinterpret_steal(handle h) { return {h, object::stolen_t{}}; }
325
+
326
+ PYBIND11_NAMESPACE_BEGIN(detail)
327
+ std::string error_string();
328
+ PYBIND11_NAMESPACE_END(detail)
329
+
330
+ #if defined(_MSC_VER)
331
+ # pragma warning(push)
332
+ # pragma warning(disable: 4275 4251) // warning C4275: An exported class was derived from a class that wasn't exported. Can be ignored when derived from a STL class.
333
+ #endif
334
+ /// Fetch and hold an error which was already set in Python. An instance of this is typically
335
+ /// thrown to propagate python-side errors back through C++ which can either be caught manually or
336
+ /// else falls back to the function dispatcher (which then raises the captured error back to
337
+ /// python).
338
+ class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::runtime_error {
339
+ public:
340
+ /// Constructs a new exception from the current Python error indicator, if any. The current
341
+ /// Python error indicator will be cleared.
342
+ error_already_set() : std::runtime_error(detail::error_string()) {
343
+ PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());
344
+ }
345
+
346
+ error_already_set(const error_already_set &) = default;
347
+ error_already_set(error_already_set &&) = default;
348
+
349
+ inline ~error_already_set() override;
350
+
351
+ /// Give the currently-held error back to Python, if any. If there is currently a Python error
352
+ /// already set it is cleared first. After this call, the current object no longer stores the
353
+ /// error variables (but the `.what()` string is still available).
354
+ void restore() { PyErr_Restore(m_type.release().ptr(), m_value.release().ptr(), m_trace.release().ptr()); }
355
+
356
+ /// If it is impossible to raise the currently-held error, such as in a destructor, we can write
357
+ /// it out using Python's unraisable hook (`sys.unraisablehook`). The error context should be
358
+ /// some object whose `repr()` helps identify the location of the error. Python already knows the
359
+ /// type and value of the error, so there is no need to repeat that. After this call, the current
360
+ /// object no longer stores the error variables, and neither does Python.
361
+ void discard_as_unraisable(object err_context) {
362
+ restore();
363
+ PyErr_WriteUnraisable(err_context.ptr());
364
+ }
365
+ /// An alternate version of `discard_as_unraisable()`, where a string provides information on the
366
+ /// location of the error. For example, `__func__` could be helpful.
367
+ void discard_as_unraisable(const char *err_context) {
368
+ discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context)));
369
+ }
370
+
371
+ // Does nothing; provided for backwards compatibility.
372
+ PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated")
373
+ void clear() {}
374
+
375
+ /// Check if the currently trapped error type matches the given Python exception class (or a
376
+ /// subclass thereof). May also be passed a tuple to search for any exception class matches in
377
+ /// the given tuple.
378
+ bool matches(handle exc) const {
379
+ return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0);
380
+ }
381
+
382
+ const object& type() const { return m_type; }
383
+ const object& value() const { return m_value; }
384
+ const object& trace() const { return m_trace; }
385
+
386
+ private:
387
+ object m_type, m_value, m_trace;
388
+ };
389
+ #if defined(_MSC_VER)
390
+ # pragma warning(pop)
391
+ #endif
392
+
393
+ #if PY_VERSION_HEX >= 0x03030000
394
+
395
+ /// Replaces the current Python error indicator with the chosen error, performing a
396
+ /// 'raise from' to indicate that the chosen error was caused by the original error.
397
+ inline void raise_from(PyObject *type, const char *message) {
398
+ // Based on _PyErr_FormatVFromCause:
399
+ // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405
400
+ // See https://github.com/pybind/pybind11/pull/2112 for details.
401
+ PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr;
402
+
403
+ assert(PyErr_Occurred());
404
+ PyErr_Fetch(&exc, &val, &tb);
405
+ PyErr_NormalizeException(&exc, &val, &tb);
406
+ if (tb != nullptr) {
407
+ PyException_SetTraceback(val, tb);
408
+ Py_DECREF(tb);
409
+ }
410
+ Py_DECREF(exc);
411
+ assert(!PyErr_Occurred());
412
+
413
+ PyErr_SetString(type, message);
414
+
415
+ PyErr_Fetch(&exc, &val2, &tb);
416
+ PyErr_NormalizeException(&exc, &val2, &tb);
417
+ Py_INCREF(val);
418
+ PyException_SetCause(val2, val);
419
+ PyException_SetContext(val2, val);
420
+ PyErr_Restore(exc, val2, tb);
421
+ }
422
+
423
+ /// Sets the current Python error indicator with the chosen error, performing a 'raise from'
424
+ /// from the error contained in error_already_set to indicate that the chosen error was
425
+ /// caused by the original error. After this function is called error_already_set will
426
+ /// no longer contain an error.
427
+ inline void raise_from(error_already_set& err, PyObject *type, const char *message) {
428
+ err.restore();
429
+ raise_from(type, message);
430
+ }
431
+
432
+ #endif
433
+
434
+ /** \defgroup python_builtins _
435
+ Unless stated otherwise, the following C++ functions behave the same
436
+ as their Python counterparts.
437
+ */
438
+
439
+ /** \ingroup python_builtins
440
+ \rst
441
+ Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of
442
+ `object` or a class which was exposed to Python as ``py::class_<T>``.
443
+ \endrst */
444
+ template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0>
445
+ bool isinstance(handle obj) { return T::check_(obj); }
446
+
447
+ template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0>
448
+ bool isinstance(handle obj) { return detail::isinstance_generic(obj, typeid(T)); }
449
+
450
+ template <> inline bool isinstance<handle>(handle) = delete;
451
+ template <> inline bool isinstance<object>(handle obj) { return obj.ptr() != nullptr; }
452
+
453
+ /// \ingroup python_builtins
454
+ /// Return true if ``obj`` is an instance of the ``type``.
455
+ inline bool isinstance(handle obj, handle type) {
456
+ const auto result = PyObject_IsInstance(obj.ptr(), type.ptr());
457
+ if (result == -1)
458
+ throw error_already_set();
459
+ return result != 0;
460
+ }
461
+
462
+ /// \addtogroup python_builtins
463
+ /// @{
464
+ inline bool hasattr(handle obj, handle name) {
465
+ return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1;
466
+ }
467
+
468
+ inline bool hasattr(handle obj, const char *name) {
469
+ return PyObject_HasAttrString(obj.ptr(), name) == 1;
470
+ }
471
+
472
+ inline void delattr(handle obj, handle name) {
473
+ if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) { throw error_already_set(); }
474
+ }
475
+
476
+ inline void delattr(handle obj, const char *name) {
477
+ if (PyObject_DelAttrString(obj.ptr(), name) != 0) { throw error_already_set(); }
478
+ }
479
+
480
+ inline object getattr(handle obj, handle name) {
481
+ PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr());
482
+ if (!result) { throw error_already_set(); }
483
+ return reinterpret_steal<object>(result);
484
+ }
485
+
486
+ inline object getattr(handle obj, const char *name) {
487
+ PyObject *result = PyObject_GetAttrString(obj.ptr(), name);
488
+ if (!result) { throw error_already_set(); }
489
+ return reinterpret_steal<object>(result);
490
+ }
491
+
492
+ inline object getattr(handle obj, handle name, handle default_) {
493
+ if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) {
494
+ return reinterpret_steal<object>(result);
495
+ }
496
+ PyErr_Clear();
497
+ return reinterpret_borrow<object>(default_);
498
+ }
499
+
500
+ inline object getattr(handle obj, const char *name, handle default_) {
501
+ if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) {
502
+ return reinterpret_steal<object>(result);
503
+ }
504
+ PyErr_Clear();
505
+ return reinterpret_borrow<object>(default_);
506
+ }
507
+
508
+ inline void setattr(handle obj, handle name, handle value) {
509
+ if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) { throw error_already_set(); }
510
+ }
511
+
512
+ inline void setattr(handle obj, const char *name, handle value) {
513
+ if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { throw error_already_set(); }
514
+ }
515
+
516
+ inline ssize_t hash(handle obj) {
517
+ auto h = PyObject_Hash(obj.ptr());
518
+ if (h == -1) { throw error_already_set(); }
519
+ return h;
520
+ }
521
+
522
+ /// @} python_builtins
523
+
524
+ PYBIND11_NAMESPACE_BEGIN(detail)
525
+ inline handle get_function(handle value) {
526
+ if (value) {
527
+ #if PY_MAJOR_VERSION >= 3
528
+ if (PyInstanceMethod_Check(value.ptr()))
529
+ value = PyInstanceMethod_GET_FUNCTION(value.ptr());
530
+ else
531
+ #endif
532
+ if (PyMethod_Check(value.ptr()))
533
+ value = PyMethod_GET_FUNCTION(value.ptr());
534
+ }
535
+ return value;
536
+ }
537
+
538
+ // Reimplementation of python's dict helper functions to ensure that exceptions
539
+ // aren't swallowed (see #2862)
540
+
541
+ // copied from cpython _PyDict_GetItemStringWithError
542
+ inline PyObject * dict_getitemstring(PyObject *v, const char *key)
543
+ {
544
+ #if PY_MAJOR_VERSION >= 3
545
+ PyObject *kv = nullptr, *rv = nullptr;
546
+ kv = PyUnicode_FromString(key);
547
+ if (kv == NULL) {
548
+ throw error_already_set();
549
+ }
550
+
551
+ rv = PyDict_GetItemWithError(v, kv);
552
+ Py_DECREF(kv);
553
+ if (rv == NULL && PyErr_Occurred()) {
554
+ throw error_already_set();
555
+ }
556
+ return rv;
557
+ #else
558
+ return PyDict_GetItemString(v, key);
559
+ #endif
560
+ }
561
+
562
+ inline PyObject * dict_getitem(PyObject *v, PyObject *key)
563
+ {
564
+ #if PY_MAJOR_VERSION >= 3
565
+ PyObject *rv = PyDict_GetItemWithError(v, key);
566
+ if (rv == NULL && PyErr_Occurred()) {
567
+ throw error_already_set();
568
+ }
569
+ return rv;
570
+ #else
571
+ return PyDict_GetItem(v, key);
572
+ #endif
573
+ }
574
+
575
+ // Helper aliases/functions to support implicit casting of values given to python accessors/methods.
576
+ // When given a pyobject, this simply returns the pyobject as-is; for other C++ type, the value goes
577
+ // through pybind11::cast(obj) to convert it to an `object`.
578
+ template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0>
579
+ auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) { return std::forward<T>(o); }
580
+ // The following casting version is implemented in cast.h:
581
+ template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0>
582
+ object object_or_cast(T &&o);
583
+ // Match a PyObject*, which we want to convert directly to handle via its converting constructor
584
+ inline handle object_or_cast(PyObject *ptr) { return ptr; }
585
+
586
+ #if defined(_MSC_VER) && _MSC_VER < 1920
587
+ # pragma warning(push)
588
+ # pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
589
+ #endif
590
+ template <typename Policy>
591
+ class accessor : public object_api<accessor<Policy>> {
592
+ using key_type = typename Policy::key_type;
593
+
594
+ public:
595
+ accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) { }
596
+ accessor(const accessor &) = default;
597
+ accessor(accessor &&) noexcept = default;
598
+
599
+ // accessor overload required to override default assignment operator (templates are not allowed
600
+ // to replace default compiler-generated assignments).
601
+ void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); }
602
+ void operator=(const accessor &a) & { operator=(handle(a)); }
603
+
604
+ template <typename T> void operator=(T &&value) && {
605
+ Policy::set(obj, key, object_or_cast(std::forward<T>(value)));
606
+ }
607
+ template <typename T> void operator=(T &&value) & {
608
+ get_cache() = reinterpret_borrow<object>(object_or_cast(std::forward<T>(value)));
609
+ }
610
+
611
+ template <typename T = Policy>
612
+ PYBIND11_DEPRECATED("Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
613
+ explicit operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value ||
614
+ std::is_same<T, accessor_policies::obj_attr>::value, bool>() const {
615
+ return hasattr(obj, key);
616
+ }
617
+ template <typename T = Policy>
618
+ PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
619
+ explicit operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const {
620
+ return obj.contains(key);
621
+ }
622
+
623
+ // NOLINTNEXTLINE(google-explicit-constructor)
624
+ operator object() const { return get_cache(); }
625
+ PyObject *ptr() const { return get_cache().ptr(); }
626
+ template <typename T> T cast() const { return get_cache().template cast<T>(); }
627
+
628
+ private:
629
+ object &get_cache() const {
630
+ if (!cache) { cache = Policy::get(obj, key); }
631
+ return cache;
632
+ }
633
+
634
+ private:
635
+ handle obj;
636
+ key_type key;
637
+ mutable object cache;
638
+ };
639
+ #if defined(_MSC_VER) && _MSC_VER < 1920
640
+ # pragma warning(pop)
641
+ #endif
642
+
643
+ PYBIND11_NAMESPACE_BEGIN(accessor_policies)
644
+ struct obj_attr {
645
+ using key_type = object;
646
+ static object get(handle obj, handle key) { return getattr(obj, key); }
647
+ static void set(handle obj, handle key, handle val) { setattr(obj, key, val); }
648
+ };
649
+
650
+ struct str_attr {
651
+ using key_type = const char *;
652
+ static object get(handle obj, const char *key) { return getattr(obj, key); }
653
+ static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); }
654
+ };
655
+
656
+ struct generic_item {
657
+ using key_type = object;
658
+
659
+ static object get(handle obj, handle key) {
660
+ PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr());
661
+ if (!result) { throw error_already_set(); }
662
+ return reinterpret_steal<object>(result);
663
+ }
664
+
665
+ static void set(handle obj, handle key, handle val) {
666
+ if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) { throw error_already_set(); }
667
+ }
668
+ };
669
+
670
+ struct sequence_item {
671
+ using key_type = size_t;
672
+
673
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
674
+ static object get(handle obj, const IdxType &index) {
675
+ PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index));
676
+ if (!result) { throw error_already_set(); }
677
+ return reinterpret_steal<object>(result);
678
+ }
679
+
680
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
681
+ static void set(handle obj, const IdxType &index, handle val) {
682
+ // PySequence_SetItem does not steal a reference to 'val'
683
+ if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) {
684
+ throw error_already_set();
685
+ }
686
+ }
687
+ };
688
+
689
+ struct list_item {
690
+ using key_type = size_t;
691
+
692
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
693
+ static object get(handle obj, const IdxType &index) {
694
+ PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index));
695
+ if (!result) { throw error_already_set(); }
696
+ return reinterpret_borrow<object>(result);
697
+ }
698
+
699
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
700
+ static void set(handle obj, const IdxType &index, handle val) {
701
+ // PyList_SetItem steals a reference to 'val'
702
+ if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
703
+ throw error_already_set();
704
+ }
705
+ }
706
+ };
707
+
708
+ struct tuple_item {
709
+ using key_type = size_t;
710
+
711
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
712
+ static object get(handle obj, const IdxType &index) {
713
+ PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index));
714
+ if (!result) { throw error_already_set(); }
715
+ return reinterpret_borrow<object>(result);
716
+ }
717
+
718
+ template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
719
+ static void set(handle obj, const IdxType &index, handle val) {
720
+ // PyTuple_SetItem steals a reference to 'val'
721
+ if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
722
+ throw error_already_set();
723
+ }
724
+ }
725
+ };
726
+ PYBIND11_NAMESPACE_END(accessor_policies)
727
+
728
+ /// STL iterator template used for tuple, list, sequence and dict
729
+ template <typename Policy>
730
+ class generic_iterator : public Policy {
731
+ using It = generic_iterator;
732
+
733
+ public:
734
+ using difference_type = ssize_t;
735
+ using iterator_category = typename Policy::iterator_category;
736
+ using value_type = typename Policy::value_type;
737
+ using reference = typename Policy::reference;
738
+ using pointer = typename Policy::pointer;
739
+
740
+ generic_iterator() = default;
741
+ generic_iterator(handle seq, ssize_t index) : Policy(seq, index) { }
742
+
743
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
744
+ reference operator*() const { return Policy::dereference(); }
745
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
746
+ reference operator[](difference_type n) const { return *(*this + n); }
747
+ pointer operator->() const { return **this; }
748
+
749
+ It &operator++() { Policy::increment(); return *this; }
750
+ It operator++(int) { auto copy = *this; Policy::increment(); return copy; }
751
+ It &operator--() { Policy::decrement(); return *this; }
752
+ It operator--(int) { auto copy = *this; Policy::decrement(); return copy; }
753
+ It &operator+=(difference_type n) { Policy::advance(n); return *this; }
754
+ It &operator-=(difference_type n) { Policy::advance(-n); return *this; }
755
+
756
+ friend It operator+(const It &a, difference_type n) { auto copy = a; return copy += n; }
757
+ friend It operator+(difference_type n, const It &b) { return b + n; }
758
+ friend It operator-(const It &a, difference_type n) { auto copy = a; return copy -= n; }
759
+ friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); }
760
+
761
+ friend bool operator==(const It &a, const It &b) { return a.equal(b); }
762
+ friend bool operator!=(const It &a, const It &b) { return !(a == b); }
763
+ friend bool operator< (const It &a, const It &b) { return b - a > 0; }
764
+ friend bool operator> (const It &a, const It &b) { return b < a; }
765
+ friend bool operator>=(const It &a, const It &b) { return !(a < b); }
766
+ friend bool operator<=(const It &a, const It &b) { return !(a > b); }
767
+ };
768
+
769
+ PYBIND11_NAMESPACE_BEGIN(iterator_policies)
770
+ /// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers
771
+ template <typename T>
772
+ struct arrow_proxy {
773
+ T value;
774
+
775
+ // NOLINTNEXTLINE(google-explicit-constructor)
776
+ arrow_proxy(T &&value) noexcept : value(std::move(value)) { }
777
+ T *operator->() const { return &value; }
778
+ };
779
+
780
+ /// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS``
781
+ class sequence_fast_readonly {
782
+ protected:
783
+ using iterator_category = std::random_access_iterator_tag;
784
+ using value_type = handle;
785
+ using reference = const handle; // PR #3263
786
+ using pointer = arrow_proxy<const handle>;
787
+
788
+ sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) { }
789
+
790
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
791
+ reference dereference() const { return *ptr; }
792
+ void increment() { ++ptr; }
793
+ void decrement() { --ptr; }
794
+ void advance(ssize_t n) { ptr += n; }
795
+ bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; }
796
+ ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; }
797
+
798
+ private:
799
+ PyObject **ptr;
800
+ };
801
+
802
+ /// Full read and write access using the sequence protocol: see ``detail::sequence_accessor``
803
+ class sequence_slow_readwrite {
804
+ protected:
805
+ using iterator_category = std::random_access_iterator_tag;
806
+ using value_type = object;
807
+ using reference = sequence_accessor;
808
+ using pointer = arrow_proxy<const sequence_accessor>;
809
+
810
+ sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) { }
811
+
812
+ reference dereference() const { return {obj, static_cast<size_t>(index)}; }
813
+ void increment() { ++index; }
814
+ void decrement() { --index; }
815
+ void advance(ssize_t n) { index += n; }
816
+ bool equal(const sequence_slow_readwrite &b) const { return index == b.index; }
817
+ ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; }
818
+
819
+ private:
820
+ handle obj;
821
+ ssize_t index;
822
+ };
823
+
824
+ /// Python's dictionary protocol permits this to be a forward iterator
825
+ class dict_readonly {
826
+ protected:
827
+ using iterator_category = std::forward_iterator_tag;
828
+ using value_type = std::pair<handle, handle>;
829
+ using reference = const value_type; // PR #3263
830
+ using pointer = arrow_proxy<const value_type>;
831
+
832
+ dict_readonly() = default;
833
+ dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }
834
+
835
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
836
+ reference dereference() const { return {key, value}; }
837
+ void increment() {
838
+ if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) {
839
+ pos = -1;
840
+ }
841
+ }
842
+ bool equal(const dict_readonly &b) const { return pos == b.pos; }
843
+
844
+ private:
845
+ handle obj;
846
+ PyObject *key = nullptr, *value = nullptr;
847
+ ssize_t pos = -1;
848
+ };
849
+ PYBIND11_NAMESPACE_END(iterator_policies)
850
+
851
+ #if !defined(PYPY_VERSION)
852
+ using tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
853
+ using list_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
854
+ #else
855
+ using tuple_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
856
+ using list_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
857
+ #endif
858
+
859
+ using sequence_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;
860
+ using dict_iterator = generic_iterator<iterator_policies::dict_readonly>;
861
+
862
+ inline bool PyIterable_Check(PyObject *obj) {
863
+ PyObject *iter = PyObject_GetIter(obj);
864
+ if (iter) {
865
+ Py_DECREF(iter);
866
+ return true;
867
+ }
868
+ PyErr_Clear();
869
+ return false;
870
+ }
871
+
872
+ inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
873
+ inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }
874
+
875
+ #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
876
+ inline bool PyUnicode_Check_Permissive(PyObject *o) { return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); }
877
+ #define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive
878
+ #else
879
+ #define PYBIND11_STR_CHECK_FUN PyUnicode_Check
880
+ #endif
881
+
882
+ inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; }
883
+
884
+ class kwargs_proxy : public handle {
885
+ public:
886
+ explicit kwargs_proxy(handle h) : handle(h) { }
887
+ };
888
+
889
+ class args_proxy : public handle {
890
+ public:
891
+ explicit args_proxy(handle h) : handle(h) { }
892
+ kwargs_proxy operator*() const { return kwargs_proxy(*this); }
893
+ };
894
+
895
+ /// Python argument categories (using PEP 448 terms)
896
+ template <typename T> using is_keyword = std::is_base_of<arg, T>;
897
+ template <typename T> using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking
898
+ template <typename T> using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking
899
+ template <typename T> using is_positional = satisfies_none_of<T,
900
+ is_keyword, is_s_unpacking, is_ds_unpacking
901
+ >;
902
+ template <typename T> using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>;
903
+
904
+ // Call argument collector forward declarations
905
+ template <return_value_policy policy = return_value_policy::automatic_reference>
906
+ class simple_collector;
907
+ template <return_value_policy policy = return_value_policy::automatic_reference>
908
+ class unpacking_collector;
909
+
910
+ PYBIND11_NAMESPACE_END(detail)
911
+
912
+ // TODO: After the deprecated constructors are removed, this macro can be simplified by
913
+ // inheriting ctors: `using Parent::Parent`. It's not an option right now because
914
+ // the `using` statement triggers the parent deprecation warning even if the ctor
915
+ // isn't even used.
916
+ #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
917
+ public: \
918
+ PYBIND11_DEPRECATED("Use reinterpret_borrow<"#Name">() or reinterpret_steal<"#Name">()") \
919
+ Name(handle h, bool is_borrowed) : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) { } \
920
+ Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) { } \
921
+ Name(handle h, stolen_t) : Parent(h, stolen_t{}) { } \
922
+ PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
923
+ bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \
924
+ static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \
925
+ template <typename Policy_> \
926
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
927
+ Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) { }
928
+
929
+ #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
930
+ PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
931
+ /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
932
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
933
+ Name(const object &o) \
934
+ : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) \
935
+ { if (!m_ptr) throw error_already_set(); } \
936
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
937
+ Name(object &&o) \
938
+ : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) \
939
+ { if (!m_ptr) throw error_already_set(); }
940
+
941
+ #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \
942
+ PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
943
+ Name() : Parent() { }
944
+
945
+ #define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \
946
+ ::pybind11::type_error("Object of type '" + \
947
+ ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) + \
948
+ "' is not an instance of '" #Name "'")
949
+
950
+ #define PYBIND11_OBJECT(Name, Parent, CheckFun) \
951
+ PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
952
+ /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
953
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
954
+ Name(const object &o) : Parent(o) \
955
+ { if (m_ptr && !check_(m_ptr)) throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); } \
956
+ /* NOLINTNEXTLINE(google-explicit-constructor) */ \
957
+ Name(object &&o) : Parent(std::move(o)) \
958
+ { if (m_ptr && !check_(m_ptr)) throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); }
959
+
960
+ #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
961
+ PYBIND11_OBJECT(Name, Parent, CheckFun) \
962
+ Name() : Parent() { }
963
+
964
+ /// \addtogroup pytypes
965
+ /// @{
966
+
967
+ /** \rst
968
+ Wraps a Python iterator so that it can also be used as a C++ input iterator
969
+
970
+ Caveat: copying an iterator does not (and cannot) clone the internal
971
+ state of the Python iterable. This also applies to the post-increment
972
+ operator. This iterator should only be used to retrieve the current
973
+ value using ``operator*()``.
974
+ \endrst */
975
+ class iterator : public object {
976
+ public:
977
+ using iterator_category = std::input_iterator_tag;
978
+ using difference_type = ssize_t;
979
+ using value_type = handle;
980
+ using reference = const handle; // PR #3263
981
+ using pointer = const handle *;
982
+
983
+ PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)
984
+
985
+ iterator& operator++() {
986
+ advance();
987
+ return *this;
988
+ }
989
+
990
+ iterator operator++(int) {
991
+ auto rv = *this;
992
+ advance();
993
+ return rv;
994
+ }
995
+
996
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
997
+ reference operator*() const {
998
+ if (m_ptr && !value.ptr()) {
999
+ auto& self = const_cast<iterator &>(*this);
1000
+ self.advance();
1001
+ }
1002
+ return value;
1003
+ }
1004
+
1005
+ pointer operator->() const { operator*(); return &value; }
1006
+
1007
+ /** \rst
1008
+ The value which marks the end of the iteration. ``it == iterator::sentinel()``
1009
+ is equivalent to catching ``StopIteration`` in Python.
1010
+
1011
+ .. code-block:: cpp
1012
+
1013
+ void foo(py::iterator it) {
1014
+ while (it != py::iterator::sentinel()) {
1015
+ // use `*it`
1016
+ ++it;
1017
+ }
1018
+ }
1019
+ \endrst */
1020
+ static iterator sentinel() { return {}; }
1021
+
1022
+ friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); }
1023
+ friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); }
1024
+
1025
+ private:
1026
+ void advance() {
1027
+ value = reinterpret_steal<object>(PyIter_Next(m_ptr));
1028
+ if (PyErr_Occurred()) { throw error_already_set(); }
1029
+ }
1030
+
1031
+ private:
1032
+ object value = {};
1033
+ };
1034
+
1035
+
1036
+
1037
+ class type : public object {
1038
+ public:
1039
+ PYBIND11_OBJECT(type, object, PyType_Check)
1040
+
1041
+ /// Return a type handle from a handle or an object
1042
+ static handle handle_of(handle h) { return handle((PyObject*) Py_TYPE(h.ptr())); }
1043
+
1044
+ /// Return a type object from a handle or an object
1045
+ static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); }
1046
+
1047
+ // Defined in pybind11/cast.h
1048
+ /// Convert C++ type to handle if previously registered. Does not convert
1049
+ /// standard types, like int, float. etc. yet.
1050
+ /// See https://github.com/pybind/pybind11/issues/2486
1051
+ template<typename T>
1052
+ static handle handle_of();
1053
+
1054
+ /// Convert C++ type to type if previously registered. Does not convert
1055
+ /// standard types, like int, float. etc. yet.
1056
+ /// See https://github.com/pybind/pybind11/issues/2486
1057
+ template<typename T>
1058
+ static type of() {return type(type::handle_of<T>(), borrowed_t{}); }
1059
+ };
1060
+
1061
+ class iterable : public object {
1062
+ public:
1063
+ PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check)
1064
+ };
1065
+
1066
+ class bytes;
1067
+
1068
+ class str : public object {
1069
+ public:
1070
+ PYBIND11_OBJECT_CVT(str, object, PYBIND11_STR_CHECK_FUN, raw_str)
1071
+
1072
+ template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1073
+ str(const char *c, const SzType &n)
1074
+ : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1075
+ if (!m_ptr) pybind11_fail("Could not allocate string object!");
1076
+ }
1077
+
1078
+ // 'explicit' is explicitly omitted from the following constructors to allow implicit conversion to py::str from C++ string-like objects
1079
+ // NOLINTNEXTLINE(google-explicit-constructor)
1080
+ str(const char *c = "")
1081
+ : object(PyUnicode_FromString(c), stolen_t{}) {
1082
+ if (!m_ptr) pybind11_fail("Could not allocate string object!");
1083
+ }
1084
+
1085
+ // NOLINTNEXTLINE(google-explicit-constructor)
1086
+ str(const std::string &s) : str(s.data(), s.size()) { }
1087
+
1088
+ explicit str(const bytes &b);
1089
+
1090
+ /** \rst
1091
+ Return a string representation of the object. This is analogous to
1092
+ the ``str()`` function in Python.
1093
+ \endrst */
1094
+ explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { if (!m_ptr) throw error_already_set(); }
1095
+
1096
+ // NOLINTNEXTLINE(google-explicit-constructor)
1097
+ operator std::string() const {
1098
+ object temp = *this;
1099
+ if (PyUnicode_Check(m_ptr)) {
1100
+ temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
1101
+ if (!temp)
1102
+ throw error_already_set();
1103
+ }
1104
+ char *buffer = nullptr;
1105
+ ssize_t length = 0;
1106
+ if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length))
1107
+ pybind11_fail("Unable to extract string contents! (invalid type)");
1108
+ return std::string(buffer, (size_t) length);
1109
+ }
1110
+
1111
+ template <typename... Args>
1112
+ str format(Args &&...args) const {
1113
+ return attr("format")(std::forward<Args>(args)...);
1114
+ }
1115
+
1116
+ private:
1117
+ /// Return string representation -- always returns a new reference, even if already a str
1118
+ static PyObject *raw_str(PyObject *op) {
1119
+ PyObject *str_value = PyObject_Str(op);
1120
+ #if PY_MAJOR_VERSION < 3
1121
+ if (!str_value) throw error_already_set();
1122
+ PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
1123
+ Py_XDECREF(str_value); str_value = unicode;
1124
+ #endif
1125
+ return str_value;
1126
+ }
1127
+ };
1128
+ /// @} pytypes
1129
+
1130
+ inline namespace literals {
1131
+ /** \rst
1132
+ String literal version of `str`
1133
+ \endrst */
1134
+ inline str operator"" _s(const char *s, size_t size) { return {s, size}; }
1135
+ } // namespace literals
1136
+
1137
+ /// \addtogroup pytypes
1138
+ /// @{
1139
+ class bytes : public object {
1140
+ public:
1141
+ PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK)
1142
+
1143
+ // Allow implicit conversion:
1144
+ // NOLINTNEXTLINE(google-explicit-constructor)
1145
+ bytes(const char *c = "")
1146
+ : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) {
1147
+ if (!m_ptr) pybind11_fail("Could not allocate bytes object!");
1148
+ }
1149
+
1150
+ template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1151
+ bytes(const char *c, const SzType &n)
1152
+ : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, ssize_t_cast(n)), stolen_t{}) {
1153
+ if (!m_ptr) pybind11_fail("Could not allocate bytes object!");
1154
+ }
1155
+
1156
+ // Allow implicit conversion:
1157
+ // NOLINTNEXTLINE(google-explicit-constructor)
1158
+ bytes(const std::string &s) : bytes(s.data(), s.size()) { }
1159
+
1160
+ explicit bytes(const pybind11::str &s);
1161
+
1162
+ // NOLINTNEXTLINE(google-explicit-constructor)
1163
+ operator std::string() const {
1164
+ char *buffer = nullptr;
1165
+ ssize_t length = 0;
1166
+ if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length))
1167
+ pybind11_fail("Unable to extract bytes contents!");
1168
+ return std::string(buffer, (size_t) length);
1169
+ }
1170
+ };
1171
+ // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1172
+ // are included in the doxygen group; close here and reopen after as a workaround
1173
+ /// @} pytypes
1174
+
1175
+ inline bytes::bytes(const pybind11::str &s) {
1176
+ object temp = s;
1177
+ if (PyUnicode_Check(s.ptr())) {
1178
+ temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));
1179
+ if (!temp)
1180
+ pybind11_fail("Unable to extract string contents! (encoding issue)");
1181
+ }
1182
+ char *buffer = nullptr;
1183
+ ssize_t length = 0;
1184
+ if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length))
1185
+ pybind11_fail("Unable to extract string contents! (invalid type)");
1186
+ auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));
1187
+ if (!obj)
1188
+ pybind11_fail("Could not allocate bytes object!");
1189
+ m_ptr = obj.release().ptr();
1190
+ }
1191
+
1192
+ inline str::str(const bytes& b) {
1193
+ char *buffer = nullptr;
1194
+ ssize_t length = 0;
1195
+ if (PYBIND11_BYTES_AS_STRING_AND_SIZE(b.ptr(), &buffer, &length))
1196
+ pybind11_fail("Unable to extract bytes contents!");
1197
+ auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, length));
1198
+ if (!obj)
1199
+ pybind11_fail("Could not allocate string object!");
1200
+ m_ptr = obj.release().ptr();
1201
+ }
1202
+
1203
+ /// \addtogroup pytypes
1204
+ /// @{
1205
+ class bytearray : public object {
1206
+ public:
1207
+ PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject)
1208
+
1209
+ template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1210
+ bytearray(const char *c, const SzType &n)
1211
+ : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
1212
+ if (!m_ptr) pybind11_fail("Could not allocate bytearray object!");
1213
+ }
1214
+
1215
+ bytearray()
1216
+ : bytearray("", 0) {}
1217
+
1218
+ explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) { }
1219
+
1220
+ size_t size() const { return static_cast<size_t>(PyByteArray_Size(m_ptr)); }
1221
+
1222
+ explicit operator std::string() const {
1223
+ char *buffer = PyByteArray_AS_STRING(m_ptr);
1224
+ ssize_t size = PyByteArray_GET_SIZE(m_ptr);
1225
+ return std::string(buffer, static_cast<size_t>(size));
1226
+ }
1227
+ };
1228
+ // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
1229
+ // are included in the doxygen group; close here and reopen after as a workaround
1230
+ /// @} pytypes
1231
+
1232
+ /// \addtogroup pytypes
1233
+ /// @{
1234
+ class none : public object {
1235
+ public:
1236
+ PYBIND11_OBJECT(none, object, detail::PyNone_Check)
1237
+ none() : object(Py_None, borrowed_t{}) { }
1238
+ };
1239
+
1240
+ class ellipsis : public object {
1241
+ public:
1242
+ PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check)
1243
+ ellipsis() : object(Py_Ellipsis, borrowed_t{}) { }
1244
+ };
1245
+
1246
+ class bool_ : public object {
1247
+ public:
1248
+ PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool)
1249
+ bool_() : object(Py_False, borrowed_t{}) { }
1250
+ // Allow implicit conversion from and to `bool`:
1251
+ // NOLINTNEXTLINE(google-explicit-constructor)
1252
+ bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) { }
1253
+ // NOLINTNEXTLINE(google-explicit-constructor)
1254
+ operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; }
1255
+
1256
+ private:
1257
+ /// Return the truth value of an object -- always returns a new reference
1258
+ static PyObject *raw_bool(PyObject *op) {
1259
+ const auto value = PyObject_IsTrue(op);
1260
+ if (value == -1) return nullptr;
1261
+ return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr();
1262
+ }
1263
+ };
1264
+
1265
+ PYBIND11_NAMESPACE_BEGIN(detail)
1266
+ // Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1;
1267
+ // otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned).
1268
+ // (The distinction is critically important when casting a returned -1 error value to some other
1269
+ // unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes).
1270
+ template <typename Unsigned>
1271
+ Unsigned as_unsigned(PyObject *o) {
1272
+ if (PYBIND11_SILENCE_MSVC_C4127(sizeof(Unsigned) <= sizeof(unsigned long))
1273
+ #if PY_VERSION_HEX < 0x03000000
1274
+ || PyInt_Check(o)
1275
+ #endif
1276
+ ) {
1277
+ unsigned long v = PyLong_AsUnsignedLong(o);
1278
+ return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1279
+ }
1280
+ unsigned long long v = PyLong_AsUnsignedLongLong(o);
1281
+ return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
1282
+ }
1283
+ PYBIND11_NAMESPACE_END(detail)
1284
+
1285
+ class int_ : public object {
1286
+ public:
1287
+ PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long)
1288
+ int_() : object(PyLong_FromLong(0), stolen_t{}) { }
1289
+ // Allow implicit conversion from C++ integral types:
1290
+ template <typename T,
1291
+ detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1292
+ // NOLINTNEXTLINE(google-explicit-constructor)
1293
+ int_(T value) {
1294
+ if (PYBIND11_SILENCE_MSVC_C4127(sizeof(T) <= sizeof(long))) {
1295
+ if (std::is_signed<T>::value)
1296
+ m_ptr = PyLong_FromLong((long) value);
1297
+ else
1298
+ m_ptr = PyLong_FromUnsignedLong((unsigned long) value);
1299
+ } else {
1300
+ if (std::is_signed<T>::value)
1301
+ m_ptr = PyLong_FromLongLong((long long) value);
1302
+ else
1303
+ m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value);
1304
+ }
1305
+ if (!m_ptr) pybind11_fail("Could not allocate int object!");
1306
+ }
1307
+
1308
+ template <typename T,
1309
+ detail::enable_if_t<std::is_integral<T>::value, int> = 0>
1310
+ // NOLINTNEXTLINE(google-explicit-constructor)
1311
+ operator T() const {
1312
+ return std::is_unsigned<T>::value
1313
+ ? detail::as_unsigned<T>(m_ptr)
1314
+ : sizeof(T) <= sizeof(long)
1315
+ ? (T) PyLong_AsLong(m_ptr)
1316
+ : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
1317
+ }
1318
+ };
1319
+
1320
+ class float_ : public object {
1321
+ public:
1322
+ PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)
1323
+ // Allow implicit conversion from float/double:
1324
+ // NOLINTNEXTLINE(google-explicit-constructor)
1325
+ float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1326
+ if (!m_ptr) pybind11_fail("Could not allocate float object!");
1327
+ }
1328
+ // NOLINTNEXTLINE(google-explicit-constructor)
1329
+ float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
1330
+ if (!m_ptr) pybind11_fail("Could not allocate float object!");
1331
+ }
1332
+ // NOLINTNEXTLINE(google-explicit-constructor)
1333
+ operator float() const { return (float) PyFloat_AsDouble(m_ptr); }
1334
+ // NOLINTNEXTLINE(google-explicit-constructor)
1335
+ operator double() const { return (double) PyFloat_AsDouble(m_ptr); }
1336
+ };
1337
+
1338
+ class weakref : public object {
1339
+ public:
1340
+ PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref)
1341
+ explicit weakref(handle obj, handle callback = {})
1342
+ : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) {
1343
+ if (!m_ptr) pybind11_fail("Could not allocate weak reference!");
1344
+ }
1345
+
1346
+ private:
1347
+ static PyObject *raw_weakref(PyObject *o) {
1348
+ return PyWeakref_NewRef(o, nullptr);
1349
+ }
1350
+ };
1351
+
1352
+ class slice : public object {
1353
+ public:
1354
+ PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check)
1355
+ slice(handle start, handle stop, handle step) {
1356
+ m_ptr = PySlice_New(start.ptr(), stop.ptr(), step.ptr());
1357
+ if (!m_ptr)
1358
+ pybind11_fail("Could not allocate slice object!");
1359
+ }
1360
+
1361
+ #ifdef PYBIND11_HAS_OPTIONAL
1362
+ slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t> step)
1363
+ : slice(index_to_object(start), index_to_object(stop), index_to_object(step)) {}
1364
+ #else
1365
+ slice(ssize_t start_, ssize_t stop_, ssize_t step_)
1366
+ : slice(int_(start_), int_(stop_), int_(step_)) {}
1367
+ #endif
1368
+
1369
+ bool compute(size_t length, size_t *start, size_t *stop, size_t *step,
1370
+ size_t *slicelength) const {
1371
+ return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1372
+ (ssize_t) length, (ssize_t *) start,
1373
+ (ssize_t *) stop, (ssize_t *) step,
1374
+ (ssize_t *) slicelength) == 0;
1375
+ }
1376
+ bool compute(ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step,
1377
+ ssize_t *slicelength) const {
1378
+ return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
1379
+ length, start,
1380
+ stop, step,
1381
+ slicelength) == 0;
1382
+ }
1383
+
1384
+ private:
1385
+ template <typename T>
1386
+ static object index_to_object(T index) {
1387
+ return index ? object(int_(*index)) : object(none());
1388
+ }
1389
+ };
1390
+
1391
+ class capsule : public object {
1392
+ public:
1393
+ PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact)
1394
+ PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()")
1395
+ capsule(PyObject *ptr, bool is_borrowed) : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) { }
1396
+
1397
+ explicit capsule(const void *value, const char *name = nullptr, void (*destructor)(PyObject *) = nullptr)
1398
+ : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) {
1399
+ if (!m_ptr)
1400
+ pybind11_fail("Could not allocate capsule object!");
1401
+ }
1402
+
1403
+ PYBIND11_DEPRECATED("Please pass a destructor that takes a void pointer as input")
1404
+ capsule(const void *value, void (*destruct)(PyObject *))
1405
+ : object(PyCapsule_New(const_cast<void*>(value), nullptr, destruct), stolen_t{}) {
1406
+ if (!m_ptr)
1407
+ pybind11_fail("Could not allocate capsule object!");
1408
+ }
1409
+
1410
+ capsule(const void *value, void (*destructor)(void *)) {
1411
+ m_ptr = PyCapsule_New(const_cast<void *>(value), nullptr, [](PyObject *o) {
1412
+ auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o));
1413
+ void *ptr = PyCapsule_GetPointer(o, nullptr);
1414
+ destructor(ptr);
1415
+ });
1416
+
1417
+ if (!m_ptr)
1418
+ pybind11_fail("Could not allocate capsule object!");
1419
+
1420
+ if (PyCapsule_SetContext(m_ptr, (void *) destructor) != 0)
1421
+ pybind11_fail("Could not set capsule context!");
1422
+ }
1423
+
1424
+ explicit capsule(void (*destructor)()) {
1425
+ m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) {
1426
+ auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, nullptr));
1427
+ destructor();
1428
+ });
1429
+
1430
+ if (!m_ptr)
1431
+ pybind11_fail("Could not allocate capsule object!");
1432
+ }
1433
+
1434
+ // NOLINTNEXTLINE(google-explicit-constructor)
1435
+ template <typename T> operator T *() const {
1436
+ return get_pointer<T>();
1437
+ }
1438
+
1439
+ /// Get the pointer the capsule holds.
1440
+ template<typename T = void>
1441
+ T* get_pointer() const {
1442
+ auto name = this->name();
1443
+ T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));
1444
+ if (!result) {
1445
+ PyErr_Clear();
1446
+ pybind11_fail("Unable to extract capsule contents!");
1447
+ }
1448
+ return result;
1449
+ }
1450
+
1451
+ /// Replaces a capsule's pointer *without* calling the destructor on the existing one.
1452
+ void set_pointer(const void *value) {
1453
+ if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0) {
1454
+ PyErr_Clear();
1455
+ pybind11_fail("Could not set capsule pointer");
1456
+ }
1457
+ }
1458
+
1459
+ const char *name() const { return PyCapsule_GetName(m_ptr); }
1460
+ };
1461
+
1462
+ class tuple : public object {
1463
+ public:
1464
+ PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple)
1465
+ template <typename SzType = ssize_t,
1466
+ detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1467
+ // Some compilers generate link errors when using `const SzType &` here:
1468
+ explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) {
1469
+ if (!m_ptr) pybind11_fail("Could not allocate tuple object!");
1470
+ }
1471
+ size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
1472
+ bool empty() const { return size() == 0; }
1473
+ detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }
1474
+ detail::item_accessor operator[](handle h) const { return object::operator[](h); }
1475
+ detail::tuple_iterator begin() const { return {*this, 0}; }
1476
+ detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }
1477
+ };
1478
+
1479
+ // We need to put this into a separate function because the Intel compiler
1480
+ // fails to compile enable_if_t<all_of<is_keyword_or_ds<Args>...>::value> part below
1481
+ // (tested with ICC 2021.1 Beta 20200827).
1482
+ template <typename... Args>
1483
+ constexpr bool args_are_all_keyword_or_ds()
1484
+ {
1485
+ return detail::all_of<detail::is_keyword_or_ds<Args>...>::value;
1486
+ }
1487
+
1488
+ class dict : public object {
1489
+ public:
1490
+ PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)
1491
+ dict() : object(PyDict_New(), stolen_t{}) {
1492
+ if (!m_ptr) pybind11_fail("Could not allocate dict object!");
1493
+ }
1494
+ template <typename... Args,
1495
+ typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>,
1496
+ // MSVC workaround: it can't compile an out-of-line definition, so defer the collector
1497
+ typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
1498
+ explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) { }
1499
+
1500
+ size_t size() const { return (size_t) PyDict_Size(m_ptr); }
1501
+ bool empty() const { return size() == 0; }
1502
+ detail::dict_iterator begin() const { return {*this, 0}; }
1503
+ detail::dict_iterator end() const { return {}; }
1504
+ void clear() /* py-non-const */ { PyDict_Clear(ptr()); }
1505
+ template <typename T> bool contains(T &&key) const {
1506
+ return PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr()) == 1;
1507
+ }
1508
+
1509
+ private:
1510
+ /// Call the `dict` Python type -- always returns a new reference
1511
+ static PyObject *raw_dict(PyObject *op) {
1512
+ if (PyDict_Check(op))
1513
+ return handle(op).inc_ref().ptr();
1514
+ return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
1515
+ }
1516
+ };
1517
+
1518
+ class sequence : public object {
1519
+ public:
1520
+ PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)
1521
+ size_t size() const {
1522
+ ssize_t result = PySequence_Size(m_ptr);
1523
+ if (result == -1)
1524
+ throw error_already_set();
1525
+ return (size_t) result;
1526
+ }
1527
+ bool empty() const { return size() == 0; }
1528
+ detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
1529
+ detail::item_accessor operator[](handle h) const { return object::operator[](h); }
1530
+ detail::sequence_iterator begin() const { return {*this, 0}; }
1531
+ detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; }
1532
+ };
1533
+
1534
+ class list : public object {
1535
+ public:
1536
+ PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
1537
+ template <typename SzType = ssize_t,
1538
+ detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
1539
+ // Some compilers generate link errors when using `const SzType &` here:
1540
+ explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) {
1541
+ if (!m_ptr) pybind11_fail("Could not allocate list object!");
1542
+ }
1543
+ size_t size() const { return (size_t) PyList_Size(m_ptr); }
1544
+ bool empty() const { return size() == 0; }
1545
+ detail::list_accessor operator[](size_t index) const { return {*this, index}; }
1546
+ detail::item_accessor operator[](handle h) const { return object::operator[](h); }
1547
+ detail::list_iterator begin() const { return {*this, 0}; }
1548
+ detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
1549
+ template <typename T> void append(T &&val) /* py-non-const */ {
1550
+ PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
1551
+ }
1552
+ template <typename IdxType,
1553
+ typename ValType,
1554
+ detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
1555
+ void insert(const IdxType &index, ValType &&val) /* py-non-const */ {
1556
+ PyList_Insert(
1557
+ m_ptr, ssize_t_cast(index), detail::object_or_cast(std::forward<ValType>(val)).ptr());
1558
+ }
1559
+ };
1560
+
1561
+ class args : public tuple { PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) };
1562
+ class kwargs : public dict { PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check) };
1563
+
1564
+ class set : public object {
1565
+ public:
1566
+ PYBIND11_OBJECT_CVT(set, object, PySet_Check, PySet_New)
1567
+ set() : object(PySet_New(nullptr), stolen_t{}) {
1568
+ if (!m_ptr) pybind11_fail("Could not allocate set object!");
1569
+ }
1570
+ size_t size() const { return (size_t) PySet_Size(m_ptr); }
1571
+ bool empty() const { return size() == 0; }
1572
+ template <typename T> bool add(T &&val) /* py-non-const */ {
1573
+ return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
1574
+ }
1575
+ void clear() /* py-non-const */ { PySet_Clear(m_ptr); }
1576
+ template <typename T> bool contains(T &&val) const {
1577
+ return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1;
1578
+ }
1579
+ };
1580
+
1581
+ class function : public object {
1582
+ public:
1583
+ PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)
1584
+ handle cpp_function() const {
1585
+ handle fun = detail::get_function(m_ptr);
1586
+ if (fun && PyCFunction_Check(fun.ptr()))
1587
+ return fun;
1588
+ return handle();
1589
+ }
1590
+ bool is_cpp_function() const { return (bool) cpp_function(); }
1591
+ };
1592
+
1593
+ class staticmethod : public object {
1594
+ public:
1595
+ PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)
1596
+ };
1597
+
1598
+ class buffer : public object {
1599
+ public:
1600
+ PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)
1601
+
1602
+ buffer_info request(bool writable = false) const {
1603
+ int flags = PyBUF_STRIDES | PyBUF_FORMAT;
1604
+ if (writable) flags |= PyBUF_WRITABLE;
1605
+ auto *view = new Py_buffer();
1606
+ if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
1607
+ delete view;
1608
+ throw error_already_set();
1609
+ }
1610
+ return buffer_info(view);
1611
+ }
1612
+ };
1613
+
1614
+ class memoryview : public object {
1615
+ public:
1616
+ PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
1617
+
1618
+ /** \rst
1619
+ Creates ``memoryview`` from ``buffer_info``.
1620
+
1621
+ ``buffer_info`` must be created from ``buffer::request()``. Otherwise
1622
+ throws an exception.
1623
+
1624
+ For creating a ``memoryview`` from objects that support buffer protocol,
1625
+ use ``memoryview(const object& obj)`` instead of this constructor.
1626
+ \endrst */
1627
+ explicit memoryview(const buffer_info& info) {
1628
+ if (!info.view())
1629
+ pybind11_fail("Prohibited to create memoryview without Py_buffer");
1630
+ // Note: PyMemoryView_FromBuffer never increments obj reference.
1631
+ m_ptr = (info.view()->obj) ?
1632
+ PyMemoryView_FromObject(info.view()->obj) :
1633
+ PyMemoryView_FromBuffer(info.view());
1634
+ if (!m_ptr)
1635
+ pybind11_fail("Unable to create memoryview from buffer descriptor");
1636
+ }
1637
+
1638
+ /** \rst
1639
+ Creates ``memoryview`` from static buffer.
1640
+
1641
+ This method is meant for providing a ``memoryview`` for C/C++ buffer not
1642
+ managed by Python. The caller is responsible for managing the lifetime
1643
+ of ``ptr`` and ``format``, which MUST outlive the memoryview constructed
1644
+ here.
1645
+
1646
+ See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
1647
+
1648
+ .. _PyMemoryView_FromBuffer: https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer
1649
+
1650
+ :param ptr: Pointer to the buffer.
1651
+ :param itemsize: Byte size of an element.
1652
+ :param format: Pointer to the null-terminated format string. For
1653
+ homogeneous Buffers, this should be set to
1654
+ ``format_descriptor<T>::value``.
1655
+ :param shape: Shape of the tensor (1 entry per dimension).
1656
+ :param strides: Number of bytes between adjacent entries (for each
1657
+ per dimension).
1658
+ :param readonly: Flag to indicate if the underlying storage may be
1659
+ written to.
1660
+ \endrst */
1661
+ static memoryview from_buffer(
1662
+ void *ptr, ssize_t itemsize, const char *format,
1663
+ detail::any_container<ssize_t> shape,
1664
+ detail::any_container<ssize_t> strides, bool readonly = false);
1665
+
1666
+ static memoryview from_buffer(
1667
+ const void *ptr, ssize_t itemsize, const char *format,
1668
+ detail::any_container<ssize_t> shape,
1669
+ detail::any_container<ssize_t> strides) {
1670
+ return memoryview::from_buffer(
1671
+ const_cast<void *>(ptr), itemsize, format, std::move(shape), std::move(strides), true);
1672
+ }
1673
+
1674
+ template<typename T>
1675
+ static memoryview from_buffer(
1676
+ T *ptr, detail::any_container<ssize_t> shape,
1677
+ detail::any_container<ssize_t> strides, bool readonly = false) {
1678
+ return memoryview::from_buffer(
1679
+ reinterpret_cast<void*>(ptr), sizeof(T),
1680
+ format_descriptor<T>::value, shape, strides, readonly);
1681
+ }
1682
+
1683
+ template<typename T>
1684
+ static memoryview from_buffer(
1685
+ const T *ptr, detail::any_container<ssize_t> shape,
1686
+ detail::any_container<ssize_t> strides) {
1687
+ return memoryview::from_buffer(
1688
+ const_cast<T*>(ptr), shape, strides, true);
1689
+ }
1690
+
1691
+ #if PY_MAJOR_VERSION >= 3
1692
+ /** \rst
1693
+ Creates ``memoryview`` from static memory.
1694
+
1695
+ This method is meant for providing a ``memoryview`` for C/C++ buffer not
1696
+ managed by Python. The caller is responsible for managing the lifetime
1697
+ of ``mem``, which MUST outlive the memoryview constructed here.
1698
+
1699
+ This method is not available in Python 2.
1700
+
1701
+ See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
1702
+
1703
+ .. _PyMemoryView_FromMemory: https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory
1704
+ \endrst */
1705
+ static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) {
1706
+ PyObject* ptr = PyMemoryView_FromMemory(
1707
+ reinterpret_cast<char*>(mem), size,
1708
+ (readonly) ? PyBUF_READ : PyBUF_WRITE);
1709
+ if (!ptr)
1710
+ pybind11_fail("Could not allocate memoryview object!");
1711
+ return memoryview(object(ptr, stolen_t{}));
1712
+ }
1713
+
1714
+ static memoryview from_memory(const void *mem, ssize_t size) {
1715
+ return memoryview::from_memory(const_cast<void*>(mem), size, true);
1716
+ }
1717
+ #endif
1718
+ };
1719
+
1720
+ #ifndef DOXYGEN_SHOULD_SKIP_THIS
1721
+ inline memoryview memoryview::from_buffer(
1722
+ void *ptr, ssize_t itemsize, const char* format,
1723
+ detail::any_container<ssize_t> shape,
1724
+ detail::any_container<ssize_t> strides, bool readonly) {
1725
+ size_t ndim = shape->size();
1726
+ if (ndim != strides->size())
1727
+ pybind11_fail("memoryview: shape length doesn't match strides length");
1728
+ ssize_t size = ndim != 0u ? 1 : 0;
1729
+ for (size_t i = 0; i < ndim; ++i)
1730
+ size *= (*shape)[i];
1731
+ Py_buffer view;
1732
+ view.buf = ptr;
1733
+ view.obj = nullptr;
1734
+ view.len = size * itemsize;
1735
+ view.readonly = static_cast<int>(readonly);
1736
+ view.itemsize = itemsize;
1737
+ view.format = const_cast<char*>(format);
1738
+ view.ndim = static_cast<int>(ndim);
1739
+ view.shape = shape->data();
1740
+ view.strides = strides->data();
1741
+ view.suboffsets = nullptr;
1742
+ view.internal = nullptr;
1743
+ PyObject* obj = PyMemoryView_FromBuffer(&view);
1744
+ if (!obj)
1745
+ throw error_already_set();
1746
+ return memoryview(object(obj, stolen_t{}));
1747
+ }
1748
+ #endif // DOXYGEN_SHOULD_SKIP_THIS
1749
+ /// @} pytypes
1750
+
1751
+ /// \addtogroup python_builtins
1752
+ /// @{
1753
+
1754
+ /// Get the length of a Python object.
1755
+ inline size_t len(handle h) {
1756
+ ssize_t result = PyObject_Length(h.ptr());
1757
+ if (result < 0)
1758
+ throw error_already_set();
1759
+ return (size_t) result;
1760
+ }
1761
+
1762
+ /// Get the length hint of a Python object.
1763
+ /// Returns 0 when this cannot be determined.
1764
+ inline size_t len_hint(handle h) {
1765
+ #if PY_VERSION_HEX >= 0x03040000
1766
+ ssize_t result = PyObject_LengthHint(h.ptr(), 0);
1767
+ #else
1768
+ ssize_t result = PyObject_Length(h.ptr());
1769
+ #endif
1770
+ if (result < 0) {
1771
+ // Sometimes a length can't be determined at all (eg generators)
1772
+ // In which case simply return 0
1773
+ PyErr_Clear();
1774
+ return 0;
1775
+ }
1776
+ return (size_t) result;
1777
+ }
1778
+
1779
+ inline str repr(handle h) {
1780
+ PyObject *str_value = PyObject_Repr(h.ptr());
1781
+ if (!str_value) throw error_already_set();
1782
+ #if PY_MAJOR_VERSION < 3
1783
+ PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
1784
+ Py_XDECREF(str_value); str_value = unicode;
1785
+ if (!str_value) throw error_already_set();
1786
+ #endif
1787
+ return reinterpret_steal<str>(str_value);
1788
+ }
1789
+
1790
+ inline iterator iter(handle obj) {
1791
+ PyObject *result = PyObject_GetIter(obj.ptr());
1792
+ if (!result) { throw error_already_set(); }
1793
+ return reinterpret_steal<iterator>(result);
1794
+ }
1795
+ /// @} python_builtins
1796
+
1797
+ PYBIND11_NAMESPACE_BEGIN(detail)
1798
+ template <typename D> iterator object_api<D>::begin() const { return iter(derived()); }
1799
+ template <typename D> iterator object_api<D>::end() const { return iterator::sentinel(); }
1800
+ template <typename D> item_accessor object_api<D>::operator[](handle key) const {
1801
+ return {derived(), reinterpret_borrow<object>(key)};
1802
+ }
1803
+ template <typename D> item_accessor object_api<D>::operator[](const char *key) const {
1804
+ return {derived(), pybind11::str(key)};
1805
+ }
1806
+ template <typename D> obj_attr_accessor object_api<D>::attr(handle key) const {
1807
+ return {derived(), reinterpret_borrow<object>(key)};
1808
+ }
1809
+ template <typename D> str_attr_accessor object_api<D>::attr(const char *key) const {
1810
+ return {derived(), key};
1811
+ }
1812
+ template <typename D> args_proxy object_api<D>::operator*() const {
1813
+ return args_proxy(derived().ptr());
1814
+ }
1815
+ template <typename D> template <typename T> bool object_api<D>::contains(T &&item) const {
1816
+ return attr("__contains__")(std::forward<T>(item)).template cast<bool>();
1817
+ }
1818
+
1819
+ template <typename D>
1820
+ pybind11::str object_api<D>::str() const { return pybind11::str(derived()); }
1821
+
1822
+ template <typename D>
1823
+ str_attr_accessor object_api<D>::doc() const { return attr("__doc__"); }
1824
+
1825
+ template <typename D>
1826
+ handle object_api<D>::get_type() const { return type::handle_of(derived()); }
1827
+
1828
+ template <typename D>
1829
+ bool object_api<D>::rich_compare(object_api const &other, int value) const {
1830
+ int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
1831
+ if (rv == -1)
1832
+ throw error_already_set();
1833
+ return rv == 1;
1834
+ }
1835
+
1836
+ #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
1837
+ template <typename D> object object_api<D>::op() const { \
1838
+ object result = reinterpret_steal<object>(fn(derived().ptr())); \
1839
+ if (!result.ptr()) \
1840
+ throw error_already_set(); \
1841
+ return result; \
1842
+ }
1843
+
1844
+ #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
1845
+ template <typename D> \
1846
+ object object_api<D>::op(object_api const &other) const { \
1847
+ object result = reinterpret_steal<object>( \
1848
+ fn(derived().ptr(), other.derived().ptr())); \
1849
+ if (!result.ptr()) \
1850
+ throw error_already_set(); \
1851
+ return result; \
1852
+ }
1853
+
1854
+ PYBIND11_MATH_OPERATOR_UNARY (operator~, PyNumber_Invert)
1855
+ PYBIND11_MATH_OPERATOR_UNARY (operator-, PyNumber_Negative)
1856
+ PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)
1857
+ PYBIND11_MATH_OPERATOR_BINARY(operator+=, PyNumber_InPlaceAdd)
1858
+ PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)
1859
+ PYBIND11_MATH_OPERATOR_BINARY(operator-=, PyNumber_InPlaceSubtract)
1860
+ PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)
1861
+ PYBIND11_MATH_OPERATOR_BINARY(operator*=, PyNumber_InPlaceMultiply)
1862
+ PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)
1863
+ PYBIND11_MATH_OPERATOR_BINARY(operator/=, PyNumber_InPlaceTrueDivide)
1864
+ PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)
1865
+ PYBIND11_MATH_OPERATOR_BINARY(operator|=, PyNumber_InPlaceOr)
1866
+ PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)
1867
+ PYBIND11_MATH_OPERATOR_BINARY(operator&=, PyNumber_InPlaceAnd)
1868
+ PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)
1869
+ PYBIND11_MATH_OPERATOR_BINARY(operator^=, PyNumber_InPlaceXor)
1870
+ PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)
1871
+ PYBIND11_MATH_OPERATOR_BINARY(operator<<=, PyNumber_InPlaceLshift)
1872
+ PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)
1873
+ PYBIND11_MATH_OPERATOR_BINARY(operator>>=, PyNumber_InPlaceRshift)
1874
+
1875
+ #undef PYBIND11_MATH_OPERATOR_UNARY
1876
+ #undef PYBIND11_MATH_OPERATOR_BINARY
1877
+
1878
+ PYBIND11_NAMESPACE_END(detail)
1879
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)