mxk1998 commited on
Commit
0b255cc
·
verified ·
1 Parent(s): 6064732

Publish sealed evaluation sources, batch 23

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/ISSUE_TEMPLATE/config.yml +8 -0
  2. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/dependabot.yml +15 -0
  3. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/labeler.yml +13 -0
  4. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/labeler_merged.yml +8 -0
  5. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/matchers/pylint.json +32 -0
  6. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/pull_request_template.md +15 -0
  7. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/ci.yml +1207 -0
  8. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/configure.yml +85 -0
  9. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/docs-link.yml +41 -0
  10. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/format.yml +54 -0
  11. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/labeler.yml +25 -0
  12. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/nightlies.yml +59 -0
  13. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/pip.yml +118 -0
  14. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/reusable-standard.yml +97 -0
  15. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/tests-cibw.yml +87 -0
  16. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/upstream.yml +116 -0
  17. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.gitignore +54 -0
  18. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.pre-commit-config.yaml +149 -0
  19. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.readthedocs.yml +20 -0
  20. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/CMakeLists.txt +425 -0
  21. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/CMakePresets.json +93 -0
  22. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/LICENSE +29 -0
  23. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/README.rst +216 -0
  24. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/SECURITY.md +13 -0
  25. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/Doxyfile +21 -0
  26. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/Makefile +192 -0
  27. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/_static/css/custom.css +3 -0
  28. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/chrono.rst +81 -0
  29. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/custom.rst +137 -0
  30. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/eigen.rst +310 -0
  31. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/functional.rst +109 -0
  32. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/index.rst +43 -0
  33. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/overview.rst +170 -0
  34. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/stl.rst +249 -0
  35. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/strings.rst +296 -0
  36. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/classes.rst +1413 -0
  37. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/deadlock.md +391 -0
  38. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/deprecated.rst +179 -0
  39. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/embedding.rst +495 -0
  40. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/exceptions.rst +422 -0
  41. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/functions.rst +616 -0
  42. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/misc.rst +615 -0
  43. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/pycpp/index.rst +13 -0
  44. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/pycpp/numpy.rst +493 -0
  45. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/pycpp/object.rst +286 -0
  46. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/pycpp/utilities.rst +155 -0
  47. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/smart_ptrs.rst +179 -0
  48. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/basics.rst +316 -0
  49. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/benchmark.py +89 -0
  50. third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/benchmark.rst +95 -0
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/ISSUE_TEMPLATE/config.yml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ blank_issues_enabled: false
2
+ contact_links:
3
+ - name: Ask a question
4
+ url: https://github.com/pybind/pybind11/discussions/new
5
+ about: Please ask and answer questions here, or propose new ideas.
6
+ - name: Gitter room
7
+ url: https://gitter.im/pybind/Lobby
8
+ about: A room for discussing pybind11 with an active community
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/dependabot.yml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+ updates:
3
+ # Maintain dependencies for GitHub Actions
4
+ - package-ecosystem: "github-actions"
5
+ directory: "/"
6
+ schedule:
7
+ interval: "weekly"
8
+ groups:
9
+ actions:
10
+ patterns:
11
+ - "*"
12
+ ignore:
13
+ - dependency-name: actions/checkout
14
+ versions:
15
+ - "<5"
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/labeler.yml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ docs:
2
+ all:
3
+ - changed-files:
4
+ - all-globs-to-all-files:
5
+ - '!docs/changelog.md'
6
+ - '!docs/upgrade.rst'
7
+ - base-branch: "^(?!dependabot).*"
8
+ - base-branch: "^(?!pre-commit-ci).*"
9
+
10
+ ci:
11
+ - changed-files:
12
+ - any-glob-to-any-file:
13
+ - '.github/workflows/*.yml'
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/labeler_merged.yml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Add 'needs changelog` label to any change to code files as long as the `CHANGELOG` hasn't changed
2
+ # Skip dependabot and pre-commit-ci PRs
3
+ needs changelog:
4
+ - all:
5
+ - changed-files:
6
+ - all-globs-to-all-files: "!docs/changelog.md"
7
+ - base-branch: "^(?!dependabot).*"
8
+ - base-branch: "^(?!pre-commit-ci).*"
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/matchers/pylint.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "problemMatcher": [
3
+ {
4
+ "severity": "warning",
5
+ "pattern": [
6
+ {
7
+ "regexp": "^([^:]+):(\\d+):(\\d+): ([A-DF-Z]\\d+): \\033\\[[\\d;]+m([^\\033]+).*$",
8
+ "file": 1,
9
+ "line": 2,
10
+ "column": 3,
11
+ "code": 4,
12
+ "message": 5
13
+ }
14
+ ],
15
+ "owner": "pylint-warning"
16
+ },
17
+ {
18
+ "severity": "error",
19
+ "pattern": [
20
+ {
21
+ "regexp": "^([^:]+):(\\d+):(\\d+): (E\\d+): \\033\\[[\\d;]+m([^\\033]+).*$",
22
+ "file": 1,
23
+ "line": 2,
24
+ "column": 3,
25
+ "code": 4,
26
+ "message": 5
27
+ }
28
+ ],
29
+ "owner": "pylint-error"
30
+ }
31
+ ]
32
+ }
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/pull_request_template.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--
2
+ Title (above): please place [branch_name] at the beginning if you are targeting a branch other than master. *Do not target stable*.
3
+ It is recommended to use conventional commit format, see conventionalcommits.org, but not required.
4
+ -->
5
+ ## Description
6
+
7
+ <!-- Include relevant issues or PRs here, describe what changed and why -->
8
+
9
+
10
+ ## Suggested changelog entry:
11
+
12
+ <!-- Fill in the block below with the expected entry. Delete if no entry needed;
13
+ but do not delete the header if an entry is needed! Will be collected via a script. -->
14
+
15
+ * Placeholder.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/ci.yml ADDED
@@ -0,0 +1,1207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ pull_request:
6
+ types:
7
+ - opened
8
+ - synchronize
9
+ - reopened
10
+ - ready_for_review
11
+
12
+ permissions: read-all
13
+
14
+ concurrency:
15
+ group: test-${{ github.ref }}
16
+ cancel-in-progress: true
17
+
18
+ env:
19
+ PYTHONDEVMODE: 1
20
+ PIP_BREAK_SYSTEM_PACKAGES: 1
21
+ PIP_ONLY_BINARY: numpy
22
+ FORCE_COLOR: 3
23
+ PYTEST_TIMEOUT: 300
24
+ # For cmake:
25
+ VERBOSE: 1
26
+ CMAKE_COLOR_DIAGNOSTICS: 1
27
+
28
+ jobs:
29
+ # This is the "main" test suite, which tests a large number of different
30
+ # versions of default compilers and Python versions in GitHub Actions.
31
+ # It is in two parts: one that always runs, and one that runs on non-draft
32
+ standard-small:
33
+ if: github.event.action != 'ready_for_review'
34
+ strategy:
35
+ fail-fast: false
36
+ matrix:
37
+ include:
38
+ - runs-on: ubuntu-22.04
39
+ python-version: '3.8'
40
+ cmake-args: -DPYBIND11_FINDPYTHON=OFF -DPYBIND11_NUMPY_1_ONLY=ON
41
+ - runs-on: ubuntu-latest
42
+ python-version: '3.13'
43
+ cmake-args: -DCMAKE_CXX_STANDARD=23 -DPYBIND11_SIMPLE_GIL_MANAGEMENT=ON
44
+ - runs-on: ubuntu-latest
45
+ python-version: '3.14t'
46
+ cmake-args: -DCMAKE_CXX_STANDARD=17 -DPYBIND11_TEST_SMART_HOLDER=ON
47
+ - runs-on: ubuntu-latest
48
+ python-version: 'pypy3.11'
49
+ cmake-args: -DCMAKE_CXX_STANDARD=17
50
+ - runs-on: ubuntu-latest
51
+ python-version: 'graalpy-24.2'
52
+ cmake-args: -DCMAKE_CXX_STANDARD=20
53
+ - runs-on: macos-latest
54
+ python-version: '3.14'
55
+ cmake-args: -DCMAKE_CXX_STANDARD=14
56
+ - runs-on: windows-2022
57
+ python-version: '3.8'
58
+ cmake-args: -DPYBIND11_FINDPYTHON=OFF
59
+
60
+
61
+ name: 🐍
62
+ uses: ./.github/workflows/reusable-standard.yml
63
+ with:
64
+ runs-on: ${{ matrix.runs-on }}
65
+ python-version: ${{ matrix.python-version }}
66
+ cmake-args: ${{ matrix.cmake-args }}
67
+
68
+ standard-large:
69
+ if: github.event.pull_request.draft == false
70
+ strategy:
71
+ fail-fast: false
72
+ matrix:
73
+ include:
74
+ - runs-on: ubuntu-latest
75
+ python-version: '3.8'
76
+ cmake-args: -DPYBIND11_FINDPYTHON=ON -DCMAKE_CXX_STANDARD=17
77
+ - runs-on: ubuntu-latest
78
+ python-version: '3.10'
79
+ cmake-args: -DCMAKE_CXX_STANDARD=20
80
+ - runs-on: ubuntu-latest
81
+ python-version: '3.11'
82
+ cmake-args: -DPYBIND11_TEST_SMART_HOLDER=ON -DCMAKE_CXX_STANDARD=17
83
+ - runs-on: ubuntu-latest
84
+ python-version: '3.12'
85
+ cmake-args: -DPYBIND11_TEST_SMART_HOLDER=ON -DPYBIND11_SIMPLE_GIL_MANAGEMENT=ON
86
+ - runs-on: ubuntu-latest
87
+ python-version: '3.13t'
88
+ cmake-args: -DCMAKE_CXX_STANDARD=20 -DPYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION=ON
89
+ - runs-on: ubuntu-latest
90
+ python-version: '3.14'
91
+ cmake-args: -DCMAKE_CXX_STANDARD=14 -DCMAKE_CXX_FLAGS="-DPYBIND11_HAS_SUBINTERPRETER_SUPPORT=0"
92
+ - runs-on: ubuntu-latest
93
+ python-version: 'pypy-3.10'
94
+ cmake-args: -DCMAKE_CXX_STANDARD=14
95
+ - runs-on: ubuntu-latest
96
+ python-version: 'graalpy-24.1'
97
+
98
+ # No SciPy for macOS ARM
99
+ - runs-on: macos-13
100
+ python-version: '3.8'
101
+ cmake-args: -DCMAKE_CXX_STANDARD=14
102
+ - runs-on: macos-13
103
+ python-version: '3.11'
104
+ cmake-args: -DPYBIND11_TEST_SMART_HOLDER=ON
105
+ - runs-on: macos-latest
106
+ python-version: '3.12'
107
+ cmake-args: -DCMAKE_CXX_STANDARD=17 -DPYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION=ON
108
+ - runs-on: macos-13
109
+ python-version: '3.13t'
110
+ cmake-args: -DCMAKE_CXX_STANDARD=11
111
+ - runs-on: macos-latest
112
+ python-version: '3.14t'
113
+ cmake-args: -DCMAKE_CXX_STANDARD=20
114
+ - runs-on: macos-13
115
+ python-version: 'pypy-3.10'
116
+ cmake-args: -DCMAKE_CXX_STANDARD=17
117
+ - runs-on: macos-latest
118
+ python-version: 'pypy-3.11'
119
+ - runs-on: macos-latest
120
+ python-version: 'graalpy-24.2'
121
+
122
+ - runs-on: windows-latest
123
+ python-version: '3.9'
124
+ cmake-args: -DPYBIND11_TEST_SMART_HOLDER=ON
125
+ - runs-on: windows-2022
126
+ python-version: '3.8'
127
+ cmake-args: -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded -DPYBIND11_NUMPY_1_ONLY=ON
128
+ - runs-on: windows-2022
129
+ python-version: '3.9'
130
+ cmake-args: -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDLL -DCMAKE_CXX_STANDARD=14
131
+ # This needs a python built with MTd
132
+ # - runs-on: windows-2022
133
+ # python-version: '3.11'
134
+ # cmake-args: -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDebug
135
+ - runs-on: windows-2022
136
+ python-version: '3.10'
137
+ cmake-args: -DPYBIND11_TEST_SMART_HOLDER=ON -DCMAKE_CXX_FLAGS="/GR /EHsc"
138
+ - runs-on: windows-2022
139
+ python-version: '3.13'
140
+ cmake-args: -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDebugDLL
141
+ - runs-on: windows-latest
142
+ python-version: '3.13t'
143
+ cmake-args: -DCMAKE_CXX_STANDARD=17
144
+ - runs-on: windows-latest
145
+ python-version: '3.14'
146
+ cmake-args: -DCMAKE_CXX_STANDARD=20
147
+ - runs-on: windows-latest
148
+ python-version: '3.14t'
149
+ cmake-args: -DCMAKE_CXX_STANDARD=23
150
+ - runs-on: windows-latest
151
+ python-version: 'pypy-3.10'
152
+ cmake-args: -DCMAKE_CXX_STANDARD=17
153
+ - runs-on: windows-latest
154
+ python-version: 'pypy3.11'
155
+ cmake-args: -DCMAKE_CXX_STANDARD=20
156
+ # The setup-python action currently doesn't have graalpy for windows
157
+ # See https://github.com/actions/setup-python/pull/880
158
+
159
+ name: 🐍
160
+ uses: ./.github/workflows/reusable-standard.yml
161
+ with:
162
+ runs-on: ${{ matrix.runs-on }}
163
+ python-version: ${{ matrix.python-version }}
164
+ cmake-args: ${{ matrix.cmake-args }}
165
+
166
+ # This checks inplace builds with C++11
167
+ inplace:
168
+ if: github.event.pull_request.draft == false
169
+ strategy:
170
+ fail-fast: false
171
+ matrix:
172
+ include:
173
+ - runs-on: ubuntu-latest
174
+ python-version: '3.9'
175
+ - runs-on: macos-latest
176
+ python-version: '3.12'
177
+ - runs-on: windows-latest
178
+ python-version: '3.11'
179
+
180
+ name: "🐍 ${{ matrix.python-version }} • ${{ matrix.runs-on }} • x64 inplace C++14"
181
+ runs-on: ${{ matrix.runs-on }}
182
+ timeout-minutes: 90
183
+
184
+ steps:
185
+ - uses: actions/checkout@v5
186
+
187
+ - name: Setup Python ${{ matrix.python-version }}
188
+ uses: actions/setup-python@v6
189
+ with:
190
+ python-version: ${{ matrix.python-version }}
191
+ allow-prereleases: true
192
+
193
+ - name: Install uv
194
+ uses: astral-sh/setup-uv@v6
195
+ with:
196
+ enable-cache: true
197
+
198
+ - name: Prepare env
199
+ run: uv pip install --python=python --system -r tests/requirements.txt
200
+
201
+ # TODO Resolve Windows Ninja shared object issue on Python 3.8+
202
+ - name: Use Ninja except on Windows
203
+ if: runner.os != 'Windows'
204
+ run: echo "CMAKE_GENERATOR=Ninja" >> "$GITHUB_ENV"
205
+
206
+ # More-or-less randomly adding a few extra flags here.
207
+ # In particular, use this one to test the next ABI bump (internals version).
208
+ - name: Configure
209
+ run: >
210
+ cmake -S. -B.
211
+ -DPYBIND11_WERROR=ON
212
+ -DPYBIND11_SIMPLE_GIL_MANAGEMENT=ON
213
+ -DPYBIND11_PYTEST_ARGS=-v
214
+ -DDOWNLOAD_CATCH=ON
215
+ -DDOWNLOAD_EIGEN=ON
216
+ -DCMAKE_CXX_STANDARD=14
217
+ -DPYBIND11_INTERNALS_VERSION=10000000
218
+
219
+ # Checks to makes sure defining `_` is allowed
220
+ # Triggers EHsc missing error on Windows
221
+ - name: Add underscore check
222
+ if: runner.os != 'Windows'
223
+ run: cmake -S. -B. -DCMAKE_CXX_FLAGS="-D_=1"
224
+
225
+ - name: Build
226
+ run: cmake --build .
227
+
228
+ - name: Python tests
229
+ run: cmake --build . --target pytest
230
+
231
+ - name: Compiled tests
232
+ run: cmake --build . --target cpptest
233
+
234
+ - name: Interface test
235
+ run: cmake --build . --target test_cmake_build
236
+
237
+ - name: Visibility test
238
+ run: cmake --build . --target test_cross_module_rtti
239
+
240
+
241
+ manylinux:
242
+ name: Manylinux on 🐍 3.13t • GIL
243
+ if: github.event.pull_request.draft == false
244
+ runs-on: ubuntu-latest
245
+ timeout-minutes: 40
246
+ container: quay.io/pypa/musllinux_1_2_x86_64:latest
247
+ steps:
248
+ - uses: actions/checkout@v5
249
+ with:
250
+ fetch-depth: 0
251
+
252
+ - name: Prepare uv's path
253
+ run: echo "$HOME/.local/bin" >> $GITHUB_PATH
254
+
255
+ - name: Install ninja
256
+ run: uv tool install ninja
257
+
258
+ - name: Configure via preset
259
+ run: cmake --preset venv -DPYBIND11_CREATE_WITH_UV=python3.13t
260
+
261
+ - name: Build C++11
262
+ run: cmake --build --preset venv
263
+
264
+ - name: Python tests C++11
265
+ run: cmake --build --preset testsvenv -t pytest
266
+
267
+ deadsnakes:
268
+ if: github.event.pull_request.draft == false
269
+ strategy:
270
+ fail-fast: false
271
+ matrix:
272
+ include:
273
+ # TODO: Fails on 3.10, investigate
274
+ # JOB DISABLED (NEEDS WORK): https://github.com/pybind/pybind11/issues/4889
275
+ # - python-version: "3.9"
276
+ # python-debug: true
277
+ # valgrind: true
278
+ - python-version: "3.11"
279
+ python-debug: false
280
+
281
+ name: "🐍 ${{ matrix.python-version }}${{ matrix.python-debug && '-dbg' || '' }} (deadsnakes)${{ matrix.valgrind && ' • Valgrind' || '' }} • x64"
282
+ runs-on: ubuntu-latest
283
+ timeout-minutes: 90
284
+
285
+ steps:
286
+ - uses: actions/checkout@v5
287
+
288
+ - name: Setup Python ${{ matrix.python-version }} (deadsnakes)
289
+ uses: deadsnakes/action@v3.2.0
290
+ with:
291
+ python-version: ${{ matrix.python-version }}
292
+ debug: ${{ matrix.python-debug }}
293
+
294
+ - name: Update CMake
295
+ uses: jwlawson/actions-setup-cmake@v2.0
296
+
297
+ - name: Valgrind cache
298
+ if: matrix.valgrind
299
+ uses: actions/cache@v4
300
+ id: cache-valgrind
301
+ with:
302
+ path: valgrind
303
+ key: 3.16.1 # Valgrind version
304
+
305
+ - name: Compile Valgrind
306
+ if: matrix.valgrind && steps.cache-valgrind.outputs.cache-hit != 'true'
307
+ run: |
308
+ VALGRIND_VERSION=3.16.1
309
+ curl https://sourceware.org/pub/valgrind/valgrind-$VALGRIND_VERSION.tar.bz2 -o - | tar xj
310
+ mv valgrind-$VALGRIND_VERSION valgrind
311
+ cd valgrind
312
+ ./configure
313
+ make -j 2 > /dev/null
314
+
315
+ - name: Install Valgrind
316
+ if: matrix.valgrind
317
+ working-directory: valgrind
318
+ run: |
319
+ sudo make install
320
+ sudo apt-get update
321
+ sudo apt-get install ninja-build libc6-dbg
322
+
323
+ - name: Prepare env
324
+ run: |
325
+ python -m pip install -r tests/requirements.txt
326
+
327
+ - name: Configure
328
+ run: cmake --preset default -DCMAKE_CXX_STANDARD=17
329
+
330
+ - name: Build
331
+ run: cmake --build --preset default
332
+
333
+ - name: Python tests
334
+ run: cmake --build --preset default --target pytest
335
+
336
+ - name: C++ tests
337
+ run: cmake --build --preset default --target cpptest
338
+
339
+ - name: Visibility test
340
+ run: cmake --build --preset default --target test_cross_module_rtti
341
+
342
+ - name: Run Valgrind on Python tests
343
+ if: matrix.valgrind
344
+ run: cmake --build --preset default --target memcheck
345
+
346
+
347
+ # Testing on clang using the excellent silkeh clang docker images
348
+ clang:
349
+ if: github.event.pull_request.draft == false
350
+ runs-on: ubuntu-latest
351
+ strategy:
352
+ fail-fast: false
353
+ matrix:
354
+ include:
355
+ - clang: 5
356
+ std: 14
357
+ - clang: 11
358
+ std: 20
359
+ - clang: 14
360
+ std: 20
361
+ - clang: 16
362
+ std: 20
363
+ container_suffix: "-bullseye"
364
+ - clang: 18
365
+ std: 20
366
+ cxx_flags: "-Werror -Wall -Wextra -Wwrite-strings -Wunreachable-code -Wpointer-arith -Wredundant-decls"
367
+ container_suffix: "-bookworm"
368
+
369
+ name: "🐍 3 • Clang ${{ matrix.clang }} • C++${{ matrix.std }} • x64${{ matrix.cxx_flags && ' • cxx_flags' || '' }}"
370
+ container: "silkeh/clang:${{ matrix.clang }}${{ matrix.container_suffix }}"
371
+ timeout-minutes: 90
372
+
373
+ steps:
374
+ - uses: actions/checkout@v5
375
+
376
+ - name: Add wget and python3
377
+ run: apt-get update && apt-get install -y python3-dev python3-numpy python3-pytest libeigen3-dev
378
+
379
+ - name: Configure
380
+ shell: bash
381
+ run: >
382
+ cmake -S . -B build
383
+ -DPYBIND11_WERROR=ON
384
+ -DDOWNLOAD_CATCH=ON
385
+ -DCMAKE_CXX_STANDARD=${{ matrix.std }}
386
+ -DCMAKE_CXX_FLAGS="${{ matrix.cxx_flags }}"
387
+ -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)")
388
+
389
+ - name: Build
390
+ run: cmake --build build -j 2
391
+
392
+ - name: Python tests
393
+ run: cmake --build build --target pytest
394
+
395
+ - name: C++ tests
396
+ run: cmake --build build --target cpptest
397
+
398
+ - name: Interface test
399
+ run: cmake --build build --target test_cmake_build
400
+
401
+ - name: Visibility test
402
+ run: cmake --build build --target test_cross_module_rtti
403
+
404
+ # Testing NVCC; forces sources to behave like .cu files
405
+ cuda:
406
+ runs-on: ubuntu-latest
407
+ name: "🐍 3.10 • CUDA 12.2 • Ubuntu 22.04"
408
+ container: nvidia/cuda:12.2.0-devel-ubuntu22.04
409
+ timeout-minutes: 90
410
+
411
+ steps:
412
+ - uses: actions/checkout@v5
413
+
414
+ # tzdata will try to ask for the timezone, so set the DEBIAN_FRONTEND
415
+ - name: Install 🐍 3
416
+ run: apt-get update && DEBIAN_FRONTEND="noninteractive" apt-get install -y cmake git python3-dev python3-pytest python3-numpy
417
+
418
+ - name: Configure
419
+ run: cmake -S . -B build -DPYBIND11_CUDA_TESTS=ON -DPYBIND11_WERROR=ON -DDOWNLOAD_CATCH=ON
420
+
421
+ - name: Build
422
+ run: cmake --build build -j2 --verbose
423
+
424
+ - name: Python tests
425
+ run: cmake --build build --target pytest
426
+
427
+
428
+ # TODO: Internal compiler error - report to NVidia
429
+ # # Testing CentOS 8 + PGI compilers
430
+ # centos-nvhpc8:
431
+ # runs-on: ubuntu-latest
432
+ # name: "🐍 3 • CentOS8 / PGI 20.11 • x64"
433
+ # container: centos:8
434
+ #
435
+ # steps:
436
+ # - uses: actions/checkout@v5
437
+ #
438
+ # - name: Add Python 3 and a few requirements
439
+ # run: yum update -y && yum install -y git python3-devel python3-numpy python3-pytest make environment-modules
440
+ #
441
+ # - name: Install CMake with pip
442
+ # run: |
443
+ # python3 -m pip install --upgrade pip
444
+ # python3 -m pip install cmake --prefer-binary
445
+ #
446
+ # - name: Install NVidia HPC SDK
447
+ # run: >
448
+ # yum -y install
449
+ # https://developer.download.nvidia.com/hpc-sdk/20.11/nvhpc-20-11-20.11-1.x86_64.rpm
450
+ # https://developer.download.nvidia.com/hpc-sdk/20.11/nvhpc-2020-20.11-1.x86_64.rpm
451
+ #
452
+ # - name: Configure
453
+ # shell: bash
454
+ # run: |
455
+ # source /etc/profile.d/modules.sh
456
+ # module load /opt/nvidia/hpc_sdk/modulefiles/nvhpc/20.11
457
+ # cmake -S . -B build -DDOWNLOAD_CATCH=ON -DCMAKE_CXX_STANDARD=14 -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)")
458
+ #
459
+ # - name: Build
460
+ # run: cmake --build build -j 2 --verbose
461
+ #
462
+ # - name: Python tests
463
+ # run: cmake --build build --target pytest
464
+ #
465
+ # - name: C++ tests
466
+ # run: cmake --build build --target cpptest
467
+ #
468
+ # - name: Interface test
469
+ # run: cmake --build build --target test_cmake_build
470
+
471
+
472
+ # Testing on Ubuntu + NVHPC (previous PGI) compilers, which seems to require more workarounds
473
+ ubuntu-nvhpc7:
474
+ if: github.event.pull_request.draft == false
475
+ runs-on: ubuntu-22.04
476
+ name: "🐍 3 • NVHPC 23.5 • C++17 • x64"
477
+ timeout-minutes: 90
478
+
479
+ env:
480
+ # tzdata will try to ask for the timezone, so set the DEBIAN_FRONTEND
481
+ DEBIAN_FRONTEND: 'noninteractive'
482
+ steps:
483
+ - uses: actions/checkout@v5
484
+
485
+ - name: Add NVHPC Repo
486
+ run: |
487
+ echo 'deb [trusted=yes] https://developer.download.nvidia.com/hpc-sdk/ubuntu/amd64 /' | \
488
+ sudo tee /etc/apt/sources.list.d/nvhpc.list
489
+
490
+ - name: Install 🐍 3 & NVHPC
491
+ run: |
492
+ sudo apt-get update -y && \
493
+ sudo apt-get install -y cmake environment-modules git python3-dev python3-pip python3-numpy && \
494
+ sudo apt-get install -y --no-install-recommends nvhpc-23-5 && \
495
+ sudo rm -rf /var/lib/apt/lists/*
496
+ python3 -m pip install --upgrade pip
497
+ python3 -m pip install --upgrade pytest
498
+
499
+ # On some systems, you many need further workarounds:
500
+ # https://github.com/pybind/pybind11/pull/2475
501
+ - name: Configure
502
+ shell: bash
503
+ run: |
504
+ source /etc/profile.d/modules.sh
505
+ module load /opt/nvidia/hpc_sdk/modulefiles/nvhpc/23.5
506
+ cmake -S . -B build -DDOWNLOAD_CATCH=ON \
507
+ -DCMAKE_CXX_STANDARD=17 \
508
+ -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)") \
509
+ -DCMAKE_CXX_FLAGS="-Wc,--pending_instantiations=0" \
510
+ -DPYBIND11_TEST_FILTER="test_smart_ptr.cpp"
511
+
512
+ - name: Build
513
+ run: cmake --build build -j 2 --verbose
514
+
515
+ - name: Python tests
516
+ run: cmake --build build --target pytest
517
+
518
+ - name: C++ tests
519
+ run: cmake --build build --target cpptest
520
+
521
+ - name: Interface test
522
+ run: cmake --build build --target test_cmake_build
523
+
524
+ - name: Visibility test
525
+ run: cmake --build build --target test_cross_module_rtti
526
+
527
+ # Testing on GCC using the GCC docker images (only recent images supported)
528
+ gcc:
529
+ if: github.event.pull_request.draft == false
530
+ runs-on: ubuntu-latest
531
+ strategy:
532
+ fail-fast: false
533
+ matrix:
534
+ include:
535
+ - { gcc: 9, std: 20 }
536
+ - { gcc: 10, std: 17 }
537
+ - { gcc: 10, std: 20 }
538
+ - { gcc: 13, std: 20, cxx_flags: "-Wall -Wextra -Wwrite-strings -Wunreachable-code -Wpointer-arith -Wredundant-decls" }
539
+
540
+ name: "🐍 3 • GCC ${{ matrix.gcc }} • C++${{ matrix.std }} • x64${{ matrix.cxx_flags && ' • cxx_flags' || '' }}"
541
+ container: "gcc:${{ matrix.gcc }}"
542
+ timeout-minutes: 90
543
+
544
+ steps:
545
+ - uses: actions/checkout@v5
546
+
547
+ - name: Add Python 3
548
+ run: apt-get update; apt-get install -y python3-dev python3-numpy python3-pytest python3-pip libeigen3-dev
549
+
550
+ - name: Update pip
551
+ run: python3 -m pip install --upgrade pip
552
+
553
+ - name: Update CMake
554
+ uses: jwlawson/actions-setup-cmake@v2.0
555
+
556
+ - name: Configure
557
+ shell: bash
558
+ run: >
559
+ cmake -S . -B build
560
+ -DPYBIND11_WERROR=ON
561
+ -DDOWNLOAD_CATCH=ON
562
+ -DCMAKE_CXX_STANDARD=${{ matrix.std }}
563
+ -DCMAKE_CXX_FLAGS="${{ matrix.cxx_flags }}"
564
+ -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)")
565
+
566
+ - name: Build
567
+ run: cmake --build build -j 2
568
+
569
+ - name: Python tests
570
+ run: cmake --build build --target pytest
571
+
572
+ - name: C++ tests
573
+ run: cmake --build build --target cpptest
574
+
575
+ - name: Interface test
576
+ run: cmake --build build --target test_cmake_build
577
+
578
+ - name: Visibility test
579
+ run: cmake --build build --target test_cross_module_rtti
580
+
581
+ - name: Configure - Exercise cmake -DPYBIND11_TEST_OVERRIDE
582
+ if: matrix.gcc == '12'
583
+ shell: bash
584
+ run: >
585
+ cmake -S . -B build_partial
586
+ -DPYBIND11_WERROR=ON
587
+ -DDOWNLOAD_CATCH=ON
588
+ -DCMAKE_CXX_STANDARD=${{ matrix.std }}
589
+ -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)")
590
+ "-DPYBIND11_TEST_OVERRIDE=test_call_policies.cpp;test_gil_scoped.cpp;test_thread.cpp"
591
+
592
+ - name: Build - Exercise cmake -DPYBIND11_TEST_OVERRIDE
593
+ if: matrix.gcc == '12'
594
+ run: cmake --build build_partial -j 2
595
+
596
+ - name: Python tests - Exercise cmake -DPYBIND11_TEST_OVERRIDE
597
+ if: matrix.gcc == '12'
598
+ run: cmake --build build_partial --target pytest
599
+
600
+ # Testing on ICC using the oneAPI apt repo
601
+ icc:
602
+ if: github.event.pull_request.draft == false
603
+ runs-on: ubuntu-22.04
604
+ timeout-minutes: 90
605
+
606
+ name: "🐍 3 • ICC latest • x64"
607
+
608
+ steps:
609
+ - uses: actions/checkout@v5
610
+
611
+ - name: Add apt repo
612
+ run: |
613
+ sudo apt-get update
614
+ sudo apt-get install -y wget build-essential pkg-config cmake ca-certificates gnupg
615
+ wget https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB
616
+ sudo apt-key add GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB
617
+ echo "deb https://apt.repos.intel.com/oneapi all main" | sudo tee /etc/apt/sources.list.d/oneAPI.list
618
+
619
+ - name: Add ICC & Python 3
620
+ run: sudo apt-get update; sudo apt-get install -y intel-oneapi-compiler-dpcpp-cpp-and-cpp-classic cmake python3-dev python3-numpy python3-pytest python3-pip
621
+
622
+ - name: Update pip
623
+ run: |
624
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
625
+ python3 -m pip install --upgrade pip
626
+
627
+ - name: Install dependencies
628
+ run: |
629
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
630
+ python3 -m pip install -r tests/requirements.txt
631
+
632
+ - name: Configure C++11
633
+ run: |
634
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
635
+ cmake -S . -B build-11 \
636
+ -DPYBIND11_WERROR=ON \
637
+ -DDOWNLOAD_CATCH=ON \
638
+ -DDOWNLOAD_EIGEN=OFF \
639
+ -DCMAKE_CXX_STANDARD=11 \
640
+ -DCMAKE_CXX_COMPILER=$(which icpc) \
641
+ -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)")
642
+
643
+ - name: Build C++11
644
+ run: |
645
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
646
+ cmake --build build-11 -j 2 -v
647
+
648
+ - name: Python tests C++11
649
+ run: |
650
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
651
+ sudo service apport stop
652
+ cmake --build build-11 --target check
653
+
654
+ - name: C++ tests C++11
655
+ run: |
656
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
657
+ cmake --build build-11 --target cpptest
658
+
659
+ - name: Interface test C++11
660
+ run: |
661
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
662
+ cmake --build build-11 --target test_cmake_build
663
+
664
+ - name: Visibility test
665
+ run: |
666
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
667
+ cmake --build build-11 --target test_cross_module_rtti
668
+
669
+ - name: Configure C++17
670
+ run: |
671
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
672
+ cmake -S . -B build-17 \
673
+ -DPYBIND11_WERROR=ON \
674
+ -DDOWNLOAD_CATCH=ON \
675
+ -DDOWNLOAD_EIGEN=OFF \
676
+ -DCMAKE_CXX_STANDARD=17 \
677
+ -DCMAKE_CXX_COMPILER=$(which icpc) \
678
+ -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)")
679
+
680
+ - name: Build C++17
681
+ run: |
682
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
683
+ cmake --build build-17 -j 2 -v
684
+
685
+ - name: Python tests C++17
686
+ run: |
687
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
688
+ sudo service apport stop
689
+ cmake --build build-17 --target check
690
+
691
+ - name: C++ tests C++17
692
+ run: |
693
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
694
+ cmake --build build-17 --target cpptest
695
+
696
+ - name: Interface test C++17
697
+ run: |
698
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
699
+ cmake --build build-17 --target test_cmake_build
700
+
701
+ - name: Visibility test
702
+ run: |
703
+ set +e; source /opt/intel/oneapi/setvars.sh; set -e
704
+ cmake --build build-17 --target test_cross_module_rtti
705
+
706
+ # Testing on CentOS (manylinux uses a centos base).
707
+ centos:
708
+ if: github.event.pull_request.draft == false
709
+ runs-on: ubuntu-latest
710
+ strategy:
711
+ fail-fast: false
712
+ matrix:
713
+ container:
714
+ - "almalinux:8"
715
+ - "almalinux:9"
716
+
717
+ name: "🐍 3 • ${{ matrix.container }} • x64"
718
+ container: "${{ matrix.container }}"
719
+ timeout-minutes: 90
720
+
721
+ steps:
722
+ - name: Latest actions/checkout
723
+ uses: actions/checkout@v5
724
+
725
+ - name: Add Python 3.8
726
+ if: matrix.container == 'almalinux:8'
727
+ run: dnf update -y && dnf install -y python38-devel gcc-c++ make git
728
+
729
+ - name: Add Python 3 (default)
730
+ if: matrix.container != 'almalinux:8'
731
+ run: dnf update -y && dnf install -y python3-devel gcc-c++ make git
732
+
733
+ - name: Update pip
734
+ run: python3 -m pip install --upgrade pip
735
+
736
+ - name: Install dependencies
737
+ run: |
738
+ python3 -m pip install cmake -r tests/requirements.txt
739
+
740
+ - name: Ensure NumPy 2 is used (required Python >= 3.9)
741
+ if: matrix.container == 'almalinux:9'
742
+ run: |
743
+ python3 -m pip install 'numpy>=2.0.0b1' 'scipy>=1.13.0rc1'
744
+
745
+ - name: Configure
746
+ shell: bash
747
+ run: >
748
+ cmake -S . -B build
749
+ -DCMAKE_BUILD_TYPE=MinSizeRel
750
+ -DPYBIND11_WERROR=ON
751
+ -DDOWNLOAD_CATCH=ON
752
+ -DDOWNLOAD_EIGEN=ON
753
+ -DCMAKE_CXX_STANDARD=11
754
+ -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)")
755
+
756
+ - name: Build
757
+ run: cmake --build build -j 2
758
+
759
+ - name: Python tests
760
+ run: cmake --build build --target pytest
761
+
762
+ - name: C++ tests
763
+ run: cmake --build build --target cpptest
764
+
765
+ - name: Interface test
766
+ run: cmake --build build --target test_cmake_build
767
+
768
+ - name: Visibility test
769
+ run: cmake --build build --target test_cross_module_rtti
770
+
771
+
772
+ # This tests an "install" with the CMake tools
773
+ install-classic:
774
+ if: github.event.pull_request.draft == false
775
+ name: "🐍 3.9 • Debian • x86 • Install"
776
+ runs-on: ubuntu-latest
777
+ container: i386/debian:bullseye
778
+ timeout-minutes: 90
779
+
780
+ steps:
781
+ - uses: actions/checkout@v1 # v1 is required to run inside docker
782
+
783
+ - name: Install requirements
784
+ run: |
785
+ apt-get update
786
+ apt-get install -y git make cmake g++ libeigen3-dev python3-dev python3-pip
787
+ pip3 install "pytest==6.*"
788
+
789
+ - name: Configure for install
790
+ run: >
791
+ cmake .
792
+ -DPYBIND11_INSTALL=1 -DPYBIND11_TEST=0
793
+ -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)")
794
+
795
+ - name: Make and install
796
+ run: make install
797
+
798
+ - name: Copy tests to new directory
799
+ run: cp -a tests /pybind11-tests
800
+
801
+ - name: Make a new test directory
802
+ run: mkdir /build-tests
803
+
804
+ - name: Configure tests
805
+ run: >
806
+ cmake ../pybind11-tests
807
+ -DDOWNLOAD_CATCH=ON
808
+ -DPYBIND11_WERROR=ON
809
+ -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)")
810
+ working-directory: /build-tests
811
+
812
+ - name: Python tests
813
+ run: make pytest -j 2
814
+ working-directory: /build-tests
815
+
816
+
817
+ # This verifies that the documentation is not horribly broken, and does a
818
+ # basic validation check on the SDist.
819
+ doxygen:
820
+ if: github.event.pull_request.draft == false
821
+ name: "Documentation build test"
822
+ runs-on: ubuntu-latest
823
+ timeout-minutes: 90
824
+
825
+ steps:
826
+ - uses: actions/checkout@v5
827
+
828
+ - uses: actions/setup-python@v6
829
+ with:
830
+ python-version: "3.x"
831
+
832
+ - name: Install Doxygen
833
+ run: sudo apt-get install -y doxygen librsvg2-bin # Changed to rsvg-convert in 20.04
834
+
835
+ - name: Build docs
836
+ run: pipx run nox -s docs
837
+
838
+ - name: Make SDist
839
+ run: pipx run nox -s build -- --sdist
840
+
841
+ - run: git status --ignored
842
+
843
+ - name: Check local include dir
844
+ run: >
845
+ ls pybind11;
846
+ python3 -c "import pybind11, pathlib; assert (a := pybind11.get_include()) == (b := str(pathlib.Path('include').resolve())), f'{a} != {b}'"
847
+
848
+ - name: Compare Dists (headers only)
849
+ working-directory: include
850
+ run: |
851
+ python3 -m pip install --user -U ../dist/*.tar.gz
852
+ installed=$(python3 -c "import pybind11; print(pybind11.get_include() + '/pybind11')")
853
+ diff -rq $installed ./pybind11
854
+
855
+ win32:
856
+ if: github.event.pull_request.draft == false
857
+ strategy:
858
+ fail-fast: false
859
+ matrix:
860
+ include:
861
+ - python: '3.8'
862
+ args: -DCMAKE_CXX_STANDARD=17
863
+ - python: '3.10'
864
+ args: -DCMAKE_CXX_STANDARD=20
865
+ - python: '3.13'
866
+
867
+
868
+ name: "🐍 ${{ matrix.python }} • MSVC 2022 • x86 ${{ matrix.args }}"
869
+ runs-on: windows-2022
870
+ timeout-minutes: 90
871
+
872
+ steps:
873
+ - uses: actions/checkout@v5
874
+
875
+ - name: Setup Python ${{ matrix.python }}
876
+ uses: actions/setup-python@v6
877
+ with:
878
+ python-version: ${{ matrix.python }}
879
+ architecture: x86
880
+ # Python 3.13.4 broken on Windows
881
+ check-latest: >-
882
+ ${{ matrix.python == '3.13' && runner.os == 'Windows' }}
883
+
884
+ - name: Update CMake
885
+ uses: jwlawson/actions-setup-cmake@v2.0
886
+
887
+ - name: Prepare MSVC
888
+ uses: ilammy/msvc-dev-cmd@v1.13.0
889
+ with:
890
+ arch: x86
891
+
892
+ - name: Prepare env
893
+ run: |
894
+ python -m pip install -r tests/requirements.txt
895
+
896
+ - name: Configure ${{ matrix.args }}
897
+ run: >
898
+ cmake -S . -B build
899
+ -G "Visual Studio 17 2022" -A Win32
900
+ -DPYBIND11_WERROR=ON
901
+ -DDOWNLOAD_CATCH=ON
902
+ -DDOWNLOAD_EIGEN=ON
903
+ ${{ matrix.args }}
904
+ - name: Build C++11
905
+ run: cmake --build build -j 2
906
+
907
+ - name: Python tests
908
+ run: cmake --build build -t pytest
909
+
910
+ win32-debug:
911
+ if: github.event.pull_request.draft == false
912
+ strategy:
913
+ fail-fast: false
914
+ matrix:
915
+ include:
916
+ - python: 3.9
917
+ args: -DCMAKE_CXX_STANDARD=20
918
+ - python: 3.8
919
+ args: -DCMAKE_CXX_STANDARD=17
920
+
921
+ name: "🐍 ${{ matrix.python }} • MSVC 2022 (Debug) • x86 ${{ matrix.args }}"
922
+ runs-on: windows-2022
923
+ timeout-minutes: 90
924
+
925
+ steps:
926
+ - uses: actions/checkout@v5
927
+
928
+ - name: Setup Python ${{ matrix.python }}
929
+ uses: actions/setup-python@v6
930
+ with:
931
+ python-version: ${{ matrix.python }}
932
+ architecture: x86
933
+
934
+ - name: Update CMake
935
+ uses: jwlawson/actions-setup-cmake@v2.0
936
+
937
+ - name: Prepare MSVC
938
+ uses: ilammy/msvc-dev-cmd@v1.13.0
939
+ with:
940
+ arch: x86
941
+
942
+ - name: Prepare env
943
+ run: |
944
+ python -m pip install -r tests/requirements.txt
945
+
946
+ - name: Configure ${{ matrix.args }}
947
+ run: >
948
+ cmake -S . -B build
949
+ -G "Visual Studio 17 2022" -A Win32
950
+ -DCMAKE_BUILD_TYPE=Debug
951
+ -DPYBIND11_WERROR=ON
952
+ -DDOWNLOAD_CATCH=ON
953
+ -DDOWNLOAD_EIGEN=ON
954
+ ${{ matrix.args }}
955
+ - name: Build C++11
956
+ run: cmake --build build --config Debug -j 2
957
+
958
+ - name: Python tests
959
+ run: cmake --build build --config Debug -t pytest
960
+
961
+
962
+ windows-2022:
963
+ if: github.event.pull_request.draft == false
964
+ strategy:
965
+ fail-fast: false
966
+ matrix:
967
+ python:
968
+ - 3.9
969
+
970
+ name: "🐍 ${{ matrix.python }} • MSVC 2022 C++20 • x64"
971
+ runs-on: windows-2022
972
+ timeout-minutes: 90
973
+
974
+ steps:
975
+ - uses: actions/checkout@v5
976
+
977
+ - name: Setup Python ${{ matrix.python }}
978
+ uses: actions/setup-python@v6
979
+ with:
980
+ python-version: ${{ matrix.python }}
981
+
982
+ - name: Prepare env
983
+ run: python3 -m pip install -r tests/requirements.txt
984
+
985
+ - name: Update CMake
986
+ uses: jwlawson/actions-setup-cmake@v2.0
987
+
988
+ - name: Configure C++20
989
+ run: >
990
+ cmake -S . -B build
991
+ -DPYBIND11_WERROR=ON
992
+ -DDOWNLOAD_CATCH=ON
993
+ -DDOWNLOAD_EIGEN=ON
994
+ -DCMAKE_CXX_STANDARD=20
995
+
996
+ - name: Build C++20
997
+ run: cmake --build build -j 2
998
+
999
+ - name: Python tests
1000
+ run: cmake --build build --target pytest
1001
+
1002
+ - name: C++20 tests
1003
+ run: cmake --build build --target cpptest -j 2
1004
+
1005
+ - name: Interface test C++20
1006
+ run: cmake --build build --target test_cmake_build
1007
+
1008
+ - name: Visibility test
1009
+ run: cmake --build build --target test_cross_module_rtti
1010
+
1011
+ - name: Configure C++20 - Exercise cmake -DPYBIND11_TEST_OVERRIDE
1012
+ run: >
1013
+ cmake -S . -B build_partial
1014
+ -DPYBIND11_WERROR=ON
1015
+ -DDOWNLOAD_CATCH=ON
1016
+ -DDOWNLOAD_EIGEN=ON
1017
+ -DCMAKE_CXX_STANDARD=20
1018
+ "-DPYBIND11_TEST_OVERRIDE=test_call_policies.cpp;test_gil_scoped.cpp;test_thread.cpp"
1019
+
1020
+ - name: Build C++20 - Exercise cmake -DPYBIND11_TEST_OVERRIDE
1021
+ run: cmake --build build_partial -j 2
1022
+
1023
+ - name: Python tests - Exercise cmake -DPYBIND11_TEST_OVERRIDE
1024
+ run: cmake --build build_partial --target pytest
1025
+
1026
+ mingw:
1027
+ if: github.event.pull_request.draft == false
1028
+ name: "🐍 3 • windows-latest • ${{ matrix.sys }}"
1029
+ runs-on: windows-latest
1030
+ timeout-minutes: 90
1031
+ defaults:
1032
+ run:
1033
+ shell: msys2 {0}
1034
+ strategy:
1035
+ fail-fast: false
1036
+ matrix:
1037
+ include:
1038
+ - sys: mingw32
1039
+ env: i686
1040
+ extra_install: ""
1041
+ - sys: mingw64
1042
+ env: x86_64
1043
+ extra_install: |
1044
+ mingw-w64-x86_64-python-numpy
1045
+ mingw-w64-x86_64-python-scipy
1046
+ mingw-w64-x86_64-eigen3
1047
+ steps:
1048
+ - uses: msys2/setup-msys2@v2
1049
+ with:
1050
+ msystem: ${{matrix.sys}}
1051
+ install: >-
1052
+ git
1053
+ mingw-w64-${{matrix.env}}-gcc
1054
+ mingw-w64-${{matrix.env}}-python-pip
1055
+ mingw-w64-${{matrix.env}}-cmake
1056
+ mingw-w64-${{matrix.env}}-make
1057
+ mingw-w64-${{matrix.env}}-python-pytest
1058
+ mingw-w64-${{matrix.env}}-boost
1059
+ mingw-w64-${{matrix.env}}-catch
1060
+ ${{ matrix.extra_install }}
1061
+
1062
+ - uses: actions/checkout@v5
1063
+
1064
+ - name: Configure C++11
1065
+ # LTO leads to many undefined reference like
1066
+ # `pybind11::detail::function_call::function_call(pybind11::detail::function_call&&)
1067
+ run: >-
1068
+ cmake -G "MinGW Makefiles" -DCMAKE_CXX_STANDARD=11 -DPYBIND11_WERROR=ON -DDOWNLOAD_CATCH=ON
1069
+ -DPYTHON_EXECUTABLE=$(python -c "import sys; print(sys.executable)")
1070
+ -S . -B build
1071
+
1072
+ - name: Build C++11
1073
+ run: cmake --build build -j 2
1074
+
1075
+ - name: Python tests C++11
1076
+ run: cmake --build build --target pytest -j 2
1077
+
1078
+ - name: C++11 tests
1079
+ run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build --target cpptest -j 2
1080
+
1081
+ - name: Interface test C++11
1082
+ run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build --target test_cmake_build
1083
+
1084
+ - name: Visibility test
1085
+ run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build --target test_cross_module_rtti
1086
+
1087
+ - name: Clean directory
1088
+ run: git clean -fdx
1089
+
1090
+ - name: Configure C++14
1091
+ run: >-
1092
+ cmake -G "MinGW Makefiles" -DCMAKE_CXX_STANDARD=14 -DPYBIND11_WERROR=ON -DDOWNLOAD_CATCH=ON
1093
+ -DPYTHON_EXECUTABLE=$(python -c "import sys; print(sys.executable)")
1094
+ -S . -B build2
1095
+
1096
+ - name: Build C++14
1097
+ run: cmake --build build2 -j 2
1098
+
1099
+ - name: Python tests C++14
1100
+ run: cmake --build build2 --target pytest -j 2
1101
+
1102
+ - name: C++14 tests
1103
+ run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build2 --target cpptest -j 2
1104
+
1105
+ - name: Interface test C++14
1106
+ run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build2 --target test_cmake_build
1107
+
1108
+ - name: Visibility test
1109
+ run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build2 --target test_cross_module_rtti
1110
+
1111
+ - name: Clean directory
1112
+ run: git clean -fdx
1113
+
1114
+ - name: Configure C++17
1115
+ run: >-
1116
+ cmake -G "MinGW Makefiles" -DCMAKE_CXX_STANDARD=17 -DPYBIND11_WERROR=ON -DDOWNLOAD_CATCH=ON
1117
+ -DPYTHON_EXECUTABLE=$(python -c "import sys; print(sys.executable)")
1118
+ -S . -B build3
1119
+
1120
+ - name: Build C++17
1121
+ run: cmake --build build3 -j 2
1122
+
1123
+ - name: Python tests C++17
1124
+ run: cmake --build build3 --target pytest -j 2
1125
+
1126
+ - name: C++17 tests
1127
+ run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build3 --target cpptest -j 2
1128
+
1129
+ - name: Interface test C++17
1130
+ run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build3 --target test_cmake_build
1131
+
1132
+ - name: Visibility test
1133
+ run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build3 --target test_cross_module_rtti
1134
+
1135
+ windows_clang:
1136
+ if: github.event.pull_request.draft == false
1137
+
1138
+ strategy:
1139
+ matrix:
1140
+ os: [windows-latest]
1141
+ python: ['3.10']
1142
+
1143
+ runs-on: "${{ matrix.os }}"
1144
+ timeout-minutes: 90
1145
+
1146
+ name: "🐍 ${{ matrix.python }} • ${{ matrix.os }} • clang-latest"
1147
+
1148
+ steps:
1149
+ - name: Show env
1150
+ run: env
1151
+
1152
+ - name: Checkout
1153
+ uses: actions/checkout@v5
1154
+
1155
+ - name: Set up Clang
1156
+ uses: egor-tensin/setup-clang@v1
1157
+
1158
+ - name: Setup Python ${{ matrix.python }}
1159
+ uses: actions/setup-python@v6
1160
+ with:
1161
+ python-version: ${{ matrix.python }}
1162
+
1163
+ - name: Update CMake
1164
+ uses: jwlawson/actions-setup-cmake@v2.0
1165
+
1166
+ - name: Install ninja-build tool
1167
+ uses: seanmiddleditch/gha-setup-ninja@v6
1168
+
1169
+ - name: Run pip installs
1170
+ run: |
1171
+ python -m pip install --upgrade pip
1172
+ python -m pip install -r tests/requirements.txt
1173
+
1174
+ - name: Show Clang++ version
1175
+ run: clang++ --version
1176
+
1177
+ - name: Show CMake version
1178
+ run: cmake --version
1179
+
1180
+ # TODO: WERROR=ON
1181
+ - name: Configure Clang
1182
+ run: >
1183
+ cmake -G Ninja -S . -B .
1184
+ -DPYBIND11_WERROR=OFF
1185
+ -DPYBIND11_SIMPLE_GIL_MANAGEMENT=OFF
1186
+ -DDOWNLOAD_CATCH=ON
1187
+ -DDOWNLOAD_EIGEN=ON
1188
+ -DCMAKE_CXX_COMPILER=clang++
1189
+ -DCMAKE_CXX_STANDARD=17
1190
+
1191
+ - name: Build
1192
+ run: cmake --build . -j 2
1193
+
1194
+ - name: Python tests
1195
+ run: cmake --build . --target pytest -j 2
1196
+
1197
+ - name: C++ tests
1198
+ run: cmake --build . --target cpptest -j 2
1199
+
1200
+ - name: Interface test
1201
+ run: cmake --build . --target test_cmake_build -j 2
1202
+
1203
+ - name: Visibility test
1204
+ run: cmake --build . --target test_cross_module_rtti -j 2
1205
+
1206
+ - name: Clean directory
1207
+ run: git clean -fdx
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/configure.yml ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Config
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ pull_request:
6
+ types:
7
+ - opened
8
+ - synchronize
9
+ - reopened
10
+ - ready_for_review
11
+ push:
12
+ branches:
13
+ - master
14
+ - stable
15
+ - v*
16
+
17
+ permissions:
18
+ contents: read
19
+
20
+ jobs:
21
+ # This tests various versions of CMake in various combinations, to make sure
22
+ # the configure step passes.
23
+ cmake:
24
+ if: github.event.pull_request.draft == false
25
+ strategy:
26
+ fail-fast: false
27
+ matrix:
28
+ include:
29
+ - runs-on: ubuntu-22.04
30
+ cmake: "3.15"
31
+
32
+ - runs-on: ubuntu-24.04
33
+ cmake: "3.26"
34
+
35
+ - runs-on: ubuntu-24.04
36
+ cmake: "3.29"
37
+
38
+ - runs-on: macos-13
39
+ cmake: "3.15"
40
+
41
+ - runs-on: macos-14
42
+ cmake: "4.0"
43
+
44
+ - runs-on: windows-latest
45
+ cmake: "4.0"
46
+
47
+ name: 🐍 3.11 • CMake ${{ matrix.cmake }} • ${{ matrix.runs-on }}
48
+ runs-on: ${{ matrix.runs-on }}
49
+
50
+ steps:
51
+ - uses: actions/checkout@v5
52
+
53
+ - name: Setup Python 3.11
54
+ uses: actions/setup-python@v6
55
+ with:
56
+ python-version: 3.11
57
+
58
+ - name: Install uv
59
+ uses: astral-sh/setup-uv@v6
60
+
61
+ - name: Prepare env
62
+ run: uv pip install --python=python --system -r tests/requirements.txt
63
+
64
+ # An action for adding a specific version of CMake:
65
+ # https://github.com/jwlawson/actions-setup-cmake
66
+ - name: Setup CMake ${{ matrix.cmake }}
67
+ uses: jwlawson/actions-setup-cmake@v2.0
68
+ with:
69
+ cmake-version: ${{ matrix.cmake }}
70
+
71
+ # These steps use a directory with a space in it intentionally
72
+ - name: Configure
73
+ shell: bash
74
+ run: cmake -S. -B"build dir" -DPYBIND11_WERROR=ON -DDOWNLOAD_CATCH=ON
75
+
76
+ # Only build and test if this was manually triggered in the GitHub UI
77
+ - name: Build
78
+ working-directory: build dir
79
+ if: github.event_name == 'workflow_dispatch'
80
+ run: cmake --build . --config Release
81
+
82
+ - name: Test
83
+ working-directory: build dir
84
+ if: github.event_name == 'workflow_dispatch'
85
+ run: cmake --build . --config Release --target check
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/docs-link.yml ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Read the Docs PR preview
2
+
3
+ on:
4
+ pull_request_target:
5
+ types:
6
+ - opened
7
+ - synchronize
8
+
9
+ permissions:
10
+ contents: read
11
+ pull-requests: write
12
+
13
+ concurrency:
14
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
15
+ cancel-in-progress: true
16
+
17
+ jobs:
18
+ documentation-links:
19
+ runs-on: ubuntu-latest
20
+ if: github.event.repository.fork == false
21
+ steps:
22
+ - uses: actions/checkout@v5
23
+
24
+ - name: Check for docs changes
25
+ id: docs_changes
26
+ run: |
27
+ # Fetch the PR head
28
+ git fetch origin pull/${{ github.event.pull_request.number }}/head:pr-head
29
+
30
+ # Show diff between base (current checkout) and PR head
31
+ if git diff --name-only HEAD pr-head | grep -q '^docs/'; then
32
+ echo "docs_changed=true" >> "$GITHUB_OUTPUT"
33
+ else
34
+ echo "docs_changed=false" >> "$GITHUB_OUTPUT"
35
+ fi
36
+
37
+ - uses: readthedocs/actions/preview@v1
38
+ if: steps.docs_changes.outputs.docs_changed == 'true'
39
+ with:
40
+ project-slug: "pybind11"
41
+ single-version: "true"
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/format.yml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is a format job. Pre-commit has a first-party GitHub action, so we use
2
+ # that: https://github.com/pre-commit/action
3
+
4
+ name: Format
5
+
6
+ on:
7
+ workflow_dispatch:
8
+ pull_request:
9
+ push:
10
+ branches:
11
+ - master
12
+ - stable
13
+ - "v*"
14
+
15
+ permissions:
16
+ contents: read
17
+
18
+ env:
19
+ FORCE_COLOR: 3
20
+ # For cmake:
21
+ VERBOSE: 1
22
+
23
+ jobs:
24
+ pre-commit:
25
+ name: Format
26
+ runs-on: ubuntu-latest
27
+ steps:
28
+ - uses: actions/checkout@v5
29
+ - uses: actions/setup-python@v6
30
+ with:
31
+ python-version: "3.x"
32
+ - name: Add matchers
33
+ run: echo "::add-matcher::$GITHUB_WORKSPACE/.github/matchers/pylint.json"
34
+ - uses: pre-commit/action@v3.0.1
35
+
36
+ clang-tidy:
37
+ # When making changes here, please also review the "Clang-Tidy" section
38
+ # in .github/CONTRIBUTING.md and update as needed.
39
+ name: Clang-Tidy
40
+ runs-on: ubuntu-latest
41
+ container: silkeh/clang:20
42
+ steps:
43
+ - uses: actions/checkout@v5
44
+
45
+ - name: Install requirements
46
+ run: apt-get update && apt-get install -y git python3-dev python3-pytest ninja-build
47
+
48
+ - name: Configure
49
+ run: cmake --preset tidy
50
+ - name: Build
51
+ run: cmake --build --preset tidy
52
+
53
+ - name: Embedded
54
+ run: cmake --build --preset tidy -t cpptest
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/labeler.yml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Labeler
2
+ on:
3
+ pull_request_target:
4
+ types: [closed]
5
+
6
+ permissions: {}
7
+
8
+ jobs:
9
+ label:
10
+ name: Labeler
11
+ runs-on: ubuntu-latest
12
+ permissions:
13
+ contents: read
14
+ pull-requests: write
15
+ steps:
16
+
17
+ - uses: actions/labeler@v6
18
+ if: >
19
+ github.event.pull_request.merged == true &&
20
+ !startsWith(github.event.pull_request.title, 'chore(deps):') &&
21
+ !startsWith(github.event.pull_request.title, 'ci(fix):') &&
22
+ !startsWith(github.event.pull_request.title, 'docs(changelog):')
23
+ with:
24
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
25
+ configuration-path: .github/labeler_merged.yml
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/nightlies.yml ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Upload nightly wheels to Anaconda Cloud
2
+
3
+ on:
4
+ # Run daily at 2:34 UTC to upload nightly wheels to Anaconda Cloud
5
+ schedule:
6
+ - cron: "34 2 * * *"
7
+ # Run on demand with workflow dispatch
8
+ workflow_dispatch:
9
+
10
+ permissions:
11
+ actions: read
12
+
13
+ concurrency:
14
+ group: ${{ github.workflow }}-${{ github.ref }}
15
+ cancel-in-progress: true
16
+
17
+ jobs:
18
+ build_wheel:
19
+ name: Build and upload wheel
20
+ if: github.repository_owner == 'pybind'
21
+ runs-on: ubuntu-latest
22
+ steps:
23
+ - uses: actions/checkout@v5
24
+ with:
25
+ fetch-depth: 0
26
+
27
+ - name: Install uv
28
+ uses: astral-sh/setup-uv@v6
29
+
30
+ - name: Build SDist and wheels
31
+ run: |
32
+ uv tool install nox
33
+ nox -s build
34
+ nox -s build_global
35
+
36
+ - uses: actions/upload-artifact@v4
37
+ with:
38
+ name: Packages
39
+ path: dist/*
40
+
41
+ upload_nightly_wheels:
42
+ name: Upload nightly wheels to Anaconda Cloud
43
+ if: github.repository_owner == 'pybind'
44
+ needs: [build_wheel]
45
+ runs-on: ubuntu-latest
46
+ steps:
47
+ - uses: actions/download-artifact@v5
48
+ with:
49
+ name: Packages
50
+ path: dist
51
+
52
+ - name: List wheel to be deployed
53
+ run: ls -lha dist/*.whl
54
+
55
+ - name: Upload wheel to Anaconda Cloud as nightly
56
+ uses: scientific-python/upload-nightly-action@b36e8c0c10dbcfd2e05bf95f17ef8c14fd708dbf # 0.6.2
57
+ with:
58
+ artifacts_path: dist
59
+ anaconda_nightly_upload_token: ${{ secrets.ANACONDA_ORG_UPLOAD_TOKEN }}
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/pip.yml ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Pip
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ pull_request:
6
+ push:
7
+ branches:
8
+ - master
9
+ - stable
10
+ - v*
11
+ release:
12
+ types:
13
+ - published
14
+
15
+ permissions:
16
+ contents: read
17
+
18
+ jobs:
19
+ # This builds the sdists and wheels and makes sure the files are exactly as
20
+ # expected.
21
+ test-packaging:
22
+ name: 🐍 3.8 • 📦 tests • windows-latest
23
+ runs-on: windows-latest
24
+
25
+ steps:
26
+ - uses: actions/checkout@v5
27
+
28
+ - name: Setup 🐍 3.8
29
+ uses: actions/setup-python@v6
30
+ with:
31
+ python-version: 3.8
32
+
33
+ - name: Install uv
34
+ uses: astral-sh/setup-uv@v6
35
+
36
+ - name: Prepare env
37
+ run: uv pip install --system -r tests/requirements.txt
38
+
39
+ - name: Python Packaging tests
40
+ run: pytest tests/extra_python_package/
41
+
42
+
43
+ # This runs the packaging tests and also builds and saves the packages as
44
+ # artifacts.
45
+ packaging:
46
+ name: 🐍 3.8 • 📦 & 📦 tests • ubuntu-latest
47
+ runs-on: ubuntu-latest
48
+
49
+ steps:
50
+ - uses: actions/checkout@v5
51
+
52
+ - name: Setup 🐍 3.8
53
+ uses: actions/setup-python@v6
54
+ with:
55
+ python-version: 3.8
56
+
57
+ - name: Install uv
58
+ uses: astral-sh/setup-uv@v6
59
+
60
+ - name: Prepare env
61
+ run: uv pip install --system -r tests/requirements.txt twine nox
62
+
63
+ - name: Python Packaging tests
64
+ run: pytest tests/extra_python_package/
65
+
66
+ - name: Build SDist and wheels
67
+ run: |
68
+ nox -s build
69
+ nox -s build_global
70
+
71
+ - name: Check metadata
72
+ run: twine check dist/*
73
+
74
+ - name: Save standard package
75
+ uses: actions/upload-artifact@v4
76
+ with:
77
+ name: standard
78
+ path: dist/pybind11-*
79
+
80
+ - name: Save global package
81
+ uses: actions/upload-artifact@v4
82
+ with:
83
+ name: global
84
+ path: dist/*global-*
85
+
86
+
87
+
88
+ # When a GitHub release is made, upload the artifacts to PyPI
89
+ upload:
90
+ name: Upload to PyPI
91
+ runs-on: ubuntu-latest
92
+ if: github.event_name == 'release' && github.event.action == 'published'
93
+ needs: [packaging]
94
+ environment:
95
+ name: pypi
96
+ url: https://pypi.org/p/pybind11
97
+ permissions:
98
+ id-token: write
99
+ attestations: write
100
+
101
+ steps:
102
+ # Downloads all to directories matching the artifact names
103
+ - uses: actions/download-artifact@v5
104
+
105
+ - name: Generate artifact attestation for sdist and wheel
106
+ uses: actions/attest-build-provenance@v3
107
+ with:
108
+ subject-path: "*/pybind11*"
109
+
110
+ - name: Publish standard package
111
+ uses: pypa/gh-action-pypi-publish@release/v1
112
+ with:
113
+ packages-dir: standard/
114
+
115
+ - name: Publish global package
116
+ uses: pypa/gh-action-pypi-publish@release/v1
117
+ with:
118
+ packages-dir: global/
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/reusable-standard.yml ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Reusable Standard Test
2
+
3
+ on:
4
+ workflow_call:
5
+ inputs:
6
+ python-version:
7
+ required: true
8
+ type: string
9
+ cmake-args:
10
+ required: false
11
+ type: string
12
+ default: ''
13
+ runs-on:
14
+ required: true
15
+ type: string
16
+
17
+ env:
18
+ PYTHONDEVMODE: 1
19
+ PIP_BREAK_SYSTEM_PACKAGES: 1
20
+ PIP_ONLY_BINARY: numpy
21
+ FORCE_COLOR: 3
22
+ PYTEST_TIMEOUT: 300
23
+ # For cmake:
24
+ VERBOSE: 1
25
+ CMAKE_COLOR_DIAGNOSTICS: 1
26
+
27
+ jobs:
28
+ standard:
29
+ name: 🧪
30
+ runs-on: ${{ inputs.runs-on }}
31
+ timeout-minutes: 90
32
+
33
+ steps:
34
+ - uses: actions/checkout@v5
35
+
36
+ - name: Setup Python ${{ inputs.python-version }}
37
+ uses: actions/setup-python@v6
38
+ with:
39
+ python-version: ${{ inputs.python-version }}
40
+ allow-prereleases: true
41
+ # Python 3.13.4 broken on Windows
42
+ check-latest: >-
43
+ ${{ inputs.python-version == '3.13' && runner.os == 'Windows' }}
44
+
45
+ - name: Setup Boost (Linux)
46
+ if: runner.os == 'Linux'
47
+ run: sudo apt-get install libboost-dev
48
+
49
+ - name: Setup Boost (macOS)
50
+ if: runner.os == 'macOS'
51
+ run: brew install boost
52
+
53
+ - name: Install uv
54
+ uses: astral-sh/setup-uv@v6
55
+ with:
56
+ enable-cache: true
57
+
58
+ - name: Prepare env
59
+ run: uv pip install --python=python --system -r tests/requirements.txt
60
+
61
+ - name: Setup annotations on Linux
62
+ if: runner.os == 'Linux'
63
+ run: uv pip install --python=python --system pytest-github-actions-annotate-failures
64
+
65
+ # TODO Resolve Windows Ninja shared object issue on Python 3.8+
66
+ - name: Use Ninja except on Windows
67
+ if: runner.os != 'Windows'
68
+ run: echo "CMAKE_GENERATOR=Ninja" >> "$GITHUB_ENV"
69
+
70
+ - name: Configure
71
+ run: >
72
+ cmake -S. -Bbuild -Werror=dev
73
+ -DPYBIND11_WERROR=ON
74
+ -DPYBIND11_PYTEST_ARGS=-v
75
+ -DDOWNLOAD_CATCH=ON
76
+ -DDOWNLOAD_EIGEN=ON
77
+ ${{ inputs.cmake-args }}
78
+
79
+ - name: Build
80
+ run: cmake --build build
81
+
82
+ - name: Python tests
83
+ run: cmake --build build --target pytest
84
+
85
+ - name: C++ tests
86
+ run: cmake --build build --target cpptest
87
+
88
+ - name: Interface test
89
+ run: cmake --build build --target test_cmake_build
90
+
91
+ - name: Visibility test
92
+ run: cmake --build build --target test_cross_module_rtti
93
+
94
+ - name: Setuptools helpers test
95
+ run: |
96
+ uv pip install --python=python --system setuptools
97
+ pytest tests/extra_setuptools
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/tests-cibw.yml ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CIBW
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ pull_request:
6
+ branches:
7
+ - master
8
+ - stable
9
+ - v*
10
+
11
+ concurrency:
12
+ group: ${{ github.workflow }}-${{ github.ref }}
13
+ cancel-in-progress: true
14
+
15
+ jobs:
16
+ build-wasm-emscripten:
17
+ name: Pyodide wheel
18
+ runs-on: ubuntu-latest
19
+ steps:
20
+ - uses: actions/checkout@v5
21
+ with:
22
+ submodules: true
23
+ fetch-depth: 0
24
+
25
+ - uses: pypa/cibuildwheel@v3.1
26
+ env:
27
+ PYODIDE_BUILD_EXPORTS: whole_archive
28
+ with:
29
+ package-dir: tests
30
+ only: cp312-pyodide_wasm32
31
+
32
+ build-ios:
33
+ name: iOS wheel ${{ matrix.runs-on }}
34
+ runs-on: ${{ matrix.runs-on }}
35
+ strategy:
36
+ fail-fast: false
37
+ matrix:
38
+ runs-on: [macos-14, macos-13]
39
+ steps:
40
+ - uses: actions/checkout@v5
41
+ with:
42
+ submodules: true
43
+ fetch-depth: 0
44
+
45
+ # We have to uninstall first because GH is now using a local tap to build cmake<4, iOS needs cmake>=4
46
+ - run: brew uninstall cmake && brew install cmake
47
+
48
+ - uses: pypa/cibuildwheel@v3.1
49
+ env:
50
+ CIBW_PLATFORM: ios
51
+ CIBW_SKIP: cp314-* # https://github.com/pypa/cibuildwheel/issues/2494
52
+ with:
53
+ package-dir: tests
54
+
55
+ build-android:
56
+ name: Android wheel ${{ matrix.runs-on }}
57
+ runs-on: ${{ matrix.runs-on }}
58
+ strategy:
59
+ fail-fast: false
60
+ matrix:
61
+ runs-on: [macos-latest, macos-13, ubuntu-latest]
62
+ steps:
63
+ - uses: actions/checkout@v5
64
+ with:
65
+ submodules: true
66
+ fetch-depth: 0
67
+
68
+ # GitHub Actions can't currently run the Android emulator on macOS.
69
+ - name: Skip Android tests on macOS
70
+ if: contains(matrix.runs-on, 'macos')
71
+ run: echo "CIBW_TEST_COMMAND=" >> "$GITHUB_ENV"
72
+
73
+ # https://github.blog/changelog/2024-04-02-github-actions-hardware-accelerated-android-virtualization-now-available/
74
+ - name: Enable KVM for Android emulator
75
+ if: contains(matrix.runs-on, 'ubuntu')
76
+ run: |
77
+ echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
78
+ sudo udevadm control --reload-rules
79
+ sudo udevadm trigger --name-match=kvm
80
+
81
+ - run: pipx install patchelf
82
+
83
+ - uses: pypa/cibuildwheel@v3.1
84
+ env:
85
+ CIBW_PLATFORM: android
86
+ with:
87
+ package-dir: tests
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.github/workflows/upstream.yml ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Upstream
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ pull_request:
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ concurrency:
11
+ group: upstream-${{ github.ref }}
12
+ cancel-in-progress: true
13
+
14
+ env:
15
+ PIP_BREAK_SYSTEM_PACKAGES: 1
16
+ # For cmake:
17
+ VERBOSE: 1
18
+
19
+ jobs:
20
+ standard:
21
+ name: "🐍 3.13 latest • ubuntu-latest • x64"
22
+ runs-on: ubuntu-latest
23
+ # Only runs when the 'python dev' label is selected
24
+ if: "contains(github.event.pull_request.labels.*.name, 'python dev')"
25
+
26
+ steps:
27
+ - uses: actions/checkout@v5
28
+
29
+ - name: Setup Python 3.13
30
+ uses: actions/setup-python@v6
31
+ with:
32
+ python-version: "3.13"
33
+ allow-prereleases: true
34
+
35
+ - name: Setup Boost
36
+ run: sudo apt-get install libboost-dev
37
+
38
+ - name: Update CMake
39
+ uses: jwlawson/actions-setup-cmake@v2.0
40
+
41
+ - name: Run pip installs
42
+ run: |
43
+ python -m pip install --upgrade pip
44
+ python -m pip install -r tests/requirements.txt
45
+
46
+ - name: Show platform info
47
+ run: |
48
+ python -m platform
49
+ cmake --version
50
+ pip list
51
+
52
+ # First build - C++11 mode and inplace
53
+ - name: Configure C++11
54
+ run: >
55
+ cmake -S . -B build11
56
+ -DPYBIND11_WERROR=ON
57
+ -DDOWNLOAD_CATCH=ON
58
+ -DDOWNLOAD_EIGEN=ON
59
+ -DCMAKE_CXX_STANDARD=11
60
+ -DCMAKE_BUILD_TYPE=Debug
61
+
62
+ - name: Build C++11
63
+ run: cmake --build build11 -j 2
64
+
65
+ - name: Python tests C++11
66
+ run: cmake --build build11 --target pytest -j 2
67
+
68
+ - name: C++11 tests
69
+ run: cmake --build build11 --target cpptest -j 2
70
+
71
+ - name: Interface test C++11
72
+ run: cmake --build build11 --target test_cmake_build
73
+
74
+ # Second build - C++17 mode and in a build directory
75
+ - name: Configure C++17
76
+ run: >
77
+ cmake -S . -B build17
78
+ -DPYBIND11_WERROR=ON
79
+ -DDOWNLOAD_CATCH=ON
80
+ -DDOWNLOAD_EIGEN=ON
81
+ -DCMAKE_CXX_STANDARD=17
82
+
83
+ - name: Build C++17
84
+ run: cmake --build build17 -j 2
85
+
86
+ - name: Python tests C++17
87
+ run: cmake --build build17 --target pytest
88
+
89
+ - name: C++17 tests
90
+ run: cmake --build build17 --target cpptest
91
+
92
+ # Third build - C++17 mode with unstable ABI
93
+ - name: Configure (unstable ABI)
94
+ run: >
95
+ cmake -S . -B build17max
96
+ -DPYBIND11_WERROR=ON
97
+ -DDOWNLOAD_CATCH=ON
98
+ -DDOWNLOAD_EIGEN=ON
99
+ -DCMAKE_CXX_STANDARD=17
100
+ -DPYBIND11_INTERNALS_VERSION=10000000
101
+
102
+ - name: Build (unstable ABI)
103
+ run: cmake --build build17max -j 2
104
+
105
+ - name: Python tests (unstable ABI)
106
+ run: cmake --build build17max --target pytest
107
+
108
+ - name: Interface test (unstable ABI)
109
+ run: cmake --build build17max --target test_cmake_build
110
+
111
+ # This makes sure the setup_helpers module can build packages using
112
+ # setuptools
113
+ - name: Setuptools helpers test
114
+ run: |
115
+ pip install setuptools
116
+ pytest tests/extra_setuptools
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.gitignore ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CMakeCache.txt
2
+ CMakeFiles
3
+ Makefile
4
+ cmake_install.cmake
5
+ cmake_uninstall.cmake
6
+ .DS_Store
7
+ *.so
8
+ *.pyd
9
+ *.dll
10
+ *.sln
11
+ *.sdf
12
+ *.opensdf
13
+ *.vcxproj
14
+ *.vcxproj.user
15
+ *.filters
16
+ example.dir
17
+ Win32
18
+ x64
19
+ Release
20
+ Debug
21
+ .vs
22
+ CTestTestfile.cmake
23
+ Testing
24
+ autogen
25
+ MANIFEST
26
+ /.ninja_*
27
+ /*.ninja
28
+ /docs/.build
29
+ __pycache__/
30
+ *.py[co]
31
+ *.egg-info
32
+ *~
33
+ .*.swp
34
+ .DS_Store
35
+ /dist
36
+ /*build*
37
+ .cache/
38
+ sosize-*.txt
39
+ pybind11Config*.cmake
40
+ pybind11Targets.cmake
41
+ /*env*
42
+ /.vscode
43
+ /pybind11/include/*
44
+ /pybind11/share/*
45
+ /docs/_build/*
46
+ .ipynb_checkpoints/
47
+ tests/main.cpp
48
+ CMakeUserPresents.json
49
+
50
+ /Python
51
+ /tmp*
52
+ .ruby-version
53
+ .*cache*/
54
+ *.lock
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.pre-commit-config.yaml ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # To use:
2
+ #
3
+ # pre-commit run -a
4
+ #
5
+ # Or:
6
+ #
7
+ # pre-commit install # (runs every time you commit in git)
8
+ #
9
+ # To update this file:
10
+ #
11
+ # pre-commit autoupdate
12
+ #
13
+ # See https://github.com/pre-commit/pre-commit
14
+
15
+
16
+ ci:
17
+ autoupdate_commit_msg: "chore(deps): update pre-commit hooks"
18
+ autofix_commit_msg: "style: pre-commit fixes"
19
+ autoupdate_schedule: monthly
20
+
21
+ # third-party content
22
+ exclude: ^tools/JoinPaths.cmake$
23
+
24
+ repos:
25
+
26
+ # Clang format the codebase automatically
27
+ - repo: https://github.com/pre-commit/mirrors-clang-format
28
+ rev: "v21.1.2"
29
+ hooks:
30
+ - id: clang-format
31
+ types_or: [c++, c, cuda]
32
+
33
+ # Ruff, the Python auto-correcting linter/formatter written in Rust
34
+ - repo: https://github.com/astral-sh/ruff-pre-commit
35
+ rev: v0.13.3
36
+ hooks:
37
+ - id: ruff-check
38
+ args: ["--fix", "--show-fixes"]
39
+ - id: ruff-format
40
+
41
+ # Check static types with mypy
42
+ - repo: https://github.com/pre-commit/mirrors-mypy
43
+ rev: "v1.18.2"
44
+ hooks:
45
+ - id: mypy
46
+ args: []
47
+ exclude: ^(tests|docs)/
48
+ additional_dependencies:
49
+ - markdown-it-py
50
+ - nox
51
+ - rich
52
+ - types-setuptools
53
+
54
+ # CMake formatting
55
+ - repo: https://github.com/cheshirekow/cmake-format-precommit
56
+ rev: "v0.6.13"
57
+ hooks:
58
+ - id: cmake-format
59
+ additional_dependencies: [pyyaml]
60
+ types: [file]
61
+ files: (\.cmake|CMakeLists.txt)(.in)?$
62
+
63
+ # Standard hooks
64
+ - repo: https://github.com/pre-commit/pre-commit-hooks
65
+ rev: "v6.0.0"
66
+ hooks:
67
+ - id: check-added-large-files
68
+ - id: check-case-conflict
69
+ - id: check-docstring-first
70
+ - id: check-merge-conflict
71
+ - id: check-symlinks
72
+ - id: check-toml
73
+ - id: check-yaml
74
+ - id: debug-statements
75
+ - id: end-of-file-fixer
76
+ - id: mixed-line-ending
77
+ - id: requirements-txt-fixer
78
+ - id: trailing-whitespace
79
+ exclude: \.patch?$
80
+
81
+ # Also code format the docs
82
+ - repo: https://github.com/adamchainz/blacken-docs
83
+ rev: "1.20.0"
84
+ hooks:
85
+ - id: blacken-docs
86
+ additional_dependencies:
87
+ - black==23.*
88
+
89
+ # Changes tabs to spaces
90
+ - repo: https://github.com/Lucas-C/pre-commit-hooks
91
+ rev: "v1.5.5"
92
+ hooks:
93
+ - id: remove-tabs
94
+ exclude: (^docs/.*|\.patch)?$
95
+
96
+ # Avoid directional quotes
97
+ - repo: https://github.com/sirosen/texthooks
98
+ rev: "0.7.1"
99
+ hooks:
100
+ - id: fix-ligatures
101
+ - id: fix-smartquotes
102
+
103
+ # Checking for common mistakes
104
+ - repo: https://github.com/pre-commit/pygrep-hooks
105
+ rev: "v1.10.0"
106
+ hooks:
107
+ - id: rst-backticks
108
+ - id: rst-directive-colons
109
+ - id: rst-inline-touching-normal
110
+
111
+ # Check for spelling
112
+ # Use tools/codespell_ignore_lines_from_errors.py
113
+ # to rebuild .codespell-ignore-lines
114
+ - repo: https://github.com/codespell-project/codespell
115
+ rev: "v2.4.1"
116
+ hooks:
117
+ - id: codespell
118
+ exclude: ".supp$"
119
+ args: ["-x.codespell-ignore-lines", "-Lccompiler,intstruct"]
120
+
121
+ # Check for common shell mistakes
122
+ - repo: https://github.com/shellcheck-py/shellcheck-py
123
+ rev: "v0.11.0.1"
124
+ hooks:
125
+ - id: shellcheck
126
+
127
+ # Disallow some common capitalization mistakes
128
+ - repo: local
129
+ hooks:
130
+ - id: disallow-caps
131
+ name: Disallow improper capitalization
132
+ language: pygrep
133
+ entry: PyBind|\bNumpy\b|Cmake|CCache|PyTest
134
+ exclude: ^\.pre-commit-config.yaml$
135
+
136
+ # PyLint has native support - not always usable, but works for us
137
+ - repo: https://github.com/PyCQA/pylint
138
+ rev: "v3.3.9"
139
+ hooks:
140
+ - id: pylint
141
+ files: ^pybind11
142
+
143
+ # Check schemas on some of our YAML files
144
+ - repo: https://github.com/python-jsonschema/check-jsonschema
145
+ rev: 0.34.0
146
+ hooks:
147
+ - id: check-readthedocs
148
+ - id: check-github-workflows
149
+ - id: check-dependabot
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/.readthedocs.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://blog.readthedocs.com/migrate-configuration-v2/
2
+
3
+ version: 2
4
+
5
+ build:
6
+ os: ubuntu-22.04
7
+ apt_packages:
8
+ - librsvg2-bin
9
+ tools:
10
+ python: "3.11"
11
+
12
+ sphinx:
13
+ configuration: docs/conf.py
14
+
15
+ python:
16
+ install:
17
+ - requirements: docs/requirements.txt
18
+
19
+ formats:
20
+ - pdf
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/CMakeLists.txt ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CMakeLists.txt -- Build system for the pybind11 modules
2
+ #
3
+ # Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
4
+ #
5
+ # All rights reserved. Use of this source code is governed by a
6
+ # BSD-style license that can be found in the LICENSE file.
7
+
8
+ # Propagate this policy (FindPythonInterp removal) so it can be detected later
9
+ if(NOT CMAKE_VERSION VERSION_LESS "3.27")
10
+ cmake_policy(GET CMP0148 _pybind11_cmp0148)
11
+ endif()
12
+
13
+ cmake_minimum_required(VERSION 3.15...4.0)
14
+
15
+ if(_pybind11_cmp0148)
16
+ cmake_policy(SET CMP0148 ${_pybind11_cmp0148})
17
+ unset(_pybind11_cmp0148)
18
+ endif()
19
+
20
+ # Avoid infinite recursion if tests include this as a subdirectory
21
+ include_guard(GLOBAL)
22
+
23
+ # Extract project version from source
24
+ file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/include/pybind11/detail/common.h"
25
+ pybind11_version_defines REGEX "#define PYBIND11_VERSION_(MAJOR|MINOR|PATCH) ")
26
+
27
+ foreach(ver ${pybind11_version_defines})
28
+ if(ver MATCHES [[#define PYBIND11_VERSION_(MAJOR|MINOR|PATCH) +([^ ]+)$]])
29
+ set(PYBIND11_VERSION_${CMAKE_MATCH_1} "${CMAKE_MATCH_2}")
30
+ endif()
31
+ endforeach()
32
+
33
+ if(PYBIND11_VERSION_PATCH MATCHES [[\.([a-zA-Z0-9]+)$]])
34
+ set(pybind11_VERSION_TYPE "${CMAKE_MATCH_1}")
35
+ endif()
36
+ string(REGEX MATCH "^[0-9]+" PYBIND11_VERSION_PATCH "${PYBIND11_VERSION_PATCH}")
37
+
38
+ project(
39
+ pybind11
40
+ LANGUAGES CXX
41
+ VERSION "${PYBIND11_VERSION_MAJOR}.${PYBIND11_VERSION_MINOR}.${PYBIND11_VERSION_PATCH}")
42
+
43
+ # Standard includes
44
+ include(GNUInstallDirs)
45
+ include(CMakePackageConfigHelpers)
46
+ include(CMakeDependentOption)
47
+
48
+ if(NOT pybind11_FIND_QUIETLY)
49
+ message(STATUS "pybind11 v${pybind11_VERSION} ${pybind11_VERSION_TYPE}")
50
+ endif()
51
+
52
+ # Check if pybind11 is being used directly or via add_subdirectory
53
+ if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
54
+ ### Warn if not an out-of-source builds
55
+ if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR)
56
+ set(lines
57
+ "You are building in-place. If that is not what you intended to "
58
+ "do, you can clean the source directory with:\n"
59
+ "rm -r CMakeCache.txt CMakeFiles/ cmake_uninstall.cmake pybind11Config.cmake "
60
+ "pybind11ConfigVersion.cmake tests/CMakeFiles/\n")
61
+ message(AUTHOR_WARNING ${lines})
62
+ endif()
63
+
64
+ set(PYBIND11_MASTER_PROJECT ON)
65
+
66
+ message(STATUS "CMake ${CMAKE_VERSION}")
67
+
68
+ if(DEFINED SKBUILD AND DEFINED ENV{PYBIND11_GLOBAL_SDIST})
69
+ message(
70
+ FATAL_ERROR
71
+ "PYBIND11_GLOBAL_SDIST is not supported, use nox -s build_global or a pybind11-global SDist instead."
72
+ )
73
+ endif()
74
+
75
+ if(CMAKE_CXX_STANDARD)
76
+ set(CMAKE_CXX_EXTENSIONS OFF)
77
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
78
+ endif()
79
+
80
+ set(pybind11_system "")
81
+
82
+ set_property(GLOBAL PROPERTY USE_FOLDERS ON)
83
+ if(CMAKE_VERSION VERSION_LESS "3.18")
84
+ set(_pybind11_findpython_default OFF)
85
+ else()
86
+ set(_pybind11_findpython_default ON)
87
+ endif()
88
+ else()
89
+ set(PYBIND11_MASTER_PROJECT OFF)
90
+ set(pybind11_system SYSTEM)
91
+ set(_pybind11_findpython_default COMPAT)
92
+ endif()
93
+
94
+ # Options
95
+ option(PYBIND11_INSTALL "Install pybind11 header files?" ${PYBIND11_MASTER_PROJECT})
96
+ option(PYBIND11_TEST "Build pybind11 test suite?" ${PYBIND11_MASTER_PROJECT})
97
+ option(PYBIND11_NOPYTHON "Disable search for Python" OFF)
98
+ option(PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION
99
+ "To enforce that a handle_type_name<> specialization exists" OFF)
100
+ option(PYBIND11_SIMPLE_GIL_MANAGEMENT
101
+ "Use simpler GIL management logic that does not support disassociation" OFF)
102
+ set(PYBIND11_INTERNALS_VERSION
103
+ ""
104
+ CACHE STRING "Override the ABI version, may be used to enable the unstable ABI.")
105
+ option(PYBIND11_USE_CROSSCOMPILING "Respect CMAKE_CROSSCOMPILING" OFF)
106
+
107
+ if(PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION)
108
+ add_compile_definitions(PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION)
109
+ endif()
110
+ if(PYBIND11_SIMPLE_GIL_MANAGEMENT)
111
+ add_compile_definitions(PYBIND11_SIMPLE_GIL_MANAGEMENT)
112
+ endif()
113
+
114
+ cmake_dependent_option(
115
+ USE_PYTHON_INCLUDE_DIR
116
+ "Install pybind11 headers in Python include directory instead of default installation prefix"
117
+ OFF "PYBIND11_INSTALL" OFF)
118
+
119
+ set(PYBIND11_FINDPYTHON
120
+ ${_pybind11_findpython_default}
121
+ CACHE STRING "Force new FindPython - NEW, OLD, COMPAT")
122
+
123
+ if(PYBIND11_MASTER_PROJECT)
124
+
125
+ # Allow PYTHON_EXECUTABLE if in FINDPYTHON mode and building pybind11's tests
126
+ # (makes transition easier while we support both modes).
127
+ if(PYBIND11_FINDPYTHON
128
+ AND DEFINED PYTHON_EXECUTABLE
129
+ AND NOT DEFINED Python_EXECUTABLE)
130
+ set(Python_EXECUTABLE "${PYTHON_EXECUTABLE}")
131
+ endif()
132
+
133
+ # This is a shortcut that is primarily for the venv cmake preset,
134
+ # but can be used to quickly setup tests manually, too
135
+ set(PYBIND11_CREATE_WITH_UV
136
+ ""
137
+ CACHE STRING "Create a virtualenv if it doesn't exist")
138
+
139
+ if(NOT PYBIND11_CREATE_WITH_UV STREQUAL "")
140
+ set(Python_ROOT_DIR "${CMAKE_CURRENT_BINARY_DIR}/.venv")
141
+ if(EXISTS "${Python_ROOT_DIR}")
142
+ if(EXISTS "${CMAKE_BINARY_DIR}/CMakeCache.txt")
143
+ message(STATUS "Using existing venv at ${Python_ROOT_DIR}, remove or --fresh to recreate")
144
+ else()
145
+ # --fresh used to remove the cache
146
+ file(REMOVE_RECURSE "${CMAKE_CURRENT_BINARY_DIR}/.venv")
147
+ endif()
148
+ endif()
149
+ if(NOT EXISTS "${Python_ROOT_DIR}")
150
+ find_program(UV uv REQUIRED)
151
+ # CMake 3.19+ would be able to use COMMAND_ERROR_IS_FATAL
152
+ message(
153
+ STATUS "Creating venv with ${UV} venv -p ${PYBIND11_CREATE_WITH_UV} '${Python_ROOT_DIR}'")
154
+ execute_process(COMMAND ${UV} venv -p ${PYBIND11_CREATE_WITH_UV} "${Python_ROOT_DIR}"
155
+ RESULT_VARIABLE _venv_result)
156
+ if(_venv_result AND NOT _venv_result EQUAL 0)
157
+ message(FATAL_ERROR "uv venv failed with '${_venv_result}'")
158
+ endif()
159
+ message(
160
+ STATUS
161
+ "Installing deps with ${UV} pip install -p '${Python_ROOT_DIR}' -r tests/requirements.txt"
162
+ )
163
+ execute_process(
164
+ COMMAND ${UV} pip install -p "${Python_ROOT_DIR}" -r
165
+ "${CMAKE_CURRENT_SOURCE_DIR}/tests/requirements.txt" RESULT_VARIABLE _pip_result)
166
+ if(_pip_result AND NOT _pip_result EQUAL 0)
167
+ message(FATAL_ERROR "uv pip install failed with '${_pip_result}'")
168
+ endif()
169
+ endif()
170
+ else()
171
+ if(NOT DEFINED Python3_EXECUTABLE
172
+ AND NOT DEFINED Python_EXECUTABLE
173
+ AND NOT DEFINED Python_ROOT_DIR
174
+ AND NOT DEFINED ENV{VIRTUALENV}
175
+ AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.venv")
176
+ message(STATUS "Autodetecting Python in virtual environment")
177
+ set(Python_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/.venv")
178
+ endif()
179
+ endif()
180
+ endif()
181
+
182
+ set(PYBIND11_HEADERS
183
+ include/pybind11/detail/argument_vector.h
184
+ include/pybind11/detail/class.h
185
+ include/pybind11/detail/common.h
186
+ include/pybind11/detail/cpp_conduit.h
187
+ include/pybind11/detail/descr.h
188
+ include/pybind11/detail/dynamic_raw_ptr_cast_if_possible.h
189
+ include/pybind11/detail/exception_translation.h
190
+ include/pybind11/detail/function_record_pyobject.h
191
+ include/pybind11/detail/holder_caster_foreign_helpers.h
192
+ include/pybind11/detail/init.h
193
+ include/pybind11/detail/internals.h
194
+ include/pybind11/detail/native_enum_data.h
195
+ include/pybind11/detail/pybind11_namespace_macros.h
196
+ include/pybind11/detail/struct_smart_holder.h
197
+ include/pybind11/detail/type_caster_base.h
198
+ include/pybind11/detail/typeid.h
199
+ include/pybind11/detail/using_smart_holder.h
200
+ include/pybind11/detail/value_and_holder.h
201
+ include/pybind11/attr.h
202
+ include/pybind11/buffer_info.h
203
+ include/pybind11/cast.h
204
+ include/pybind11/chrono.h
205
+ include/pybind11/common.h
206
+ include/pybind11/complex.h
207
+ include/pybind11/conduit/pybind11_conduit_v1.h
208
+ include/pybind11/conduit/pybind11_platform_abi_id.h
209
+ include/pybind11/conduit/wrap_include_python_h.h
210
+ include/pybind11/critical_section.h
211
+ include/pybind11/options.h
212
+ include/pybind11/eigen.h
213
+ include/pybind11/eigen/common.h
214
+ include/pybind11/eigen/matrix.h
215
+ include/pybind11/eigen/tensor.h
216
+ include/pybind11/embed.h
217
+ include/pybind11/eval.h
218
+ include/pybind11/gil.h
219
+ include/pybind11/gil_safe_call_once.h
220
+ include/pybind11/gil_simple.h
221
+ include/pybind11/iostream.h
222
+ include/pybind11/functional.h
223
+ include/pybind11/native_enum.h
224
+ include/pybind11/numpy.h
225
+ include/pybind11/operators.h
226
+ include/pybind11/pybind11.h
227
+ include/pybind11/pytypes.h
228
+ include/pybind11/subinterpreter.h
229
+ include/pybind11/stl.h
230
+ include/pybind11/stl_bind.h
231
+ include/pybind11/stl/filesystem.h
232
+ include/pybind11/trampoline_self_life_support.h
233
+ include/pybind11/type_caster_pyobject_ptr.h
234
+ include/pybind11/typing.h
235
+ include/pybind11/warnings.h)
236
+
237
+ # Compare with grep and warn if mismatched
238
+ if(PYBIND11_MASTER_PROJECT)
239
+ file(
240
+ GLOB_RECURSE _pybind11_header_check
241
+ LIST_DIRECTORIES false
242
+ RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}"
243
+ CONFIGURE_DEPENDS "include/pybind11/*.h")
244
+ set(_pybind11_here_only ${PYBIND11_HEADERS})
245
+ set(_pybind11_disk_only ${_pybind11_header_check})
246
+ list(REMOVE_ITEM _pybind11_here_only ${_pybind11_header_check})
247
+ list(REMOVE_ITEM _pybind11_disk_only ${PYBIND11_HEADERS})
248
+ if(_pybind11_here_only)
249
+ message(AUTHOR_WARNING "PYBIND11_HEADERS has extra files:" ${_pybind11_here_only})
250
+ endif()
251
+ if(_pybind11_disk_only)
252
+ message(AUTHOR_WARNING "PYBIND11_HEADERS is missing files:" ${_pybind11_disk_only})
253
+ endif()
254
+ endif()
255
+
256
+ list(TRANSFORM PYBIND11_HEADERS PREPEND "${CMAKE_CURRENT_SOURCE_DIR}/")
257
+
258
+ # Cache variable so this can be used in parent projects
259
+ set(pybind11_INCLUDE_DIR
260
+ "${CMAKE_CURRENT_LIST_DIR}/include"
261
+ CACHE INTERNAL "Directory where pybind11 headers are located")
262
+
263
+ # Backward compatible variable for add_subdirectory mode
264
+ if(NOT PYBIND11_MASTER_PROJECT)
265
+ set(PYBIND11_INCLUDE_DIR
266
+ "${pybind11_INCLUDE_DIR}"
267
+ CACHE INTERNAL "")
268
+ endif()
269
+
270
+ # Note: when creating targets, you cannot use if statements at configure time -
271
+ # you need generator expressions, because those will be placed in the target file.
272
+ # You can also place ifs *in* the Config.in, but not here.
273
+
274
+ # This section builds targets, but does *not* touch Python
275
+ # Non-IMPORT targets cannot be defined twice
276
+ if(NOT TARGET pybind11_headers)
277
+ # Build the headers-only target (no Python included):
278
+ # (long name used here to keep this from clashing in subdirectory mode)
279
+ add_library(pybind11_headers INTERFACE)
280
+ add_library(pybind11::pybind11_headers ALIAS pybind11_headers) # to match exported target
281
+ add_library(pybind11::headers ALIAS pybind11_headers) # easier to use/remember
282
+
283
+ target_include_directories(
284
+ pybind11_headers ${pybind11_system} INTERFACE $<BUILD_INTERFACE:${pybind11_INCLUDE_DIR}>
285
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
286
+
287
+ target_compile_features(pybind11_headers INTERFACE cxx_inheriting_constructors cxx_user_literals
288
+ cxx_right_angle_brackets)
289
+ if(NOT "${PYBIND11_INTERNALS_VERSION}" STREQUAL "")
290
+ target_compile_definitions(
291
+ pybind11_headers INTERFACE "PYBIND11_INTERNALS_VERSION=${PYBIND11_INTERNALS_VERSION}")
292
+ endif()
293
+ else()
294
+ # It is invalid to install a target twice, too.
295
+ set(PYBIND11_INSTALL OFF)
296
+ endif()
297
+
298
+ include("${CMAKE_CURRENT_SOURCE_DIR}/tools/pybind11Common.cmake")
299
+ # https://github.com/jtojnar/cmake-snips/#concatenating-paths-when-building-pkg-config-files
300
+ # TODO: cmake 3.20 adds the cmake_path() function, which obsoletes this snippet
301
+ include("${CMAKE_CURRENT_SOURCE_DIR}/tools/JoinPaths.cmake")
302
+
303
+ # Relative directory setting
304
+ if(USE_PYTHON_INCLUDE_DIR AND DEFINED Python_INCLUDE_DIRS)
305
+ file(RELATIVE_PATH CMAKE_INSTALL_INCLUDEDIR ${CMAKE_INSTALL_PREFIX} ${Python_INCLUDE_DIRS})
306
+ elseif(USE_PYTHON_INCLUDE_DIR AND DEFINED PYTHON_INCLUDE_DIR)
307
+ file(RELATIVE_PATH CMAKE_INSTALL_INCLUDEDIR ${CMAKE_INSTALL_PREFIX} ${PYTHON_INCLUDE_DIRS})
308
+ endif()
309
+
310
+ if(PYBIND11_INSTALL)
311
+ if(DEFINED SKBUILD_PROJECT_NAME AND SKBUILD_PROJECT_NAME STREQUAL "pybind11_global")
312
+ install(DIRECTORY ${pybind11_INCLUDE_DIR}/pybind11 DESTINATION "${SKBUILD_HEADERS_DIR}")
313
+ endif()
314
+ install(DIRECTORY ${pybind11_INCLUDE_DIR}/pybind11 DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
315
+ set(PYBIND11_CMAKECONFIG_INSTALL_DIR
316
+ "${CMAKE_INSTALL_DATAROOTDIR}/cmake/${PROJECT_NAME}"
317
+ CACHE STRING "install path for pybind11Config.cmake")
318
+
319
+ if(IS_ABSOLUTE "${CMAKE_INSTALL_INCLUDEDIR}")
320
+ set(pybind11_INCLUDEDIR "${CMAKE_INSTALL_FULL_INCLUDEDIR}")
321
+ else()
322
+ set(pybind11_INCLUDEDIR "\$\{PACKAGE_PREFIX_DIR\}/${CMAKE_INSTALL_INCLUDEDIR}")
323
+ endif()
324
+
325
+ configure_package_config_file(
326
+ tools/${PROJECT_NAME}Config.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
327
+ INSTALL_DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR})
328
+
329
+ # CMake natively supports header-only libraries
330
+ write_basic_package_version_file(
331
+ ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake
332
+ VERSION ${PROJECT_VERSION}
333
+ COMPATIBILITY AnyNewerVersion ARCH_INDEPENDENT)
334
+
335
+ install(
336
+ FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake
337
+ ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake
338
+ tools/FindPythonLibsNew.cmake
339
+ tools/pybind11Common.cmake
340
+ tools/pybind11Tools.cmake
341
+ tools/pybind11NewTools.cmake
342
+ tools/pybind11GuessPythonExtSuffix.cmake
343
+ DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR})
344
+
345
+ if(NOT PYBIND11_EXPORT_NAME)
346
+ set(PYBIND11_EXPORT_NAME "${PROJECT_NAME}Targets")
347
+ endif()
348
+
349
+ install(TARGETS pybind11_headers EXPORT "${PYBIND11_EXPORT_NAME}")
350
+
351
+ install(
352
+ EXPORT "${PYBIND11_EXPORT_NAME}"
353
+ NAMESPACE "pybind11::"
354
+ DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR})
355
+
356
+ # pkg-config support
357
+ if(NOT prefix_for_pc_file)
358
+ if(IS_ABSOLUTE "${CMAKE_INSTALL_DATAROOTDIR}")
359
+ set(prefix_for_pc_file "${CMAKE_INSTALL_PREFIX}")
360
+ else()
361
+ set(pc_datarootdir "${CMAKE_INSTALL_DATAROOTDIR}")
362
+ if(CMAKE_VERSION VERSION_LESS 3.20)
363
+ set(prefix_for_pc_file "\${pcfiledir}/..")
364
+ while(pc_datarootdir)
365
+ get_filename_component(pc_datarootdir "${pc_datarootdir}" DIRECTORY)
366
+ string(APPEND prefix_for_pc_file "/..")
367
+ endwhile()
368
+ else()
369
+ cmake_path(RELATIVE_PATH CMAKE_INSTALL_PREFIX BASE_DIRECTORY CMAKE_INSTALL_DATAROOTDIR
370
+ OUTPUT_VARIABLE prefix_for_pc_file)
371
+ endif()
372
+ endif()
373
+ endif()
374
+ join_paths(includedir_for_pc_file "\${prefix}" "${CMAKE_INSTALL_INCLUDEDIR}")
375
+ configure_file("${CMAKE_CURRENT_SOURCE_DIR}/tools/pybind11.pc.in"
376
+ "${CMAKE_CURRENT_BINARY_DIR}/pybind11.pc" @ONLY)
377
+ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/pybind11.pc"
378
+ DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig/")
379
+
380
+ # When building a wheel, include __init__.py's for modules
381
+ # (see https://github.com/pybind/pybind11/pull/5552)
382
+ if(DEFINED SKBUILD_PROJECT_NAME AND SKBUILD_PROJECT_NAME STREQUAL "pybind11")
383
+ file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/empty")
384
+ file(TOUCH "${CMAKE_CURRENT_BINARY_DIR}/empty/__init__.py")
385
+ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/empty/__init__.py"
386
+ DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/")
387
+ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/empty/__init__.py"
388
+ DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig/")
389
+ endif()
390
+
391
+ # Uninstall target
392
+ if(PYBIND11_MASTER_PROJECT)
393
+ configure_file("${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake_uninstall.cmake.in"
394
+ "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY)
395
+
396
+ add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P
397
+ ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake)
398
+ endif()
399
+ endif()
400
+
401
+ # BUILD_TESTING takes priority, but only if this is the master project
402
+ if(PYBIND11_MASTER_PROJECT AND DEFINED BUILD_TESTING)
403
+ if(BUILD_TESTING)
404
+ if(_pybind11_nopython)
405
+ message(FATAL_ERROR "Cannot activate tests in NOPYTHON mode")
406
+ else()
407
+ add_subdirectory(tests)
408
+ endif()
409
+ endif()
410
+ else()
411
+ if(PYBIND11_TEST)
412
+ if(_pybind11_nopython)
413
+ message(FATAL_ERROR "Cannot activate tests in NOPYTHON mode")
414
+ else()
415
+ add_subdirectory(tests)
416
+ endif()
417
+ endif()
418
+ endif()
419
+
420
+ # Better symmetry with find_package(pybind11 CONFIG) mode.
421
+ if(NOT PYBIND11_MASTER_PROJECT)
422
+ set(pybind11_FOUND
423
+ TRUE
424
+ CACHE INTERNAL "True if pybind11 and all required components found on the system")
425
+ endif()
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/CMakePresets.json ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": 6,
3
+ "configurePresets": [
4
+ {
5
+ "name": "default",
6
+ "displayName": "Default",
7
+ "binaryDir": "build",
8
+ "generator": "Ninja",
9
+ "errors": {
10
+ "dev": true,
11
+ "deprecated": true
12
+ },
13
+ "cacheVariables": {
14
+ "CMAKE_BUILD_TYPE": "Debug",
15
+ "CMAKE_EXPORT_COMPILE_COMMANDS": true,
16
+ "DOWNLOAD_CATCH": true,
17
+ "DOWNLOAD_EIGEN": true,
18
+ "PYBIND11_FINDPYTHON": "NEW",
19
+ "PYBIND11_WERROR": true,
20
+ "CMAKE_COLOR_DIAGNOSTICS": true
21
+ }
22
+ },
23
+ {
24
+ "name": "venv",
25
+ "displayName": "Venv",
26
+ "inherits": "default",
27
+ "cacheVariables": {
28
+ "PYBIND11_CREATE_WITH_UV": "python3",
29
+ "Python_ROOT_DIR": ".venv"
30
+ }
31
+ },
32
+ {
33
+ "name": "tidy",
34
+ "displayName": "Clang-tidy",
35
+ "inherits": "default",
36
+ "binaryDir": "build-tidy",
37
+ "cacheVariables": {
38
+ "CMAKE_CXX_CLANG_TIDY": "clang-tidy;--use-color;--warnings-as-errors=*",
39
+ "CMAKE_CXX_STANDARD": "17"
40
+ }
41
+ }
42
+ ],
43
+ "buildPresets": [
44
+ {
45
+ "name": "default",
46
+ "displayName": "Default Build",
47
+ "configurePreset": "default"
48
+ },
49
+ {
50
+ "name": "venv",
51
+ "displayName": "Venv Build",
52
+ "configurePreset": "venv"
53
+ },
54
+ {
55
+ "name": "tidy",
56
+ "displayName": "Clang-tidy Build",
57
+ "configurePreset": "tidy",
58
+ "nativeToolOptions": ["-k0"]
59
+ },
60
+ {
61
+ "name": "tests",
62
+ "displayName": "Tests (for workflow)",
63
+ "configurePreset": "default",
64
+ "targets": ["pytest", "cpptest", "test_cmake_build", "test_cross_module_rtti"]
65
+ },
66
+ {
67
+ "name": "testsvenv",
68
+ "displayName": "Tests Venv (for workflow)",
69
+ "configurePreset": "venv",
70
+ "targets": ["pytest", "cpptest", "test_cmake_build", "test_cross_module_rtti"]
71
+ }
72
+ ],
73
+ "workflowPresets": [
74
+ {
75
+ "name": "default",
76
+ "displayName": "Default Workflow",
77
+ "steps": [
78
+ { "type": "configure", "name": "default" },
79
+ { "type": "build", "name": "default" },
80
+ { "type": "build", "name": "tests" }
81
+ ]
82
+ },
83
+ {
84
+ "name": "venv",
85
+ "displayName": "Default Workflow",
86
+ "steps": [
87
+ { "type": "configure", "name": "venv" },
88
+ { "type": "build", "name": "venv" },
89
+ { "type": "build", "name": "testsvenv" }
90
+ ]
91
+ }
92
+ ]
93
+ }
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/LICENSE ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>, All rights reserved.
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are met:
5
+
6
+ 1. Redistributions of source code must retain the above copyright notice, this
7
+ list of conditions and the following disclaimer.
8
+
9
+ 2. Redistributions in binary form must reproduce the above copyright notice,
10
+ this list of conditions and the following disclaimer in the documentation
11
+ and/or other materials provided with the distribution.
12
+
13
+ 3. Neither the name of the copyright holder nor the names of its contributors
14
+ may be used to endorse or promote products derived from this software
15
+ without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ Please also refer to the file .github/CONTRIBUTING.md, which clarifies licensing of
29
+ external contributions to this project including patches, pull requests, etc.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/README.rst ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. figure:: https://github.com/pybind/pybind11/raw/master/docs/pybind11-logo.png
2
+ :alt: pybind11 logo
3
+
4
+ **pybind11 (v3) — Seamless interoperability between C++ and Python**
5
+
6
+ |Latest Documentation Status| |Stable Documentation Status| |Gitter chat| |GitHub Discussions|
7
+
8
+ |CI| |Build status| |SPEC 4 — Using and Creating Nightly Wheels|
9
+
10
+ |Repology| |PyPI package| |Conda-forge| |Python Versions|
11
+
12
+ `Setuptools example <https://github.com/pybind/python_example>`_
13
+ • `Scikit-build example <https://github.com/pybind/scikit_build_example>`_
14
+ • `CMake example <https://github.com/pybind/cmake_example>`_
15
+
16
+ .. start
17
+
18
+
19
+ **pybind11** is a lightweight header-only library that exposes C++ types
20
+ in Python and vice versa, mainly to create Python bindings of existing
21
+ C++ code. Its goals and syntax are similar to the excellent
22
+ `Boost.Python <http://www.boost.org/doc/libs/1_58_0/libs/python/doc/>`_
23
+ library by David Abrahams: to minimize boilerplate code in traditional
24
+ extension modules by inferring type information using compile-time
25
+ introspection.
26
+
27
+ The main issue with Boost.Python—and the reason for creating such a
28
+ similar project—is Boost. Boost is an enormously large and complex suite
29
+ of utility libraries that works with almost every C++ compiler in
30
+ existence. This compatibility has its cost: arcane template tricks and
31
+ workarounds are necessary to support the oldest and buggiest of compiler
32
+ specimens. Now that C++11-compatible compilers are widely available,
33
+ this heavy machinery has become an excessively large and unnecessary
34
+ dependency.
35
+
36
+ Think of this library as a tiny self-contained version of Boost.Python
37
+ with everything stripped away that isn't relevant for binding
38
+ generation. Without comments, the core header files only require ~4K
39
+ lines of code and depend on Python (CPython 3.8+, PyPy, or GraalPy) and the C++
40
+ standard library. This compact implementation was possible thanks to some C++11
41
+ language features (specifically: tuples, lambda functions and variadic
42
+ templates). Since its creation, this library has grown beyond Boost.Python in
43
+ many ways, leading to dramatically simpler binding code in many common
44
+ situations.
45
+
46
+ Tutorial and reference documentation is provided at
47
+ `pybind11.readthedocs.io <https://pybind11.readthedocs.io/en/latest>`_.
48
+ A PDF version of the manual is available
49
+ `here <https://pybind11.readthedocs.io/_/downloads/en/latest/pdf/>`_.
50
+ And the source code is always available at
51
+ `github.com/pybind/pybind11 <https://github.com/pybind/pybind11>`_.
52
+
53
+
54
+ Core features
55
+ -------------
56
+
57
+
58
+ pybind11 can map the following core C++ features to Python:
59
+
60
+ - Functions accepting and returning custom data structures per value,
61
+ reference, or pointer
62
+ - Instance methods and static methods
63
+ - Overloaded functions
64
+ - Instance attributes and static attributes
65
+ - Arbitrary exception types
66
+ - Enumerations
67
+ - Callbacks
68
+ - Iterators and ranges
69
+ - Custom operators
70
+ - Single and multiple inheritance
71
+ - STL data structures
72
+ - Smart pointers with reference counting like ``std::shared_ptr``
73
+ - Internal references with correct reference counting
74
+ - C++ classes with virtual (and pure virtual) methods can be extended
75
+ in Python
76
+ - Integrated NumPy support (NumPy 2 requires pybind11 2.12+)
77
+
78
+ Goodies
79
+ -------
80
+
81
+ In addition to the core functionality, pybind11 provides some extra
82
+ goodies:
83
+
84
+ - CPython 3.8+, PyPy3 7.3.17+, and GraalPy 24.1+ are supported with an
85
+ implementation-agnostic interface (see older versions for older CPython
86
+ and PyPy versions).
87
+
88
+ - It is possible to bind C++11 lambda functions with captured
89
+ variables. The lambda capture data is stored inside the resulting
90
+ Python function object.
91
+
92
+ - pybind11 uses C++11 move constructors and move assignment operators
93
+ whenever possible to efficiently transfer custom data types.
94
+
95
+ - It's easy to expose the internal storage of custom data types through
96
+ Pythons' buffer protocols. This is handy e.g. for fast conversion
97
+ between C++ matrix classes like Eigen and NumPy without expensive
98
+ copy operations.
99
+
100
+ - pybind11 can automatically vectorize functions so that they are
101
+ transparently applied to all entries of one or more NumPy array
102
+ arguments.
103
+
104
+ - Python's slice-based access and assignment operations can be
105
+ supported with just a few lines of code.
106
+
107
+ - Everything is contained in just a few header files; there is no need
108
+ to link against any additional libraries.
109
+
110
+ - Binaries are generally smaller by a factor of at least 2 compared to
111
+ equivalent bindings generated by Boost.Python. A recent pybind11
112
+ conversion of PyRosetta, an enormous Boost.Python binding project,
113
+ `reported <https://graylab.jhu.edu/Sergey/2016.RosettaCon/PyRosetta-4.pdf>`_
114
+ a binary size reduction of **5.4x** and compile time reduction by
115
+ **5.8x**.
116
+
117
+ - Function signatures are precomputed at compile time (using
118
+ ``constexpr``), leading to smaller binaries.
119
+
120
+ - With little extra effort, C++ types can be pickled and unpickled
121
+ similar to regular Python objects.
122
+
123
+ Supported compilers
124
+ -------------------
125
+
126
+ 1. Clang/LLVM 3.3 or newer (for Apple Xcode's clang, this is 5.0.0 or
127
+ newer)
128
+ 2. GCC 4.8 or newer
129
+ 3. Microsoft Visual Studio 2022 or newer (2019 probably works, but was dropped in CI)
130
+ 4. Intel classic C++ compiler 18 or newer (ICC 20.2 tested in CI)
131
+ 5. Cygwin/GCC (previously tested on 2.5.1)
132
+ 6. NVCC (CUDA 11.0 tested in CI)
133
+ 7. NVIDIA PGI (20.9 tested in CI)
134
+
135
+ Supported Platforms
136
+ -------------------
137
+
138
+ * Windows, Linux, macOS, and iOS
139
+ * CPython 3.8+, Pyodide, PyPy, and GraalPy
140
+ * C++11, C++14, C++17, C++20, and C++23
141
+
142
+ About
143
+ -----
144
+
145
+ This project was created by `Wenzel
146
+ Jakob <http://rgl.epfl.ch/people/wjakob>`_. Significant features and/or
147
+ improvements to the code were contributed by
148
+ Jonas Adler,
149
+ Lori A. Burns,
150
+ Sylvain Corlay,
151
+ Eric Cousineau,
152
+ Aaron Gokaslan,
153
+ Ralf Grosse-Kunstleve,
154
+ Trent Houliston,
155
+ Axel Huebl,
156
+ @hulucc,
157
+ Yannick Jadoul,
158
+ Sergey Lyskov,
159
+ Johan Mabille,
160
+ Tomasz Miąsko,
161
+ Dean Moldovan,
162
+ Ben Pritchard,
163
+ Jason Rhinelander,
164
+ Boris Schäling,
165
+ Pim Schellart,
166
+ Henry Schreiner,
167
+ Ivan Smirnov,
168
+ Dustin Spicuzza,
169
+ Boris Staletic,
170
+ Ethan Steinberg,
171
+ Patrick Stewart,
172
+ Ivor Wanders,
173
+ and
174
+ Xiaofei Wang.
175
+
176
+ We thank Google for a generous financial contribution to the continuous
177
+ integration infrastructure used by this project.
178
+
179
+
180
+ Contributing
181
+ ~~~~~~~~~~~~
182
+
183
+ See the `contributing
184
+ guide <https://github.com/pybind/pybind11/blob/master/.github/CONTRIBUTING.md>`_
185
+ for information on building and contributing to pybind11.
186
+
187
+ License
188
+ ~~~~~~~
189
+
190
+ pybind11 is provided under a BSD-style license that can be found in the
191
+ `LICENSE <https://github.com/pybind/pybind11/blob/master/LICENSE>`_
192
+ file. By using, distributing, or contributing to this project, you agree
193
+ to the terms and conditions of this license.
194
+
195
+ .. |Latest Documentation Status| image:: https://readthedocs.org/projects/pybind11/badge?version=latest
196
+ :target: http://pybind11.readthedocs.org/en/latest
197
+ .. |Stable Documentation Status| image:: https://img.shields.io/badge/docs-stable-blue.svg
198
+ :target: http://pybind11.readthedocs.org/en/stable
199
+ .. |Gitter chat| image:: https://img.shields.io/gitter/room/gitterHQ/gitter.svg
200
+ :target: https://gitter.im/pybind/Lobby
201
+ .. |CI| image:: https://github.com/pybind/pybind11/workflows/CI/badge.svg
202
+ :target: https://github.com/pybind/pybind11/actions
203
+ .. |Build status| image:: https://ci.appveyor.com/api/projects/status/riaj54pn4h08xy40?svg=true
204
+ :target: https://ci.appveyor.com/project/wjakob/pybind11
205
+ .. |PyPI package| image:: https://img.shields.io/pypi/v/pybind11.svg
206
+ :target: https://pypi.org/project/pybind11/
207
+ .. |Conda-forge| image:: https://img.shields.io/conda/vn/conda-forge/pybind11.svg
208
+ :target: https://github.com/conda-forge/pybind11-feedstock
209
+ .. |Repology| image:: https://repology.org/badge/latest-versions/python:pybind11.svg
210
+ :target: https://repology.org/project/python:pybind11/versions
211
+ .. |Python Versions| image:: https://img.shields.io/pypi/pyversions/pybind11.svg
212
+ :target: https://pypi.org/project/pybind11/
213
+ .. |GitHub Discussions| image:: https://img.shields.io/static/v1?label=Discussions&message=Ask&color=blue&logo=github
214
+ :target: https://github.com/pybind/pybind11/discussions
215
+ .. |SPEC 4 — Using and Creating Nightly Wheels| image:: https://img.shields.io/badge/SPEC-4-green?labelColor=%23004811&color=%235CA038
216
+ :target: https://scientific-python.org/specs/spec-0004/
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/SECURITY.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ Security updates are applied only to the latest release.
6
+
7
+ ## Reporting a Vulnerability
8
+
9
+ If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released.
10
+
11
+ Please disclose it at [security advisory](https://github.com/pybind/pybind11/security/advisories/new).
12
+
13
+ This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/Doxyfile ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PROJECT_NAME = pybind11
2
+ INPUT = ../include/pybind11/
3
+ RECURSIVE = YES
4
+
5
+ GENERATE_HTML = NO
6
+ GENERATE_LATEX = NO
7
+ GENERATE_XML = YES
8
+ XML_OUTPUT = .build/doxygenxml
9
+ XML_PROGRAMLISTING = YES
10
+
11
+ MACRO_EXPANSION = YES
12
+ EXPAND_ONLY_PREDEF = YES
13
+ EXPAND_AS_DEFINED = PYBIND11_RUNTIME_EXCEPTION
14
+
15
+ ALIASES = "rst=\verbatim embed:rst"
16
+ ALIASES += "endrst=\endverbatim"
17
+
18
+ QUIET = YES
19
+ WARNINGS = YES
20
+ WARN_IF_UNDOCUMENTED = NO
21
+ PREDEFINED = PYBIND11_NOINLINE
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/Makefile ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Makefile for Sphinx documentation
2
+ #
3
+
4
+ # You can set these variables from the command line.
5
+ SPHINXOPTS =
6
+ SPHINXBUILD = sphinx-build
7
+ PAPER =
8
+ BUILDDIR = .build
9
+
10
+ # User-friendly check for sphinx-build
11
+ ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
12
+ $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
13
+ endif
14
+
15
+ # Internal variables.
16
+ PAPEROPT_a4 = -D latex_paper_size=a4
17
+ PAPEROPT_letter = -D latex_paper_size=letter
18
+ ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
19
+ # the i18n builder cannot share the environment and doctrees with the others
20
+ I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
21
+
22
+ .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext
23
+
24
+ help:
25
+ @echo "Please use \`make <target>' where <target> is one of"
26
+ @echo " html to make standalone HTML files"
27
+ @echo " dirhtml to make HTML files named index.html in directories"
28
+ @echo " singlehtml to make a single large HTML file"
29
+ @echo " pickle to make pickle files"
30
+ @echo " json to make JSON files"
31
+ @echo " htmlhelp to make HTML files and a HTML help project"
32
+ @echo " qthelp to make HTML files and a qthelp project"
33
+ @echo " applehelp to make an Apple Help Book"
34
+ @echo " devhelp to make HTML files and a Devhelp project"
35
+ @echo " epub to make an epub"
36
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
37
+ @echo " latexpdf to make LaTeX files and run them through pdflatex"
38
+ @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
39
+ @echo " text to make text files"
40
+ @echo " man to make manual pages"
41
+ @echo " texinfo to make Texinfo files"
42
+ @echo " info to make Texinfo files and run them through makeinfo"
43
+ @echo " gettext to make PO message catalogs"
44
+ @echo " changes to make an overview of all changed/added/deprecated items"
45
+ @echo " xml to make Docutils-native XML files"
46
+ @echo " pseudoxml to make pseudoxml-XML files for display purposes"
47
+ @echo " linkcheck to check all external links for integrity"
48
+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"
49
+ @echo " coverage to run coverage check of the documentation (if enabled)"
50
+
51
+ clean:
52
+ rm -rf $(BUILDDIR)/*
53
+
54
+ html:
55
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
56
+ @echo
57
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
58
+
59
+ dirhtml:
60
+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
61
+ @echo
62
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
63
+
64
+ singlehtml:
65
+ $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
66
+ @echo
67
+ @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
68
+
69
+ pickle:
70
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
71
+ @echo
72
+ @echo "Build finished; now you can process the pickle files."
73
+
74
+ json:
75
+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
76
+ @echo
77
+ @echo "Build finished; now you can process the JSON files."
78
+
79
+ htmlhelp:
80
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
81
+ @echo
82
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
83
+ ".hhp project file in $(BUILDDIR)/htmlhelp."
84
+
85
+ qthelp:
86
+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
87
+ @echo
88
+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \
89
+ ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
90
+ @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pybind11.qhcp"
91
+ @echo "To view the help file:"
92
+ @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pybind11.qhc"
93
+
94
+ applehelp:
95
+ $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
96
+ @echo
97
+ @echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
98
+ @echo "N.B. You won't be able to view it unless you put it in" \
99
+ "~/Library/Documentation/Help or install it in your application" \
100
+ "bundle."
101
+
102
+ devhelp:
103
+ $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
104
+ @echo
105
+ @echo "Build finished."
106
+ @echo "To view the help file:"
107
+ @echo "# mkdir -p $$HOME/.local/share/devhelp/pybind11"
108
+ @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pybind11"
109
+ @echo "# devhelp"
110
+
111
+ epub:
112
+ $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
113
+ @echo
114
+ @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
115
+
116
+ latex:
117
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
118
+ @echo
119
+ @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
120
+ @echo "Run \`make' in that directory to run these through (pdf)latex" \
121
+ "(use \`make latexpdf' here to do that automatically)."
122
+
123
+ latexpdf:
124
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
125
+ @echo "Running LaTeX files through pdflatex..."
126
+ $(MAKE) -C $(BUILDDIR)/latex all-pdf
127
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
128
+
129
+ latexpdfja:
130
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
131
+ @echo "Running LaTeX files through platex and dvipdfmx..."
132
+ $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
133
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
134
+
135
+ text:
136
+ $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
137
+ @echo
138
+ @echo "Build finished. The text files are in $(BUILDDIR)/text."
139
+
140
+ man:
141
+ $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
142
+ @echo
143
+ @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
144
+
145
+ texinfo:
146
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
147
+ @echo
148
+ @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
149
+ @echo "Run \`make' in that directory to run these through makeinfo" \
150
+ "(use \`make info' here to do that automatically)."
151
+
152
+ info:
153
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
154
+ @echo "Running Texinfo files through makeinfo..."
155
+ make -C $(BUILDDIR)/texinfo info
156
+ @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
157
+
158
+ gettext:
159
+ $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
160
+ @echo
161
+ @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
162
+
163
+ changes:
164
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
165
+ @echo
166
+ @echo "The overview file is in $(BUILDDIR)/changes."
167
+
168
+ linkcheck:
169
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
170
+ @echo
171
+ @echo "Link check complete; look for any errors in the above output " \
172
+ "or in $(BUILDDIR)/linkcheck/output.txt."
173
+
174
+ doctest:
175
+ $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
176
+ @echo "Testing of doctests in the sources finished, look at the " \
177
+ "results in $(BUILDDIR)/doctest/output.txt."
178
+
179
+ coverage:
180
+ $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
181
+ @echo "Testing of coverage in the sources finished, look at the " \
182
+ "results in $(BUILDDIR)/coverage/python.txt."
183
+
184
+ xml:
185
+ $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
186
+ @echo
187
+ @echo "Build finished. The XML files are in $(BUILDDIR)/xml."
188
+
189
+ pseudoxml:
190
+ $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
191
+ @echo
192
+ @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/_static/css/custom.css ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ .highlight .go {
2
+ color: #707070;
3
+ }
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/chrono.rst ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Chrono
2
+ ======
3
+
4
+ When including the additional header file :file:`pybind11/chrono.h` conversions
5
+ from C++11 chrono datatypes to python datetime objects are automatically enabled.
6
+ This header also enables conversions of python floats (often from sources such
7
+ as ``time.monotonic()``, ``time.perf_counter()`` and ``time.process_time()``)
8
+ into durations.
9
+
10
+ An overview of clocks in C++11
11
+ ------------------------------
12
+
13
+ A point of confusion when using these conversions is the differences between
14
+ clocks provided in C++11. There are three clock types defined by the C++11
15
+ standard and users can define their own if needed. Each of these clocks have
16
+ different properties and when converting to and from python will give different
17
+ results.
18
+
19
+ The first clock defined by the standard is ``std::chrono::system_clock``. This
20
+ clock measures the current date and time. However, this clock changes with to
21
+ updates to the operating system time. For example, if your time is synchronised
22
+ with a time server this clock will change. This makes this clock a poor choice
23
+ for timing purposes but good for measuring the wall time.
24
+
25
+ The second clock defined in the standard is ``std::chrono::steady_clock``.
26
+ This clock ticks at a steady rate and is never adjusted. This makes it excellent
27
+ for timing purposes, however the value in this clock does not correspond to the
28
+ current date and time. Often this clock will be the amount of time your system
29
+ has been on, although it does not have to be. This clock will never be the same
30
+ clock as the system clock as the system clock can change but steady clocks
31
+ cannot.
32
+
33
+ The third clock defined in the standard is ``std::chrono::high_resolution_clock``.
34
+ This clock is the clock that has the highest resolution out of the clocks in the
35
+ system. It is normally a typedef to either the system clock or the steady clock
36
+ but can be its own independent clock. This is important as when using these
37
+ conversions as the types you get in python for this clock might be different
38
+ depending on the system.
39
+ If it is a typedef of the system clock, python will get datetime objects, but if
40
+ it is a different clock they will be timedelta objects.
41
+
42
+ Provided conversions
43
+ --------------------
44
+
45
+ .. rubric:: C++ to Python
46
+
47
+ - ``std::chrono::system_clock::time_point`` → ``datetime.datetime``
48
+ System clock times are converted to python datetime instances. They are
49
+ in the local timezone, but do not have any timezone information attached
50
+ to them (they are naive datetime objects).
51
+
52
+ - ``std::chrono::duration`` → ``datetime.timedelta``
53
+ Durations are converted to timedeltas, any precision in the duration
54
+ greater than microseconds is lost by rounding towards zero.
55
+
56
+ - ``std::chrono::[other_clocks]::time_point`` → ``datetime.timedelta``
57
+ Any clock time that is not the system clock is converted to a time delta.
58
+ This timedelta measures the time from the clocks epoch to now.
59
+
60
+ .. rubric:: Python to C++
61
+
62
+ - ``datetime.datetime`` or ``datetime.date`` or ``datetime.time`` → ``std::chrono::system_clock::time_point``
63
+ Date/time objects are converted into system clock timepoints. Any
64
+ timezone information is ignored and the type is treated as a naive
65
+ object.
66
+
67
+ - ``datetime.timedelta`` → ``std::chrono::duration``
68
+ Time delta are converted into durations with microsecond precision.
69
+
70
+ - ``datetime.timedelta`` → ``std::chrono::[other_clocks]::time_point``
71
+ Time deltas that are converted into clock timepoints are treated as
72
+ the amount of time from the start of the clocks epoch.
73
+
74
+ - ``float`` → ``std::chrono::duration``
75
+ Floats that are passed to C++ as durations be interpreted as a number of
76
+ seconds. These will be converted to the duration using ``duration_cast``
77
+ from the float.
78
+
79
+ - ``float`` → ``std::chrono::[other_clocks]::time_point``
80
+ Floats that are passed to C++ as time points will be interpreted as the
81
+ number of seconds from the start of the clocks epoch.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/custom.rst ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _custom_type_caster:
2
+
3
+ Custom type casters
4
+ ===================
5
+
6
+ Some applications may prefer custom type casters that convert between existing
7
+ Python types and C++ types, similar to the ``list`` ↔ ``std::vector``
8
+ and ``dict`` ↔ ``std::map`` conversions which are built into pybind11.
9
+ Implementing custom type casters is fairly advanced usage.
10
+ While it is recommended to use the pybind11 API as much as possible, more complex examples may
11
+ require familiarity with the intricacies of the Python C API.
12
+ You can refer to the `Python/C API Reference Manual <https://docs.python.org/3/c-api/index.html>`_
13
+ for more information.
14
+
15
+ The following snippets demonstrate how this works for a very simple ``Point2D`` type.
16
+ We want this type to be convertible to C++ from Python types implementing the
17
+ ``Sequence`` protocol and having two elements of type ``float``.
18
+ When returned from C++ to Python, it should be converted to a Python ``tuple[float, float]``.
19
+ For this type we could provide Python bindings for different arithmetic functions implemented
20
+ in C++ (here demonstrated by a simple ``negate`` function).
21
+
22
+ ..
23
+ PLEASE KEEP THE CODE BLOCKS IN SYNC WITH
24
+ tests/test_docs_advanced_cast_custom.cpp
25
+ tests/test_docs_advanced_cast_custom.py
26
+ Ideally, change the test, run pre-commit (incl. clang-format),
27
+ then copy the changed code back here.
28
+ Also use TEST_SUBMODULE in tests, but PYBIND11_MODULE in docs.
29
+
30
+ .. code-block:: cpp
31
+
32
+ namespace user_space {
33
+
34
+ struct Point2D {
35
+ double x;
36
+ double y;
37
+ };
38
+
39
+ Point2D negate(const Point2D &point) { return Point2D{-point.x, -point.y}; }
40
+
41
+ } // namespace user_space
42
+
43
+
44
+ The following Python snippet demonstrates the intended usage of ``negate`` from the Python side:
45
+
46
+ .. code-block:: python
47
+
48
+ from my_math_module import docs_advanced_cast_custom as m
49
+
50
+ point1 = [1.0, -1.0]
51
+ point2 = m.negate(point1)
52
+ assert point2 == (-1.0, 1.0)
53
+
54
+ To register the necessary conversion routines, it is necessary to add an
55
+ instantiation of the ``pybind11::detail::type_caster<T>`` template.
56
+ Although this is an implementation detail, adding an instantiation of this
57
+ type is explicitly allowed.
58
+
59
+ .. code-block:: cpp
60
+
61
+ namespace pybind11 {
62
+ namespace detail {
63
+
64
+ template <>
65
+ struct type_caster<user_space::Point2D> {
66
+ // This macro inserts a lot of boilerplate code and sets the type hint.
67
+ // `io_name` is used to specify different type hints for arguments and return values.
68
+ // The signature of our negate function would then look like:
69
+ // `negate(Sequence[float]) -> tuple[float, float]`
70
+ PYBIND11_TYPE_CASTER(user_space::Point2D, io_name("Sequence[float]", "tuple[float, float]"));
71
+
72
+ // C++ -> Python: convert `Point2D` to `tuple[float, float]`. The second and third arguments
73
+ // are used to indicate the return value policy and parent object (for
74
+ // return_value_policy::reference_internal) and are often ignored by custom casters.
75
+ // The return value should reflect the type hint specified by the second argument of `io_name`.
76
+ static handle
77
+ cast(const user_space::Point2D &number, return_value_policy /*policy*/, handle /*parent*/) {
78
+ return py::make_tuple(number.x, number.y).release();
79
+ }
80
+
81
+ // Python -> C++: convert a `PyObject` into a `Point2D` and return false upon failure. The
82
+ // second argument indicates whether implicit conversions should be allowed.
83
+ // The accepted types should reflect the type hint specified by the first argument of
84
+ // `io_name`.
85
+ bool load(handle src, bool /*convert*/) {
86
+ // Check if handle is a Sequence
87
+ if (!py::isinstance<py::sequence>(src)) {
88
+ return false;
89
+ }
90
+ auto seq = py::reinterpret_borrow<py::sequence>(src);
91
+ // Check if exactly two values are in the Sequence
92
+ if (seq.size() != 2) {
93
+ return false;
94
+ }
95
+ // Check if each element is either a float or an int
96
+ for (auto item : seq) {
97
+ if (!py::isinstance<py::float_>(item) && !py::isinstance<py::int_>(item)) {
98
+ return false;
99
+ }
100
+ }
101
+ value.x = seq[0].cast<double>();
102
+ value.y = seq[1].cast<double>();
103
+ return true;
104
+ }
105
+ };
106
+
107
+ } // namespace detail
108
+ } // namespace pybind11
109
+
110
+ // Bind the negate function
111
+ PYBIND11_MODULE(docs_advanced_cast_custom, m, py::mod_gil_not_used()) { m.def("negate", user_space::negate); }
112
+
113
+ .. note::
114
+
115
+ A ``type_caster<T>`` defined with ``PYBIND11_TYPE_CASTER(T, ...)`` requires
116
+ that ``T`` is default-constructible (``value`` is first default constructed
117
+ and then ``load()`` assigns to it).
118
+
119
+ .. note::
120
+ For further information on the ``return_value_policy`` argument of ``cast`` refer to :ref:`return_value_policies`.
121
+ To learn about the ``convert`` argument of ``load`` see :ref:`nonconverting_arguments`.
122
+
123
+ .. warning::
124
+
125
+ When using custom type casters, it's important to declare them consistently
126
+ in every compilation unit of the Python extension module to satisfy the C++ One Definition Rule
127
+ (`ODR <https://en.cppreference.com/w/cpp/language/definition>`_). Otherwise,
128
+ undefined behavior can ensue.
129
+
130
+ .. note::
131
+
132
+ Using the type hint ``Sequence[float]`` signals to static type checkers, that not only tuples may be
133
+ passed, but any type implementing the Sequence protocol, e.g., ``list[float]``.
134
+ Unfortunately, that loses the length information ``tuple[float, float]`` provides.
135
+ One way of still providing some length information in type hints is using ``typing.Annotated``, e.g.,
136
+ ``Annotated[Sequence[float], 2]``, or further add libraries like
137
+ `annotated-types <https://github.com/annotated-types/annotated-types>`_.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/eigen.rst ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Eigen
2
+ #####
3
+
4
+ `Eigen <http://eigen.tuxfamily.org>`_ is C++ header-based library for dense and
5
+ sparse linear algebra. Due to its popularity and widespread adoption, pybind11
6
+ provides transparent conversion and limited mapping support between Eigen and
7
+ Scientific Python linear algebra data types.
8
+
9
+ To enable the built-in Eigen support you must include the optional header file
10
+ :file:`pybind11/eigen.h`.
11
+
12
+ Pass-by-value
13
+ =============
14
+
15
+ When binding a function with ordinary Eigen dense object arguments (for
16
+ example, ``Eigen::MatrixXd``), pybind11 will accept any input value that is
17
+ already (or convertible to) a ``numpy.ndarray`` with dimensions compatible with
18
+ the Eigen type, copy its values into a temporary Eigen variable of the
19
+ appropriate type, then call the function with this temporary variable.
20
+
21
+ Sparse matrices are similarly copied to or from
22
+ ``scipy.sparse.csr_matrix``/``scipy.sparse.csc_matrix`` objects.
23
+
24
+ Pass-by-reference
25
+ =================
26
+
27
+ One major limitation of the above is that every data conversion implicitly
28
+ involves a copy, which can be both expensive (for large matrices) and disallows
29
+ binding functions that change their (Matrix) arguments. Pybind11 allows you to
30
+ work around this by using Eigen's ``Eigen::Ref<MatrixType>`` class much as you
31
+ would when writing a function taking a generic type in Eigen itself (subject to
32
+ some limitations discussed below).
33
+
34
+ When calling a bound function accepting a ``Eigen::Ref<const MatrixType>``
35
+ type, pybind11 will attempt to avoid copying by using an ``Eigen::Map`` object
36
+ that maps into the source ``numpy.ndarray`` data: this requires both that the
37
+ data types are the same (e.g. ``dtype='float64'`` and ``MatrixType::Scalar`` is
38
+ ``double``); and that the storage is layout compatible. The latter limitation
39
+ is discussed in detail in the section below, and requires careful
40
+ consideration: by default, numpy matrices and Eigen matrices are *not* storage
41
+ compatible.
42
+
43
+ If the numpy matrix cannot be used as is (either because its types differ, e.g.
44
+ passing an array of integers to an Eigen parameter requiring doubles, or
45
+ because the storage is incompatible), pybind11 makes a temporary copy and
46
+ passes the copy instead.
47
+
48
+ When a bound function parameter is instead ``Eigen::Ref<MatrixType>`` (note the
49
+ lack of ``const``), pybind11 will only allow the function to be called if it
50
+ can be mapped *and* if the numpy array is writeable (that is
51
+ ``a.flags.writeable`` is true). Any access (including modification) made to
52
+ the passed variable will be transparently carried out directly on the
53
+ ``numpy.ndarray``.
54
+
55
+ This means you can write code such as the following and have it work as
56
+ expected:
57
+
58
+ .. code-block:: cpp
59
+
60
+ void scale_by_2(Eigen::Ref<Eigen::VectorXd> v) {
61
+ v *= 2;
62
+ }
63
+
64
+ Note, however, that you will likely run into limitations due to numpy and
65
+ Eigen's difference default storage order for data; see the below section on
66
+ :ref:`storage_orders` for details on how to bind code that won't run into such
67
+ limitations.
68
+
69
+ .. note::
70
+
71
+ Passing by reference is not supported for sparse types.
72
+
73
+ Returning values to Python
74
+ ==========================
75
+
76
+ When returning an ordinary dense Eigen matrix type to numpy (e.g.
77
+ ``Eigen::MatrixXd`` or ``Eigen::RowVectorXf``) pybind11 keeps the matrix and
78
+ returns a numpy array that directly references the Eigen matrix: no copy of the
79
+ data is performed. The numpy array will have ``array.flags.owndata`` set to
80
+ ``False`` to indicate that it does not own the data, and the lifetime of the
81
+ stored Eigen matrix will be tied to the returned ``array``.
82
+
83
+ If you bind a function with a non-reference, ``const`` return type (e.g.
84
+ ``const Eigen::MatrixXd``), the same thing happens except that pybind11 also
85
+ sets the numpy array's ``writeable`` flag to false.
86
+
87
+ If you return an lvalue reference or pointer, the usual pybind11 rules apply,
88
+ as dictated by the binding function's return value policy (see the
89
+ documentation on :ref:`return_value_policies` for full details). That means,
90
+ without an explicit return value policy, lvalue references will be copied and
91
+ pointers will be managed by pybind11. In order to avoid copying, you should
92
+ explicitly specify an appropriate return value policy, as in the following
93
+ example:
94
+
95
+ .. code-block:: cpp
96
+
97
+ class MyClass {
98
+ Eigen::MatrixXd big_mat = Eigen::MatrixXd::Zero(10000, 10000);
99
+ public:
100
+ Eigen::MatrixXd &getMatrix() { return big_mat; }
101
+ const Eigen::MatrixXd &viewMatrix() { return big_mat; }
102
+ };
103
+
104
+ // Later, in binding code:
105
+ py::class_<MyClass>(m, "MyClass")
106
+ .def(py::init<>())
107
+ .def("copy_matrix", &MyClass::getMatrix) // Makes a copy!
108
+ .def("get_matrix", &MyClass::getMatrix, py::return_value_policy::reference_internal)
109
+ .def("view_matrix", &MyClass::viewMatrix, py::return_value_policy::reference_internal)
110
+ ;
111
+
112
+ .. code-block:: python
113
+
114
+ a = MyClass()
115
+ m = a.get_matrix() # flags.writeable = True, flags.owndata = False
116
+ v = a.view_matrix() # flags.writeable = False, flags.owndata = False
117
+ c = a.copy_matrix() # flags.writeable = True, flags.owndata = True
118
+ # m[5,6] and v[5,6] refer to the same element, c[5,6] does not.
119
+
120
+ Note in this example that ``py::return_value_policy::reference_internal`` is
121
+ used to tie the life of the MyClass object to the life of the returned arrays.
122
+
123
+ You may also return an ``Eigen::Ref``, ``Eigen::Map`` or other map-like Eigen
124
+ object (for example, the return value of ``matrix.block()`` and related
125
+ methods) that map into a dense Eigen type. When doing so, the default
126
+ behaviour of pybind11 is to simply reference the returned data: you must take
127
+ care to ensure that this data remains valid! You may ask pybind11 to
128
+ explicitly *copy* such a return value by using the
129
+ ``py::return_value_policy::copy`` policy when binding the function. You may
130
+ also use ``py::return_value_policy::reference_internal`` or a
131
+ ``py::keep_alive`` to ensure the data stays valid as long as the returned numpy
132
+ array does.
133
+
134
+ When returning such a reference of map, pybind11 additionally respects the
135
+ readonly-status of the returned value, marking the numpy array as non-writeable
136
+ if the reference or map was itself read-only.
137
+
138
+ .. note::
139
+
140
+ Sparse types are always copied when returned.
141
+
142
+ .. _storage_orders:
143
+
144
+ Storage orders
145
+ ==============
146
+
147
+ Passing arguments via ``Eigen::Ref`` has some limitations that you must be
148
+ aware of in order to effectively pass matrices by reference. First and
149
+ foremost is that the default ``Eigen::Ref<MatrixType>`` class requires
150
+ contiguous storage along columns (for column-major types, the default in Eigen)
151
+ or rows if ``MatrixType`` is specifically an ``Eigen::RowMajor`` storage type.
152
+ The former, Eigen's default, is incompatible with ``numpy``'s default row-major
153
+ storage, and so you will not be able to pass numpy arrays to Eigen by reference
154
+ without making one of two changes.
155
+
156
+ (Note that this does not apply to vectors (or column or row matrices): for such
157
+ types the "row-major" and "column-major" distinction is meaningless).
158
+
159
+ The first approach is to change the use of ``Eigen::Ref<MatrixType>`` to the
160
+ more general ``Eigen::Ref<MatrixType, 0, Eigen::Stride<Eigen::Dynamic,
161
+ Eigen::Dynamic>>`` (or similar type with a fully dynamic stride type in the
162
+ third template argument). Since this is a rather cumbersome type, pybind11
163
+ provides a ``py::EigenDRef<MatrixType>`` type alias for your convenience (along
164
+ with EigenDMap for the equivalent Map, and EigenDStride for just the stride
165
+ type).
166
+
167
+ This type allows Eigen to map into any arbitrary storage order. This is not
168
+ the default in Eigen for performance reasons: contiguous storage allows
169
+ vectorization that cannot be done when storage is not known to be contiguous at
170
+ compile time. The default ``Eigen::Ref`` stride type allows non-contiguous
171
+ storage along the outer dimension (that is, the rows of a column-major matrix
172
+ or columns of a row-major matrix), but not along the inner dimension.
173
+
174
+ This type, however, has the added benefit of also being able to map numpy array
175
+ slices. For example, the following (contrived) example uses Eigen with a numpy
176
+ slice to multiply by 2 all coefficients that are both on even rows (0, 2, 4,
177
+ ...) and in columns 2, 5, or 8:
178
+
179
+ .. code-block:: cpp
180
+
181
+ m.def("scale", [](py::EigenDRef<Eigen::MatrixXd> m, double c) { m *= c; });
182
+
183
+ .. code-block:: python
184
+
185
+ # a = np.array(...)
186
+ scale_by_2(myarray[0::2, 2:9:3])
187
+
188
+ The second approach to avoid copying is more intrusive: rearranging the
189
+ underlying data types to not run into the non-contiguous storage problem in the
190
+ first place. In particular, that means using matrices with ``Eigen::RowMajor``
191
+ storage, where appropriate, such as:
192
+
193
+ .. code-block:: cpp
194
+
195
+ using RowMatrixXd = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
196
+ // Use RowMatrixXd instead of MatrixXd
197
+
198
+ Now bound functions accepting ``Eigen::Ref<RowMatrixXd>`` arguments will be
199
+ callable with numpy's (default) arrays without involving a copying.
200
+
201
+ You can, alternatively, change the storage order that numpy arrays use by
202
+ adding the ``order='F'`` option when creating an array:
203
+
204
+ .. code-block:: python
205
+
206
+ myarray = np.array(source, order="F")
207
+
208
+ Such an object will be passable to a bound function accepting an
209
+ ``Eigen::Ref<MatrixXd>`` (or similar column-major Eigen type).
210
+
211
+ One major caveat with this approach, however, is that it is not entirely as
212
+ easy as simply flipping all Eigen or numpy usage from one to the other: some
213
+ operations may alter the storage order of a numpy array. For example, ``a2 =
214
+ array.transpose()`` results in ``a2`` being a view of ``array`` that references
215
+ the same data, but in the opposite storage order!
216
+
217
+ While this approach allows fully optimized vectorized calculations in Eigen, it
218
+ cannot be used with array slices, unlike the first approach.
219
+
220
+ When *returning* a matrix to Python (either a regular matrix, a reference via
221
+ ``Eigen::Ref<>``, or a map/block into a matrix), no special storage
222
+ consideration is required: the created numpy array will have the required
223
+ stride that allows numpy to properly interpret the array, whatever its storage
224
+ order.
225
+
226
+ Failing rather than copying
227
+ ===========================
228
+
229
+ The default behaviour when binding ``Eigen::Ref<const MatrixType>`` Eigen
230
+ references is to copy matrix values when passed a numpy array that does not
231
+ conform to the element type of ``MatrixType`` or does not have a compatible
232
+ stride layout. If you want to explicitly avoid copying in such a case, you
233
+ should bind arguments using the ``py::arg().noconvert()`` annotation (as
234
+ described in the :ref:`nonconverting_arguments` documentation).
235
+
236
+ The following example shows an example of arguments that don't allow data
237
+ copying to take place:
238
+
239
+ .. code-block:: cpp
240
+
241
+ // The method and function to be bound:
242
+ class MyClass {
243
+ // ...
244
+ double some_method(const Eigen::Ref<const MatrixXd> &matrix) { /* ... */ }
245
+ };
246
+ float some_function(const Eigen::Ref<const MatrixXf> &big,
247
+ const Eigen::Ref<const MatrixXf> &small) {
248
+ // ...
249
+ }
250
+
251
+ // The associated binding code:
252
+ using namespace pybind11::literals; // for "arg"_a
253
+ py::class_<MyClass>(m, "MyClass")
254
+ // ... other class definitions
255
+ .def("some_method", &MyClass::some_method, py::arg().noconvert());
256
+
257
+ m.def("some_function", &some_function,
258
+ "big"_a.noconvert(), // <- Don't allow copying for this arg
259
+ "small"_a // <- This one can be copied if needed
260
+ );
261
+
262
+ With the above binding code, attempting to call the ``some_method(m)``
263
+ method on a ``MyClass`` object, or attempting to call ``some_function(m, m2)``
264
+ will raise a ``RuntimeError`` rather than making a temporary copy of the array.
265
+ It will, however, allow the ``m2`` argument to be copied into a temporary if
266
+ necessary.
267
+
268
+ Note that explicitly specifying ``.noconvert()`` is not required for *mutable*
269
+ Eigen references (e.g. ``Eigen::Ref<MatrixXd>`` without ``const`` on the
270
+ ``MatrixXd``): mutable references will never be called with a temporary copy.
271
+
272
+ Vectors versus column/row matrices
273
+ ==================================
274
+
275
+ Eigen and numpy have fundamentally different notions of a vector. In Eigen, a
276
+ vector is simply a matrix with the number of columns or rows set to 1 at
277
+ compile time (for a column vector or row vector, respectively). NumPy, in
278
+ contrast, has comparable 2-dimensional 1xN and Nx1 arrays, but *also* has
279
+ 1-dimensional arrays of size N.
280
+
281
+ When passing a 2-dimensional 1xN or Nx1 array to Eigen, the Eigen type must
282
+ have matching dimensions: That is, you cannot pass a 2-dimensional Nx1 numpy
283
+ array to an Eigen value expecting a row vector, or a 1xN numpy array as a
284
+ column vector argument.
285
+
286
+ On the other hand, pybind11 allows you to pass 1-dimensional arrays of length N
287
+ as Eigen parameters. If the Eigen type can hold a column vector of length N it
288
+ will be passed as such a column vector. If not, but the Eigen type constraints
289
+ will accept a row vector, it will be passed as a row vector. (The column
290
+ vector takes precedence when both are supported, for example, when passing a
291
+ 1D numpy array to a MatrixXd argument). Note that the type need not be
292
+ explicitly a vector: it is permitted to pass a 1D numpy array of size 5 to an
293
+ Eigen ``Matrix<double, Dynamic, 5>``: you would end up with a 1x5 Eigen matrix.
294
+ Passing the same to an ``Eigen::MatrixXd`` would result in a 5x1 Eigen matrix.
295
+
296
+ When returning an Eigen vector to numpy, the conversion is ambiguous: a row
297
+ vector of length 4 could be returned as either a 1D array of length 4, or as a
298
+ 2D array of size 1x4. When encountering such a situation, pybind11 compromises
299
+ by considering the returned Eigen type: if it is a compile-time vector--that
300
+ is, the type has either the number of rows or columns set to 1 at compile
301
+ time--pybind11 converts to a 1D numpy array when returning the value. For
302
+ instances that are a vector only at run-time (e.g. ``MatrixXd``,
303
+ ``Matrix<float, Dynamic, 4>``), pybind11 returns the vector as a 2D array to
304
+ numpy. If this isn't want you want, you can use ``array.reshape(...)`` to get
305
+ a view of the same data in the desired dimensions.
306
+
307
+ .. seealso::
308
+
309
+ The file :file:`tests/test_eigen.cpp` contains a complete example that
310
+ shows how to pass Eigen sparse and dense data types in more detail.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/functional.rst ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Functional
2
+ ##########
3
+
4
+ The following features must be enabled by including :file:`pybind11/functional.h`.
5
+
6
+
7
+ Callbacks and passing anonymous functions
8
+ =========================================
9
+
10
+ The C++11 standard brought lambda functions and the generic polymorphic
11
+ function wrapper ``std::function<>`` to the C++ programming language, which
12
+ enable powerful new ways of working with functions. Lambda functions come in
13
+ two flavors: stateless lambda function resemble classic function pointers that
14
+ link to an anonymous piece of code, while stateful lambda functions
15
+ additionally depend on captured variables that are stored in an anonymous
16
+ *lambda closure object*.
17
+
18
+ Here is a simple example of a C++ function that takes an arbitrary function
19
+ (stateful or stateless) with signature ``int -> int`` as an argument and runs
20
+ it with the value 10.
21
+
22
+ .. code-block:: cpp
23
+
24
+ int func_arg(const std::function<int(int)> &f) {
25
+ return f(10);
26
+ }
27
+
28
+ The example below is more involved: it takes a function of signature ``int -> int``
29
+ and returns another function of the same kind. The return value is a stateful
30
+ lambda function, which stores the value ``f`` in the capture object and adds 1 to
31
+ its return value upon execution.
32
+
33
+ .. code-block:: cpp
34
+
35
+ std::function<int(int)> func_ret(const std::function<int(int)> &f) {
36
+ return [f](int i) {
37
+ return f(i) + 1;
38
+ };
39
+ }
40
+
41
+ This example demonstrates using python named parameters in C++ callbacks which
42
+ requires using ``py::cpp_function`` as a wrapper. Usage is similar to defining
43
+ methods of classes:
44
+
45
+ .. code-block:: cpp
46
+
47
+ py::cpp_function func_cpp() {
48
+ return py::cpp_function([](int i) { return i+1; },
49
+ py::arg("number"));
50
+ }
51
+
52
+ After including the extra header file :file:`pybind11/functional.h`, it is almost
53
+ trivial to generate binding code for all of these functions.
54
+
55
+ .. code-block:: cpp
56
+
57
+ #include <pybind11/functional.h>
58
+
59
+ PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {
60
+ m.def("func_arg", &func_arg);
61
+ m.def("func_ret", &func_ret);
62
+ m.def("func_cpp", &func_cpp);
63
+ }
64
+
65
+ The following interactive session shows how to call them from Python.
66
+
67
+ .. code-block:: pycon
68
+
69
+ $ python
70
+ >>> import example
71
+ >>> def square(i):
72
+ ... return i * i
73
+ ...
74
+ >>> example.func_arg(square)
75
+ 100L
76
+ >>> square_plus_1 = example.func_ret(square)
77
+ >>> square_plus_1(4)
78
+ 17L
79
+ >>> plus_1 = func_cpp()
80
+ >>> plus_1(number=43)
81
+ 44L
82
+
83
+ .. warning::
84
+
85
+ Keep in mind that passing a function from C++ to Python (or vice versa)
86
+ will instantiate a piece of wrapper code that translates function
87
+ invocations between the two languages. Naturally, this translation
88
+ increases the computational cost of each function call somewhat. A
89
+ problematic situation can arise when a function is copied back and forth
90
+ between Python and C++ many times in a row, in which case the underlying
91
+ wrappers will accumulate correspondingly. The resulting long sequence of
92
+ C++ -> Python -> C++ -> ... roundtrips can significantly decrease
93
+ performance.
94
+
95
+ There is one exception: pybind11 detects case where a stateless function
96
+ (i.e. a function pointer or a lambda function without captured variables)
97
+ is passed as an argument to another C++ function exposed in Python. In this
98
+ case, there is no overhead. Pybind11 will extract the underlying C++
99
+ function pointer from the wrapped function to sidestep a potential C++ ->
100
+ Python -> C++ roundtrip. This is demonstrated in :file:`tests/test_callbacks.cpp`.
101
+
102
+ .. note::
103
+
104
+ This functionality is very useful when generating bindings for callbacks in
105
+ C++ libraries (e.g. GUI libraries, asynchronous networking libraries, etc.).
106
+
107
+ The file :file:`tests/test_callbacks.cpp` contains a complete example
108
+ that demonstrates how to work with callbacks and anonymous functions in
109
+ more detail.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/index.rst ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _type-conversions:
2
+
3
+ Type conversions
4
+ ################
5
+
6
+ Apart from enabling cross-language function calls, a fundamental problem
7
+ that a binding tool like pybind11 must address is to provide access to
8
+ native Python types in C++ and vice versa. There are three fundamentally
9
+ different ways to do this—which approach is preferable for a particular type
10
+ depends on the situation at hand.
11
+
12
+ 1. Use a native C++ type everywhere. In this case, the type must be wrapped
13
+ using pybind11-generated bindings so that Python can interact with it.
14
+
15
+ 2. Use a native Python type everywhere. It will need to be wrapped so that
16
+ C++ functions can interact with it.
17
+
18
+ 3. Use a native C++ type on the C++ side and a native Python type on the
19
+ Python side. pybind11 refers to this as a *type conversion*.
20
+
21
+ Type conversions are the most "natural" option in the sense that native
22
+ (non-wrapped) types are used everywhere. The main downside is that a copy
23
+ of the data must be made on every Python ↔ C++ transition: this is
24
+ needed since the C++ and Python versions of the same type generally won't
25
+ have the same memory layout.
26
+
27
+ pybind11 can perform many kinds of conversions automatically. An overview
28
+ is provided in the table ":ref:`conversion_table`".
29
+
30
+ The following subsections discuss the differences between these options in more
31
+ detail. The main focus in this section is on type conversions, which represent
32
+ the last case of the above list.
33
+
34
+ .. toctree::
35
+ :maxdepth: 1
36
+
37
+ overview
38
+ strings
39
+ stl
40
+ functional
41
+ chrono
42
+ eigen
43
+ custom
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/overview.rst ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Overview
2
+ ########
3
+
4
+ .. rubric:: 1. Native type in C++, wrapper in Python
5
+
6
+ Exposing a custom C++ type using :class:`py::class_` was covered in detail
7
+ in the :doc:`/classes` section. There, the underlying data structure is
8
+ always the original C++ class while the :class:`py::class_` wrapper provides
9
+ a Python interface. Internally, when an object like this is sent from C++ to
10
+ Python, pybind11 will just add the outer wrapper layer over the native C++
11
+ object. Getting it back from Python is just a matter of peeling off the
12
+ wrapper.
13
+
14
+ .. rubric:: 2. Wrapper in C++, native type in Python
15
+
16
+ This is the exact opposite situation. Now, we have a type which is native to
17
+ Python, like a ``tuple`` or a ``list``. One way to get this data into C++ is
18
+ with the :class:`py::object` family of wrappers. These are explained in more
19
+ detail in the :doc:`/advanced/pycpp/object` section. We'll just give a quick
20
+ example here:
21
+
22
+ .. code-block:: cpp
23
+
24
+ void print_list(py::list my_list) {
25
+ for (auto item : my_list)
26
+ std::cout << item << " ";
27
+ }
28
+
29
+ .. code-block:: pycon
30
+
31
+ >>> print_list([1, 2, 3])
32
+ 1 2 3
33
+
34
+ The Python ``list`` is not converted in any way -- it's just wrapped in a C++
35
+ :class:`py::list` class. At its core it's still a Python object. Copying a
36
+ :class:`py::list` will do the usual reference-counting like in Python.
37
+ Returning the object to Python will just remove the thin wrapper.
38
+
39
+ .. rubric:: 3. Converting between native C++ and Python types
40
+
41
+ In the previous two cases we had a native type in one language and a wrapper in
42
+ the other. Now, we have native types on both sides and we convert between them.
43
+
44
+ .. code-block:: cpp
45
+
46
+ void print_vector(const std::vector<int> &v) {
47
+ for (auto item : v)
48
+ std::cout << item << "\n";
49
+ }
50
+
51
+ .. code-block:: pycon
52
+
53
+ >>> print_vector([1, 2, 3])
54
+ 1 2 3
55
+
56
+ In this case, pybind11 will construct a new ``std::vector<int>`` and copy each
57
+ element from the Python ``list``. The newly constructed object will be passed
58
+ to ``print_vector``. The same thing happens in the other direction: a new
59
+ ``list`` is made to match the value returned from C++.
60
+
61
+ Lots of these conversions are supported out of the box, as shown in the table
62
+ below. They are very convenient, but keep in mind that these conversions are
63
+ fundamentally based on copying data. This is perfectly fine for small immutable
64
+ types but it may become quite expensive for large data structures. This can be
65
+ avoided by overriding the automatic conversion with a custom wrapper (i.e. the
66
+ above-mentioned approach 1). This requires some manual effort and more details
67
+ are available in the :ref:`opaque` section.
68
+
69
+ .. _conversion_table:
70
+
71
+ List of all builtin conversions
72
+ -------------------------------
73
+
74
+ The following basic data types are supported out of the box (some may require
75
+ an additional extension header to be included). To pass other data structures
76
+ as arguments and return values, refer to the section on binding :ref:`classes`.
77
+
78
+ +------------------------------------+---------------------------+-----------------------------------+
79
+ | Data type | Description | Header file |
80
+ +====================================+===========================+===================================+
81
+ | ``int8_t``, ``uint8_t`` | 8-bit integers | :file:`pybind11/pybind11.h` |
82
+ +------------------------------------+---------------------------+-----------------------------------+
83
+ | ``int16_t``, ``uint16_t`` | 16-bit integers | :file:`pybind11/pybind11.h` |
84
+ +------------------------------------+---------------------------+-----------------------------------+
85
+ | ``int32_t``, ``uint32_t`` | 32-bit integers | :file:`pybind11/pybind11.h` |
86
+ +------------------------------------+---------------------------+-----------------------------------+
87
+ | ``int64_t``, ``uint64_t`` | 64-bit integers | :file:`pybind11/pybind11.h` |
88
+ +------------------------------------+---------------------------+-----------------------------------+
89
+ | ``ssize_t``, ``size_t`` | Platform-dependent size | :file:`pybind11/pybind11.h` |
90
+ +------------------------------------+---------------------------+-----------------------------------+
91
+ | ``float``, ``double`` | Floating point types | :file:`pybind11/pybind11.h` |
92
+ +------------------------------------+---------------------------+-----------------------------------+
93
+ | ``bool`` | Two-state Boolean type | :file:`pybind11/pybind11.h` |
94
+ +------------------------------------+---------------------------+-----------------------------------+
95
+ | ``char`` | Character literal | :file:`pybind11/pybind11.h` |
96
+ +------------------------------------+---------------------------+-----------------------------------+
97
+ | ``char16_t`` | UTF-16 character literal | :file:`pybind11/pybind11.h` |
98
+ +------------------------------------+---------------------------+-----------------------------------+
99
+ | ``char32_t`` | UTF-32 character literal | :file:`pybind11/pybind11.h` |
100
+ +------------------------------------+---------------------------+-----------------------------------+
101
+ | ``wchar_t`` | Wide character literal | :file:`pybind11/pybind11.h` |
102
+ +------------------------------------+---------------------------+-----------------------------------+
103
+ | ``const char *`` | UTF-8 string literal | :file:`pybind11/pybind11.h` |
104
+ +------------------------------------+---------------------------+-----------------------------------+
105
+ | ``const char16_t *`` | UTF-16 string literal | :file:`pybind11/pybind11.h` |
106
+ +------------------------------------+---------------------------+-----------------------------------+
107
+ | ``const char32_t *`` | UTF-32 string literal | :file:`pybind11/pybind11.h` |
108
+ +------------------------------------+---------------------------+-----------------------------------+
109
+ | ``const wchar_t *`` | Wide string literal | :file:`pybind11/pybind11.h` |
110
+ +------------------------------------+---------------------------+-----------------------------------+
111
+ | ``std::string`` | STL dynamic UTF-8 string | :file:`pybind11/pybind11.h` |
112
+ +------------------------------------+---------------------------+-----------------------------------+
113
+ | ``std::u16string`` | STL dynamic UTF-16 string | :file:`pybind11/pybind11.h` |
114
+ +------------------------------------+---------------------------+-----------------------------------+
115
+ | ``std::u32string`` | STL dynamic UTF-32 string | :file:`pybind11/pybind11.h` |
116
+ +------------------------------------+---------------------------+-----------------------------------+
117
+ | ``std::wstring`` | STL dynamic wide string | :file:`pybind11/pybind11.h` |
118
+ +------------------------------------+---------------------------+-----------------------------------+
119
+ | ``std::string_view``, | STL C++17 string views | :file:`pybind11/pybind11.h` |
120
+ | ``std::u16string_view``, etc. | | |
121
+ +------------------------------------+---------------------------+-----------------------------------+
122
+ | ``std::pair<T1, T2>`` | Pair of two custom types | :file:`pybind11/pybind11.h` |
123
+ +------------------------------------+---------------------------+-----------------------------------+
124
+ | ``std::tuple<...>`` | Arbitrary tuple of types | :file:`pybind11/pybind11.h` |
125
+ +------------------------------------+---------------------------+-----------------------------------+
126
+ | ``std::reference_wrapper<...>`` | Reference type wrapper | :file:`pybind11/pybind11.h` |
127
+ +------------------------------------+---------------------------+-----------------------------------+
128
+ | ``std::complex<T>`` | Complex numbers | :file:`pybind11/complex.h` |
129
+ +------------------------------------+---------------------------+-----------------------------------+
130
+ | ``std::array<T, Size>`` | STL static array | :file:`pybind11/stl.h` |
131
+ +------------------------------------+---------------------------+-----------------------------------+
132
+ | ``std::vector<T>`` | STL dynamic array | :file:`pybind11/stl.h` |
133
+ +------------------------------------+---------------------------+-----------------------------------+
134
+ | ``std::deque<T>`` | STL double-ended queue | :file:`pybind11/stl.h` |
135
+ +------------------------------------+---------------------------+-----------------------------------+
136
+ | ``std::valarray<T>`` | STL value array | :file:`pybind11/stl.h` |
137
+ +------------------------------------+---------------------------+-----------------------------------+
138
+ | ``std::list<T>`` | STL linked list | :file:`pybind11/stl.h` |
139
+ +------------------------------------+---------------------------+-----------------------------------+
140
+ | ``std::map<T1, T2>`` | STL ordered map | :file:`pybind11/stl.h` |
141
+ +------------------------------------+---------------------------+-----------------------------------+
142
+ | ``std::unordered_map<T1, T2>`` | STL unordered map | :file:`pybind11/stl.h` |
143
+ +------------------------------------+---------------------------+-----------------------------------+
144
+ | ``std::set<T>`` | STL ordered set | :file:`pybind11/stl.h` |
145
+ +------------------------------------+---------------------------+-----------------------------------+
146
+ | ``std::unordered_set<T>`` | STL unordered set | :file:`pybind11/stl.h` |
147
+ +------------------------------------+---------------------------+-----------------------------------+
148
+ | ``std::optional<T>`` | STL optional type (C++17) | :file:`pybind11/stl.h` |
149
+ +------------------------------------+---------------------------+-----------------------------------+
150
+ | ``std::experimental::optional<T>`` | STL optional type (exp.) | :file:`pybind11/stl.h` |
151
+ +------------------------------------+---------------------------+-----------------------------------+
152
+ | ``std::variant<...>`` | Type-safe union (C++17) | :file:`pybind11/stl.h` |
153
+ +------------------------------------+---------------------------+-----------------------------------+
154
+ | ``std::filesystem::path`` | STL path (C++17) [#]_ | :file:`pybind11/stl/filesystem.h` |
155
+ +------------------------------------+---------------------------+-----------------------------------+
156
+ | ``std::function<...>`` | STL polymorphic function | :file:`pybind11/functional.h` |
157
+ +------------------------------------+---------------------------+-----------------------------------+
158
+ | ``std::chrono::duration<...>`` | STL time duration | :file:`pybind11/chrono.h` |
159
+ +------------------------------------+---------------------------+-----------------------------------+
160
+ | ``std::chrono::time_point<...>`` | STL date/time | :file:`pybind11/chrono.h` |
161
+ +------------------------------------+---------------------------+-----------------------------------+
162
+ | ``Eigen::Matrix<...>`` | Eigen: dense matrix | :file:`pybind11/eigen.h` |
163
+ +------------------------------------+---------------------------+-----------------------------------+
164
+ | ``Eigen::Map<...>`` | Eigen: mapped memory | :file:`pybind11/eigen.h` |
165
+ +------------------------------------+---------------------------+-----------------------------------+
166
+ | ``Eigen::SparseMatrix<...>`` | Eigen: sparse matrix | :file:`pybind11/eigen.h` |
167
+ +------------------------------------+---------------------------+-----------------------------------+
168
+
169
+ .. [#] ``std::filesystem::path`` is converted to ``pathlib.Path`` and
170
+ can be loaded from ``os.PathLike``, ``str``, and ``bytes``.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/stl.rst ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ STL containers
2
+ ##############
3
+
4
+ Automatic conversion
5
+ ====================
6
+
7
+ When including the additional header file :file:`pybind11/stl.h`, conversions
8
+ between ``std::vector<>``/``std::deque<>``/``std::list<>``/``std::array<>``/``std::valarray<>``,
9
+ ``std::set<>``/``std::unordered_set<>``, and
10
+ ``std::map<>``/``std::unordered_map<>`` and the Python ``list``, ``set`` and
11
+ ``dict`` data structures are automatically enabled. The types ``std::pair<>``
12
+ and ``std::tuple<>`` are already supported out of the box with just the core
13
+ :file:`pybind11/pybind11.h` header.
14
+
15
+ The major downside of these implicit conversions is that containers must be
16
+ converted (i.e. copied) on every Python->C++ and C++->Python transition, which
17
+ can have implications on the program semantics and performance. Please read the
18
+ next sections for more details and alternative approaches that avoid this.
19
+
20
+ .. note::
21
+
22
+ Arbitrary nesting of any of these types is possible.
23
+
24
+ .. seealso::
25
+
26
+ The file :file:`tests/test_stl.cpp` contains a complete
27
+ example that demonstrates how to pass STL data types in more detail.
28
+
29
+ .. _cpp17_container_casters:
30
+
31
+ C++17 library containers
32
+ ========================
33
+
34
+ The :file:`pybind11/stl.h` header also includes support for ``std::optional<>``
35
+ and ``std::variant<>``. These require a C++17 compiler and standard library.
36
+ In C++14 mode, ``std::experimental::optional<>`` is supported if available.
37
+
38
+ Various versions of these containers also exist for C++11 (e.g. in Boost).
39
+ pybind11 provides an easy way to specialize the ``type_caster`` for such
40
+ types:
41
+
42
+ .. code-block:: cpp
43
+
44
+ // `boost::optional` as an example -- can be any `std::optional`-like container
45
+ namespace PYBIND11_NAMESPACE { namespace detail {
46
+ template <typename T>
47
+ struct type_caster<boost::optional<T>> : optional_caster<boost::optional<T>> {};
48
+ }}
49
+
50
+ The above should be placed in a header file and included in all translation units
51
+ where automatic conversion is needed. Similarly, a specialization can be provided
52
+ for custom variant types:
53
+
54
+ .. code-block:: cpp
55
+
56
+ // `boost::variant` as an example -- can be any `std::variant`-like container
57
+ namespace PYBIND11_NAMESPACE { namespace detail {
58
+ template <typename... Ts>
59
+ struct type_caster<boost::variant<Ts...>> : variant_caster<boost::variant<Ts...>> {};
60
+
61
+ // Specifies the function used to visit the variant -- `apply_visitor` instead of `visit`
62
+ template <>
63
+ struct visit_helper<boost::variant> {
64
+ template <typename... Args>
65
+ static auto call(Args &&...args) -> decltype(boost::apply_visitor(args...)) {
66
+ return boost::apply_visitor(args...);
67
+ }
68
+ };
69
+ }} // namespace PYBIND11_NAMESPACE::detail
70
+
71
+ The ``visit_helper`` specialization is not required if your ``name::variant`` provides
72
+ a ``name::visit()`` function. For any other function name, the specialization must be
73
+ included to tell pybind11 how to visit the variant.
74
+
75
+ .. warning::
76
+
77
+ When converting a ``variant`` type, pybind11 follows the same rules as when
78
+ determining which function overload to call (:ref:`overload_resolution`), and
79
+ so the same caveats hold. In particular, the order in which the ``variant``'s
80
+ alternatives are listed is important, since pybind11 will try conversions in
81
+ this order. This means that, for example, when converting ``variant<int, bool>``,
82
+ the ``bool`` variant will never be selected, as any Python ``bool`` is already
83
+ an ``int`` and is convertible to a C++ ``int``. Changing the order of alternatives
84
+ (and using ``variant<bool, int>``, in this example) provides a solution.
85
+
86
+ .. note::
87
+
88
+ pybind11 only supports the modern implementation of ``boost::variant``
89
+ which makes use of variadic templates. This requires Boost 1.56 or newer.
90
+
91
+ .. _opaque:
92
+
93
+ Making opaque types
94
+ ===================
95
+
96
+ pybind11 heavily relies on a template matching mechanism to convert parameters
97
+ and return values that are constructed from STL data types such as vectors,
98
+ linked lists, hash tables, etc. This even works in a recursive manner, for
99
+ instance to deal with lists of hash maps of pairs of elementary and custom
100
+ types, etc.
101
+
102
+ However, a fundamental limitation of this approach is that internal conversions
103
+ between Python and C++ types involve a copy operation that prevents
104
+ pass-by-reference semantics. What does this mean?
105
+
106
+ Suppose we bind the following function
107
+
108
+ .. code-block:: cpp
109
+
110
+ void append_1(std::vector<int> &v) {
111
+ v.push_back(1);
112
+ }
113
+
114
+ and call it from Python, the following happens:
115
+
116
+ .. code-block:: pycon
117
+
118
+ >>> v = [5, 6]
119
+ >>> append_1(v)
120
+ >>> print(v)
121
+ [5, 6]
122
+
123
+ As you can see, when passing STL data structures by reference, modifications
124
+ are not propagated back the Python side. A similar situation arises when
125
+ exposing STL data structures using the ``def_readwrite`` or ``def_readonly``
126
+ functions:
127
+
128
+ .. code-block:: cpp
129
+
130
+ /* ... definition ... */
131
+
132
+ class MyClass {
133
+ std::vector<int> contents;
134
+ };
135
+
136
+ /* ... binding code ... */
137
+
138
+ py::class_<MyClass>(m, "MyClass")
139
+ .def(py::init<>())
140
+ .def_readwrite("contents", &MyClass::contents);
141
+
142
+ In this case, properties can be read and written in their entirety. However, an
143
+ ``append`` operation involving such a list type has no effect:
144
+
145
+ .. code-block:: pycon
146
+
147
+ >>> m = MyClass()
148
+ >>> m.contents = [5, 6]
149
+ >>> print(m.contents)
150
+ [5, 6]
151
+ >>> m.contents.append(7)
152
+ >>> print(m.contents)
153
+ [5, 6]
154
+
155
+ Finally, the involved copy operations can be costly when dealing with very
156
+ large lists. To deal with all of the above situations, pybind11 provides a
157
+ macro named ``PYBIND11_MAKE_OPAQUE(T)`` that disables the template-based
158
+ conversion machinery of types, thus rendering them *opaque*. The contents of
159
+ opaque objects are never inspected or extracted, hence they *can* be passed by
160
+ reference. For instance, to turn ``std::vector<int>`` into an opaque type, add
161
+ the declaration
162
+
163
+ .. code-block:: cpp
164
+
165
+ PYBIND11_MAKE_OPAQUE(std::vector<int>)
166
+
167
+ before any binding code (e.g. invocations to ``class_::def()``, etc.). This
168
+ macro must be specified at the top level (and outside of any namespaces), since
169
+ it adds a template instantiation of ``type_caster``. If your binding code consists of
170
+ multiple compilation units, it must be present in every file (typically via a
171
+ common header) preceding any usage of ``std::vector<int>``. Opaque types must
172
+ also have a corresponding ``py::class_`` declaration to associate them with a
173
+ name in Python, and to define a set of available operations, e.g.:
174
+
175
+ .. code-block:: cpp
176
+
177
+ py::class_<std::vector<int>>(m, "IntVector")
178
+ .def(py::init<>())
179
+ .def("clear", &std::vector<int>::clear)
180
+ .def("pop_back", &std::vector<int>::pop_back)
181
+ .def("__len__", [](const std::vector<int> &v) { return v.size(); })
182
+ .def("__iter__", [](std::vector<int> &v) {
183
+ return py::make_iterator(v.begin(), v.end());
184
+ }, py::keep_alive<0, 1>()) /* Keep vector alive while iterator is used */
185
+ // ....
186
+
187
+ .. seealso::
188
+
189
+ The file :file:`tests/test_opaque_types.cpp` contains a complete
190
+ example that demonstrates how to create and expose opaque types using
191
+ pybind11 in more detail.
192
+
193
+ .. _stl_bind:
194
+
195
+ Binding STL containers
196
+ ======================
197
+
198
+ The ability to expose STL containers as native Python objects is a fairly
199
+ common request, hence pybind11 also provides an optional header file named
200
+ :file:`pybind11/stl_bind.h` that does exactly this. The mapped containers try
201
+ to match the behavior of their native Python counterparts as much as possible.
202
+
203
+ The following example showcases usage of :file:`pybind11/stl_bind.h`:
204
+
205
+ .. code-block:: cpp
206
+
207
+ // Don't forget this
208
+ #include <pybind11/stl_bind.h>
209
+
210
+ PYBIND11_MAKE_OPAQUE(std::vector<int>)
211
+ PYBIND11_MAKE_OPAQUE(std::map<std::string, double>)
212
+
213
+ // ...
214
+
215
+ // later in binding code:
216
+ py::bind_vector<std::vector<int>>(m, "VectorInt");
217
+ py::bind_map<std::map<std::string, double>>(m, "MapStringDouble");
218
+
219
+ When binding STL containers pybind11 considers the types of the container's
220
+ elements to decide whether the container should be confined to the local module
221
+ (via the :ref:`module_local` feature). If the container element types are
222
+ anything other than already-bound custom types bound without
223
+ ``py::module_local()`` the container binding will have ``py::module_local()``
224
+ applied. This includes converting types such as numeric types, strings, Eigen
225
+ types; and types that have not yet been bound at the time of the stl container
226
+ binding. This module-local binding is designed to avoid potential conflicts
227
+ between module bindings (for example, from two separate modules each attempting
228
+ to bind ``std::vector<int>`` as a python type).
229
+
230
+ It is possible to override this behavior to force a definition to be either
231
+ module-local or global. To do so, you can pass the attributes
232
+ ``py::module_local()`` (to make the binding module-local) or
233
+ ``py::module_local(false)`` (to make the binding global) into the
234
+ ``py::bind_vector`` or ``py::bind_map`` arguments:
235
+
236
+ .. code-block:: cpp
237
+
238
+ py::bind_vector<std::vector<int>>(m, "VectorInt", py::module_local(false));
239
+
240
+ Note, however, that such a global binding would make it impossible to load this
241
+ module at the same time as any other pybind module that also attempts to bind
242
+ the same container type (``std::vector<int>`` in the above example).
243
+
244
+ See :ref:`module_local` for more details on module-local bindings.
245
+
246
+ .. seealso::
247
+
248
+ The file :file:`tests/test_stl_binders.cpp` shows how to use the
249
+ convenience STL container wrappers.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/cast/strings.rst ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Strings, bytes and Unicode conversions
2
+ ######################################
3
+
4
+ Passing Python strings to C++
5
+ =============================
6
+
7
+ When a Python ``str`` is passed from Python to a C++ function that accepts
8
+ ``std::string`` or ``char *`` as arguments, pybind11 will encode the Python
9
+ string to UTF-8. All Python ``str`` can be encoded in UTF-8, so this operation
10
+ does not fail.
11
+
12
+ The C++ language is encoding agnostic. It is the responsibility of the
13
+ programmer to track encodings. It's often easiest to simply `use UTF-8
14
+ everywhere <http://utf8everywhere.org/>`_.
15
+
16
+ .. code-block:: c++
17
+
18
+ m.def("utf8_test",
19
+ [](const std::string &s) {
20
+ cout << "utf-8 is icing on the cake.\n";
21
+ cout << s;
22
+ }
23
+ );
24
+ m.def("utf8_charptr",
25
+ [](const char *s) {
26
+ cout << "My favorite food is\n";
27
+ cout << s;
28
+ }
29
+ );
30
+
31
+ .. code-block:: pycon
32
+
33
+ >>> utf8_test("🎂")
34
+ utf-8 is icing on the cake.
35
+ 🎂
36
+
37
+ >>> utf8_charptr("🍕")
38
+ My favorite food is
39
+ 🍕
40
+
41
+ .. note::
42
+
43
+ Some terminal emulators do not support UTF-8 or emoji fonts and may not
44
+ display the example above correctly.
45
+
46
+ The results are the same whether the C++ function accepts arguments by value or
47
+ reference, and whether or not ``const`` is used.
48
+
49
+ Passing bytes to C++
50
+ --------------------
51
+
52
+ A Python ``bytes`` object will be passed to C++ functions that accept
53
+ ``std::string`` or ``char*`` *without* conversion. In order to make a function
54
+ *only* accept ``bytes`` (and not ``str``), declare it as taking a ``py::bytes``
55
+ argument.
56
+
57
+
58
+ Returning C++ strings to Python
59
+ ===============================
60
+
61
+ When a C++ function returns a ``std::string`` or ``char*`` to a Python caller,
62
+ **pybind11 will assume that the string is valid UTF-8** and will decode it to a
63
+ native Python ``str``, using the same API as Python uses to perform
64
+ ``bytes.decode('utf-8')``. If this implicit conversion fails, pybind11 will
65
+ raise a ``UnicodeDecodeError``.
66
+
67
+ .. code-block:: c++
68
+
69
+ m.def("std_string_return",
70
+ []() {
71
+ return std::string("This string needs to be UTF-8 encoded");
72
+ }
73
+ );
74
+
75
+ .. code-block:: pycon
76
+
77
+ >>> isinstance(example.std_string_return(), str)
78
+ True
79
+
80
+
81
+ Because UTF-8 is inclusive of pure ASCII, there is never any issue with
82
+ returning a pure ASCII string to Python. If there is any possibility that the
83
+ string is not pure ASCII, it is necessary to ensure the encoding is valid
84
+ UTF-8.
85
+
86
+ .. warning::
87
+
88
+ Implicit conversion assumes that a returned ``char *`` is null-terminated.
89
+ If there is no null terminator a buffer overrun will occur.
90
+
91
+ Explicit conversions
92
+ --------------------
93
+
94
+ If some C++ code constructs a ``std::string`` that is not a UTF-8 string, one
95
+ can perform a explicit conversion and return a ``py::str`` object. Explicit
96
+ conversion has the same overhead as implicit conversion.
97
+
98
+ .. code-block:: c++
99
+
100
+ // This uses the Python C API to convert Latin-1 to Unicode
101
+ m.def("str_output",
102
+ []() {
103
+ std::string s = "Send your r\xe9sum\xe9 to Alice in HR"; // Latin-1
104
+ py::handle py_s = PyUnicode_DecodeLatin1(s.data(), s.length(), nullptr);
105
+ if (!py_s) {
106
+ throw py::error_already_set();
107
+ }
108
+ return py::reinterpret_steal<py::str>(py_s);
109
+ }
110
+ );
111
+
112
+ .. code-block:: pycon
113
+
114
+ >>> str_output()
115
+ 'Send your résumé to Alice in HR'
116
+
117
+ The `Python C API
118
+ <https://docs.python.org/3/c-api/unicode.html#built-in-codecs>`_ provides
119
+ several built-in codecs. Note that these all return *new* references, so
120
+ use :cpp:func:`reinterpret_steal` when converting them to a :cpp:class:`str`.
121
+
122
+
123
+ One could also use a third party encoding library such as libiconv to transcode
124
+ to UTF-8.
125
+
126
+ Return C++ strings without conversion
127
+ -------------------------------------
128
+
129
+ If the data in a C++ ``std::string`` does not represent text and should be
130
+ returned to Python as ``bytes``, then one can return the data as a
131
+ ``py::bytes`` object.
132
+
133
+ .. code-block:: c++
134
+
135
+ m.def("return_bytes",
136
+ []() {
137
+ std::string s("\xba\xd0\xba\xd0"); // Not valid UTF-8
138
+ return py::bytes(s); // Return the data without transcoding
139
+ }
140
+ );
141
+
142
+ .. code-block:: pycon
143
+
144
+ >>> example.return_bytes()
145
+ b'\xba\xd0\xba\xd0'
146
+
147
+
148
+ Note the asymmetry: pybind11 will convert ``bytes`` to ``std::string`` without
149
+ encoding, but cannot convert ``std::string`` back to ``bytes`` implicitly.
150
+
151
+ .. code-block:: c++
152
+
153
+ m.def("asymmetry",
154
+ [](std::string s) { // Accepts str or bytes from Python
155
+ return s; // Looks harmless, but implicitly converts to str
156
+ }
157
+ );
158
+
159
+ .. code-block:: pycon
160
+
161
+ >>> isinstance(example.asymmetry(b"have some bytes"), str)
162
+ True
163
+
164
+ >>> example.asymmetry(b"\xba\xd0\xba\xd0") # invalid utf-8 as bytes
165
+ UnicodeDecodeError: 'utf-8' codec can't decode byte 0xba in position 0: invalid start byte
166
+
167
+
168
+ Wide character strings
169
+ ======================
170
+
171
+ When a Python ``str`` is passed to a C++ function expecting ``std::wstring``,
172
+ ``wchar_t*``, ``std::u16string`` or ``std::u32string``, the ``str`` will be
173
+ encoded to UTF-16 or UTF-32 depending on how the C++ compiler implements each
174
+ type, in the platform's native endianness. When strings of these types are
175
+ returned, they are assumed to contain valid UTF-16 or UTF-32, and will be
176
+ decoded to Python ``str``.
177
+
178
+ .. code-block:: c++
179
+
180
+ #define UNICODE
181
+ #include <windows.h>
182
+
183
+ m.def("set_window_text",
184
+ [](HWND hwnd, std::wstring s) {
185
+ // Call SetWindowText with null-terminated UTF-16 string
186
+ ::SetWindowText(hwnd, s.c_str());
187
+ }
188
+ );
189
+ m.def("get_window_text",
190
+ [](HWND hwnd) {
191
+ const int buffer_size = ::GetWindowTextLength(hwnd) + 1;
192
+ auto buffer = std::make_unique< wchar_t[] >(buffer_size);
193
+
194
+ ::GetWindowText(hwnd, buffer.data(), buffer_size);
195
+
196
+ std::wstring text(buffer.get());
197
+
198
+ // wstring will be converted to Python str
199
+ return text;
200
+ }
201
+ );
202
+
203
+ Strings in multibyte encodings such as Shift-JIS must transcoded to a
204
+ UTF-8/16/32 before being returned to Python.
205
+
206
+
207
+ Character literals
208
+ ==================
209
+
210
+ C++ functions that accept character literals as input will receive the first
211
+ character of a Python ``str`` as their input. If the string is longer than one
212
+ Unicode character, trailing characters will be ignored.
213
+
214
+ When a character literal is returned from C++ (such as a ``char`` or a
215
+ ``wchar_t``), it will be converted to a ``str`` that represents the single
216
+ character.
217
+
218
+ .. code-block:: c++
219
+
220
+ m.def("pass_char", [](char c) { return c; });
221
+ m.def("pass_wchar", [](wchar_t w) { return w; });
222
+
223
+ .. code-block:: pycon
224
+
225
+ >>> example.pass_char("A")
226
+ 'A'
227
+
228
+ While C++ will cast integers to character types (``char c = 0x65;``), pybind11
229
+ does not convert Python integers to characters implicitly. The Python function
230
+ ``chr()`` can be used to convert integers to characters.
231
+
232
+ .. code-block:: pycon
233
+
234
+ >>> example.pass_char(0x65)
235
+ TypeError
236
+
237
+ >>> example.pass_char(chr(0x65))
238
+ 'A'
239
+
240
+ If the desire is to work with an 8-bit integer, use ``int8_t`` or ``uint8_t``
241
+ as the argument type.
242
+
243
+ Grapheme clusters
244
+ -----------------
245
+
246
+ A single grapheme may be represented by two or more Unicode characters. For
247
+ example 'é' is usually represented as U+00E9 but can also be expressed as the
248
+ combining character sequence U+0065 U+0301 (that is, the letter 'e' followed by
249
+ a combining acute accent). The combining character will be lost if the
250
+ two-character sequence is passed as an argument, even though it renders as a
251
+ single grapheme.
252
+
253
+ .. code-block:: pycon
254
+
255
+ >>> example.pass_wchar("é")
256
+ 'é'
257
+
258
+ >>> combining_e_acute = "e" + "\u0301"
259
+
260
+ >>> combining_e_acute
261
+ 'é'
262
+
263
+ >>> combining_e_acute == "é"
264
+ False
265
+
266
+ >>> example.pass_wchar(combining_e_acute)
267
+ 'e'
268
+
269
+ Normalizing combining characters before passing the character literal to C++
270
+ may resolve *some* of these issues:
271
+
272
+ .. code-block:: pycon
273
+
274
+ >>> example.pass_wchar(unicodedata.normalize("NFC", combining_e_acute))
275
+ 'é'
276
+
277
+ In some languages (Thai for example), there are `graphemes that cannot be
278
+ expressed as a single Unicode code point
279
+ <http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries>`_, so there is
280
+ no way to capture them in a C++ character type.
281
+
282
+
283
+ C++17 string views
284
+ ==================
285
+
286
+ C++17 string views are automatically supported when compiling in C++17 mode.
287
+ They follow the same rules for encoding and decoding as the corresponding STL
288
+ string type (for example, a ``std::u16string_view`` argument will be passed
289
+ UTF-16-encoded data, and a returned ``std::string_view`` will be decoded as
290
+ UTF-8).
291
+
292
+ References
293
+ ==========
294
+
295
+ * `The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) <https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/>`_
296
+ * `C++ - Using STL Strings at Win32 API Boundaries <https://msdn.microsoft.com/en-ca/magazine/mt238407.aspx>`_
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/classes.rst ADDED
@@ -0,0 +1,1413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Classes
2
+ #######
3
+
4
+ This section presents advanced binding code for classes and it is assumed
5
+ that you are already familiar with the basics from :doc:`/classes`.
6
+
7
+ .. _overriding_virtuals:
8
+
9
+ Overriding virtual functions in Python
10
+ ======================================
11
+
12
+ Suppose that a C++ class or interface has a virtual function that we'd like
13
+ to override from within Python (we'll focus on the class ``Animal``; ``Dog`` is
14
+ given as a specific example of how one would do this with traditional C++
15
+ code).
16
+
17
+ .. code-block:: cpp
18
+
19
+ class Animal {
20
+ public:
21
+ virtual ~Animal() { }
22
+ virtual std::string go(int n_times) = 0;
23
+ };
24
+
25
+ class Dog : public Animal {
26
+ public:
27
+ std::string go(int n_times) override {
28
+ std::string result;
29
+ for (int i=0; i<n_times; ++i)
30
+ result += "woof! ";
31
+ return result;
32
+ }
33
+ };
34
+
35
+ Let's also suppose that we are given a plain function which calls the
36
+ function ``go()`` on an arbitrary ``Animal`` instance.
37
+
38
+ .. code-block:: cpp
39
+
40
+ std::string call_go(Animal *animal) {
41
+ return animal->go(3);
42
+ }
43
+
44
+ Normally, the binding code for these classes would look as follows:
45
+
46
+ .. code-block:: cpp
47
+
48
+ PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {
49
+ py::class_<Animal>(m, "Animal")
50
+ .def("go", &Animal::go);
51
+
52
+ py::class_<Dog, Animal>(m, "Dog")
53
+ .def(py::init<>());
54
+
55
+ m.def("call_go", &call_go);
56
+ }
57
+
58
+ However, these bindings are impossible to extend: ``Animal`` is not
59
+ constructible, and we clearly require some kind of "trampoline" that
60
+ redirects virtual calls back to Python.
61
+
62
+ Defining a new type of ``Animal`` from within Python is possible but requires a
63
+ helper class that is defined as follows:
64
+
65
+ .. code-block:: cpp
66
+
67
+ class PyAnimal : public Animal, public py::trampoline_self_life_support {
68
+ public:
69
+ /* Inherit the constructors */
70
+ using Animal::Animal;
71
+
72
+ /* Trampoline (need one for each virtual function) */
73
+ std::string go(int n_times) override {
74
+ PYBIND11_OVERRIDE_PURE(
75
+ std::string, /* Return type */
76
+ Animal, /* Parent class */
77
+ go, /* Name of function in C++ (must match Python name) */
78
+ n_times /* Argument(s) */
79
+ );
80
+ }
81
+ };
82
+
83
+ The ``py::trampoline_self_life_support`` base class is needed to ensure
84
+ that a ``std::unique_ptr`` can safely be passed between Python and C++. To
85
+ help you steer clear of notorious pitfalls (e.g. inheritance slicing),
86
+ pybind11 enforces that trampoline classes inherit from
87
+ ``py::trampoline_self_life_support`` if used in in combination with
88
+ ``py::smart_holder``.
89
+
90
+ .. note::
91
+ For completeness, the base class has no effect if a holder other than
92
+ ``py::smart_holder`` used, including the default ``std::unique_ptr<T>``.
93
+ To avoid confusion, pybind11 will fail to compile bindings that combine
94
+ ``py::trampoline_self_life_support`` with a holder other than
95
+ ``py::smart_holder``.
96
+
97
+ Please think twice, though, before deciding to not use the safer
98
+ ``py::smart_holder``. The pitfalls associated with avoiding it are very
99
+ real, and the overhead for using it is very likely in the noise.
100
+
101
+ The macro :c:macro:`PYBIND11_OVERRIDE_PURE` should be used for pure virtual
102
+ functions, and :c:macro:`PYBIND11_OVERRIDE` should be used for functions which have
103
+ a default implementation. There are also two alternate macros
104
+ :c:macro:`PYBIND11_OVERRIDE_PURE_NAME` and :c:macro:`PYBIND11_OVERRIDE_NAME` which
105
+ take a string-valued name argument between the *Parent class* and *Name of the
106
+ function* slots, which defines the name of function in Python. This is required
107
+ when the C++ and Python versions of the
108
+ function have different names, e.g. ``operator()`` vs ``__call__``.
109
+
110
+ The binding code also needs a few minor adaptations (highlighted):
111
+
112
+ .. code-block:: cpp
113
+ :emphasize-lines: 2,3
114
+
115
+ PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {
116
+ py::class_<Animal, PyAnimal /* <--- trampoline */, py::smart_holder>(m, "Animal")
117
+ .def(py::init<>())
118
+ .def("go", &Animal::go);
119
+
120
+ py::class_<Dog, Animal, py::smart_holder>(m, "Dog")
121
+ .def(py::init<>());
122
+
123
+ m.def("call_go", &call_go);
124
+ }
125
+
126
+ Importantly, pybind11 is made aware of the trampoline helper class by
127
+ specifying it as an extra template argument to ``py::class_``. (This can also
128
+ be combined with other template arguments such as a custom holder type; the
129
+ order of template types does not matter). Following this, we are able to
130
+ define a constructor as usual.
131
+
132
+ Bindings should be made against the actual class, not the trampoline helper class.
133
+
134
+ .. code-block:: cpp
135
+ :emphasize-lines: 3
136
+
137
+ py::class_<Animal, PyAnimal /* <--- trampoline */, py::smart_holder>(m, "Animal");
138
+ .def(py::init<>())
139
+ .def("go", &Animal::go); /* <--- DO NOT USE &PyAnimal::go HERE */
140
+
141
+ Note, however, that the above is sufficient for allowing python classes to
142
+ extend ``Animal``, but not ``Dog``: see :ref:`virtual_and_inheritance` for the
143
+ necessary steps required to providing proper overriding support for inherited
144
+ classes.
145
+
146
+ The Python session below shows how to override ``Animal::go`` and invoke it via
147
+ a virtual method call.
148
+
149
+ .. code-block:: pycon
150
+
151
+ >>> from example import *
152
+ >>> d = Dog()
153
+ >>> call_go(d)
154
+ 'woof! woof! woof! '
155
+ >>> class Cat(Animal):
156
+ ... def go(self, n_times):
157
+ ... return "meow! " * n_times
158
+ ...
159
+ >>> c = Cat()
160
+ >>> call_go(c)
161
+ 'meow! meow! meow! '
162
+
163
+ If you are defining a custom constructor in a derived Python class, you *must*
164
+ ensure that you explicitly call the bound C++ constructor using ``__init__``,
165
+ *regardless* of whether it is a default constructor or not. Otherwise, the
166
+ memory for the C++ portion of the instance will be left uninitialized, which
167
+ will generally leave the C++ instance in an invalid state and cause undefined
168
+ behavior if the C++ instance is subsequently used.
169
+
170
+ .. versionchanged:: 2.6
171
+ The default pybind11 metaclass will throw a ``TypeError`` when it detects
172
+ that ``__init__`` was not called by a derived class.
173
+
174
+ Here is an example:
175
+
176
+ .. code-block:: python
177
+
178
+ class Dachshund(Dog):
179
+ def __init__(self, name):
180
+ Dog.__init__(self) # Without this, a TypeError is raised.
181
+ self.name = name
182
+
183
+ def bark(self):
184
+ return "yap!"
185
+
186
+ Note that a direct ``__init__`` constructor *should be called*, and ``super()``
187
+ should not be used. For simple cases of linear inheritance, ``super()``
188
+ may work, but once you begin mixing Python and C++ multiple inheritance,
189
+ things will fall apart due to differences between Python's MRO and C++'s
190
+ mechanisms.
191
+
192
+ Please take a look at the :ref:`macro_notes` before using this feature.
193
+
194
+ .. note::
195
+
196
+ When the overridden type returns a reference or pointer to a type that
197
+ pybind11 converts from Python (for example, numeric values, std::string,
198
+ and other built-in value-converting types), there are some limitations to
199
+ be aware of:
200
+
201
+ - because in these cases there is no C++ variable to reference (the value
202
+ is stored in the referenced Python variable), pybind11 provides one in
203
+ the PYBIND11_OVERRIDE macros (when needed) with static storage duration.
204
+ Note that this means that invoking the overridden method on *any*
205
+ instance will change the referenced value stored in *all* instances of
206
+ that type.
207
+
208
+ - Attempts to modify a non-const reference will not have the desired
209
+ effect: it will change only the static cache variable, but this change
210
+ will not propagate to underlying Python instance, and the change will be
211
+ replaced the next time the override is invoked.
212
+
213
+ .. warning::
214
+
215
+ The :c:macro:`PYBIND11_OVERRIDE` and accompanying macros used to be called
216
+ ``PYBIND11_OVERLOAD`` up until pybind11 v2.5.0, and :func:`get_override`
217
+ used to be called ``get_overload``. This naming was corrected and the older
218
+ macro and function names may soon be deprecated, in order to reduce
219
+ confusion with overloaded functions and methods and ``py::overload_cast``
220
+ (see :ref:`classes`).
221
+
222
+ .. seealso::
223
+
224
+ The file :file:`tests/test_virtual_functions.cpp` contains a complete
225
+ example that demonstrates how to override virtual functions using pybind11
226
+ in more detail.
227
+
228
+ .. _virtual_and_inheritance:
229
+
230
+ Combining virtual functions and inheritance
231
+ ===========================================
232
+
233
+ When combining virtual methods with inheritance, you need to be sure to provide
234
+ an override for each method for which you want to allow overrides from derived
235
+ python classes. For example, suppose we extend the above ``Animal``/``Dog``
236
+ example as follows:
237
+
238
+ .. code-block:: cpp
239
+
240
+ class Animal {
241
+ public:
242
+ virtual std::string go(int n_times) = 0;
243
+ virtual std::string name() { return "unknown"; }
244
+ };
245
+ class Dog : public Animal {
246
+ public:
247
+ std::string go(int n_times) override {
248
+ std::string result;
249
+ for (int i=0; i<n_times; ++i)
250
+ result += bark() + " ";
251
+ return result;
252
+ }
253
+ virtual std::string bark() { return "woof!"; }
254
+ };
255
+
256
+ then the trampoline class for ``Animal`` must, as described in the previous
257
+ section, override ``go()`` and ``name()``, but in order to allow python code to
258
+ inherit properly from ``Dog``, we also need a trampoline class for ``Dog`` that
259
+ overrides both the added ``bark()`` method *and* the ``go()`` and ``name()``
260
+ methods inherited from ``Animal`` (even though ``Dog`` doesn't directly
261
+ override the ``name()`` method):
262
+
263
+ .. code-block:: cpp
264
+
265
+ class PyAnimal : public Animal, public py::trampoline_self_life_support {
266
+ public:
267
+ using Animal::Animal; // Inherit constructors
268
+ std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Animal, go, n_times); }
269
+ std::string name() override { PYBIND11_OVERRIDE(std::string, Animal, name, ); }
270
+ };
271
+ class PyDog : public Dog, public py::trampoline_self_life_support {
272
+ public:
273
+ using Dog::Dog; // Inherit constructors
274
+ std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, Dog, go, n_times); }
275
+ std::string name() override { PYBIND11_OVERRIDE(std::string, Dog, name, ); }
276
+ std::string bark() override { PYBIND11_OVERRIDE(std::string, Dog, bark, ); }
277
+ };
278
+
279
+ .. note::
280
+
281
+ Note the trailing commas in the ``PYBIND11_OVERRIDE`` calls to ``name()``
282
+ and ``bark()``. These are needed to portably implement a trampoline for a
283
+ function that does not take any arguments. For functions that take
284
+ a nonzero number of arguments, the trailing comma must be omitted.
285
+
286
+ A registered class derived from a pybind11-registered class with virtual
287
+ methods requires a similar trampoline class, *even if* it doesn't explicitly
288
+ declare or override any virtual methods itself:
289
+
290
+ .. code-block:: cpp
291
+
292
+ class Husky : public Dog {};
293
+ class PyHusky : public Husky, public py::trampoline_self_life_support {
294
+ public:
295
+ using Husky::Husky; // Inherit constructors
296
+ std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Husky, go, n_times); }
297
+ std::string name() override { PYBIND11_OVERRIDE(std::string, Husky, name, ); }
298
+ std::string bark() override { PYBIND11_OVERRIDE(std::string, Husky, bark, ); }
299
+ };
300
+
301
+ There is, however, a technique that can be used to avoid this duplication
302
+ (which can be especially helpful for a base class with several virtual
303
+ methods). The technique involves using template trampoline classes, as
304
+ follows:
305
+
306
+ .. code-block:: cpp
307
+
308
+ template <class AnimalBase = Animal>
309
+ class PyAnimal : public AnimalBase, public py::trampoline_self_life_support {
310
+ public:
311
+ using AnimalBase::AnimalBase; // Inherit constructors
312
+ std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, AnimalBase, go, n_times); }
313
+ std::string name() override { PYBIND11_OVERRIDE(std::string, AnimalBase, name, ); }
314
+ };
315
+ template <class DogBase = Dog>
316
+ class PyDog : public PyAnimal<DogBase>, public py::trampoline_self_life_support {
317
+ public:
318
+ using PyAnimal<DogBase>::PyAnimal; // Inherit constructors
319
+ // Override PyAnimal's pure virtual go() with a non-pure one:
320
+ std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, DogBase, go, n_times); }
321
+ std::string bark() override { PYBIND11_OVERRIDE(std::string, DogBase, bark, ); }
322
+ };
323
+
324
+ This technique has the advantage of requiring just one trampoline method to be
325
+ declared per virtual method and pure virtual method override. It does,
326
+ however, require the compiler to generate at least as many methods (and
327
+ possibly more, if both pure virtual and overridden pure virtual methods are
328
+ exposed, as above).
329
+
330
+ The classes are then registered with pybind11 using:
331
+
332
+ .. code-block:: cpp
333
+
334
+ py::class_<Animal, PyAnimal<>, py::smart_holder> animal(m, "Animal");
335
+ py::class_<Dog, Animal, PyDog<>, py::smart_holder> dog(m, "Dog");
336
+ py::class_<Husky, Dog, PyDog<Husky>, py::smart_holder> husky(m, "Husky");
337
+ // ... add animal, dog, husky definitions
338
+
339
+ Note that ``Husky`` did not require a dedicated trampoline template class at
340
+ all, since it neither declares any new virtual methods nor provides any pure
341
+ virtual method implementations.
342
+
343
+ With either the repeated-virtuals or templated trampoline methods in place, you
344
+ can now create a python class that inherits from ``Dog``:
345
+
346
+ .. code-block:: python
347
+
348
+ class ShihTzu(Dog):
349
+ def bark(self):
350
+ return "yip!"
351
+
352
+ .. seealso::
353
+
354
+ See the file :file:`tests/test_virtual_functions.cpp` for complete examples
355
+ using both the duplication and templated trampoline approaches.
356
+
357
+ .. _extended_aliases:
358
+
359
+ Extended trampoline class functionality
360
+ =======================================
361
+
362
+ .. _extended_class_functionality_forced_trampoline:
363
+
364
+ Forced trampoline class initialisation
365
+ --------------------------------------
366
+ The trampoline classes described in the previous sections are, by default, only
367
+ initialized when needed. More specifically, they are initialized when a python
368
+ class actually inherits from a registered type (instead of merely creating an
369
+ instance of the registered type), or when a registered constructor is only
370
+ valid for the trampoline class but not the registered class. This is primarily
371
+ for performance reasons: when the trampoline class is not needed for anything
372
+ except virtual method dispatching, not initializing the trampoline class
373
+ improves performance by avoiding needing to do a run-time check to see if the
374
+ inheriting python instance has an overridden method.
375
+
376
+ Sometimes, however, it is useful to always initialize a trampoline class as an
377
+ intermediate class that does more than just handle virtual method dispatching.
378
+ For example, such a class might perform extra class initialization, extra
379
+ destruction operations, and might define new members and methods to enable a
380
+ more python-like interface to a class.
381
+
382
+ In order to tell pybind11 that it should *always* initialize the trampoline
383
+ class when creating new instances of a type, the class constructors should be
384
+ declared using ``py::init_alias<Args, ...>()`` instead of the usual
385
+ ``py::init<Args, ...>()``. This forces construction via the trampoline class,
386
+ ensuring member initialization and (eventual) destruction.
387
+
388
+ .. seealso::
389
+
390
+ See the file :file:`tests/test_virtual_functions.cpp` for complete examples
391
+ showing both normal and forced trampoline instantiation.
392
+
393
+ Different method signatures
394
+ ---------------------------
395
+ The macro's introduced in :ref:`overriding_virtuals` cover most of the standard
396
+ use cases when exposing C++ classes to Python. Sometimes it is hard or unwieldy
397
+ to create a direct one-on-one mapping between the arguments and method return
398
+ type.
399
+
400
+ An example would be when the C++ signature contains output arguments using
401
+ references (See also :ref:`faq_reference_arguments`). Another way of solving
402
+ this is to use the method body of the trampoline class to do conversions to the
403
+ input and return of the Python method.
404
+
405
+ The main building block to do so is the :func:`get_override`, this function
406
+ allows retrieving a method implemented in Python from within the trampoline's
407
+ methods. Consider for example a C++ method which has the signature
408
+ ``bool myMethod(int32_t& value)``, where the return indicates whether
409
+ something should be done with the ``value``. This can be made convenient on the
410
+ Python side by allowing the Python function to return ``None`` or an ``int``:
411
+
412
+ .. code-block:: cpp
413
+
414
+ bool MyClass::myMethod(int32_t& value)
415
+ {
416
+ pybind11::gil_scoped_acquire gil; // Acquire the GIL while in this scope.
417
+ // Try to look up the overridden method on the Python side.
418
+ pybind11::function override = pybind11::get_override(this, "myMethod");
419
+ if (override) { // method is found
420
+ auto obj = override(value); // Call the Python function.
421
+ if (py::isinstance<py::int_>(obj)) { // check if it returned a Python integer type
422
+ value = obj.cast<int32_t>(); // Cast it and assign it to the value.
423
+ return true; // Return true; value should be used.
424
+ } else {
425
+ return false; // Python returned none, return false.
426
+ }
427
+ }
428
+ return false; // Alternatively return MyClass::myMethod(value);
429
+ }
430
+
431
+ Avoiding Inheritance Slicing and ``std::weak_ptr`` surprises
432
+ ------------------------------------------------------------
433
+
434
+ When working with classes that use virtual functions and are subclassed
435
+ in Python, special care must be taken when converting Python objects to
436
+ ``std::shared_ptr<T>``. Depending on whether the class uses a plain
437
+ ``std::shared_ptr`` holder or ``py::smart_holder``, the resulting
438
+ ``shared_ptr`` may either allow inheritance slicing or lead to potentially
439
+ surprising behavior when constructing ``std::weak_ptr`` instances.
440
+
441
+ This section explains how ``std::shared_ptr`` and ``py::smart_holder`` manage
442
+ object lifetimes differently, how these differences affect trampoline-derived
443
+ objects, and what options are available to achieve the situation-specific
444
+ desired behavior.
445
+
446
+ When using ``std::shared_ptr`` as the holder type, converting a Python object
447
+ to a ``std::shared_ptr<T>`` (e.g., ``obj.cast<std::shared_ptr<T>>()``, or simply
448
+ passing the Python object as an argument to a ``.def()``-ed function) returns
449
+ a ``shared_ptr`` that shares ownership with the original ``class_`` holder,
450
+ usually preserving object lifetime. However, for Python classes that derive from
451
+ a trampoline, if the Python object is destroyed, only the base C++ object may
452
+ remain alive, leading to inheritance slicing
453
+ (see `#1333 <https://github.com/pybind/pybind11/issues/1333>`_).
454
+
455
+ In contrast, with ``py::smart_holder``, converting a Python object to
456
+ a ``std::shared_ptr<T>`` returns a new ``shared_ptr`` with an independent
457
+ control block that keeps the derived Python object alive. This avoids
458
+ inheritance slicing but can lead to unintended behavior when creating
459
+ ``std::weak_ptr`` instances
460
+ (see `#5623 <https://github.com/pybind/pybind11/issues/5623>`_).
461
+
462
+ If it is necessary to obtain a ``std::weak_ptr`` that shares the control block
463
+ with the ``smart_holder``—at the cost of reintroducing potential inheritance
464
+ slicing—you can use ``py::potentially_slicing_weak_ptr<T>(obj)``.
465
+
466
+ When precise lifetime management of derived Python objects is important,
467
+ using a Python-side ``weakref`` is the most reliable approach, as it avoids
468
+ both inheritance slicing and unintended interactions with ``std::weak_ptr``
469
+ semantics in C++.
470
+
471
+ .. seealso::
472
+
473
+ * :func:`potentially_slicing_weak_ptr` C++ documentation
474
+ * :file:`tests/test_potentially_slicing_weak_ptr.cpp`
475
+
476
+
477
+ .. _custom_constructors:
478
+
479
+ Custom constructors
480
+ ===================
481
+
482
+ The syntax for binding constructors was previously introduced, but it only
483
+ works when a constructor of the appropriate arguments actually exists on the
484
+ C++ side. To extend this to more general cases, pybind11 makes it possible
485
+ to bind factory functions as constructors. For example, suppose you have a
486
+ class like this:
487
+
488
+ .. code-block:: cpp
489
+
490
+ class Example {
491
+ private:
492
+ Example(int); // private constructor
493
+ public:
494
+ // Factory function:
495
+ static Example create(int a) { return Example(a); }
496
+ };
497
+
498
+ py::class_<Example>(m, "Example")
499
+ .def(py::init(&Example::create));
500
+
501
+ While it is possible to create a straightforward binding of the static
502
+ ``create`` method, it may sometimes be preferable to expose it as a constructor
503
+ on the Python side. This can be accomplished by calling ``.def(py::init(...))``
504
+ with the function reference returning the new instance passed as an argument.
505
+ It is also possible to use this approach to bind a function returning a new
506
+ instance by raw pointer or by the holder (e.g. ``std::unique_ptr``).
507
+
508
+ The following example shows the different approaches:
509
+
510
+ .. code-block:: cpp
511
+
512
+ class Example {
513
+ private:
514
+ Example(int); // private constructor
515
+ public:
516
+ // Factory function - returned by value:
517
+ static Example create(int a) { return Example(a); }
518
+
519
+ // These constructors are publicly callable:
520
+ Example(double);
521
+ Example(int, int);
522
+ Example(std::string);
523
+ };
524
+
525
+ py::class_<Example>(m, "Example")
526
+ // Bind the factory function as a constructor:
527
+ .def(py::init(&Example::create))
528
+ // Bind a lambda function returning a pointer wrapped in a holder:
529
+ .def(py::init([](std::string arg) {
530
+ return std::unique_ptr<Example>(new Example(arg));
531
+ }))
532
+ // Return a raw pointer:
533
+ .def(py::init([](int a, int b) { return new Example(a, b); }))
534
+ // You can mix the above with regular C++ constructor bindings as well:
535
+ .def(py::init<double>())
536
+ ;
537
+
538
+ When the constructor is invoked from Python, pybind11 will call the factory
539
+ function and store the resulting C++ instance in the Python instance.
540
+
541
+ When combining factory functions constructors with :ref:`virtual function
542
+ trampolines <overriding_virtuals>` there are two approaches. The first is to
543
+ add a constructor to the alias class that takes a base value by
544
+ rvalue-reference. If such a constructor is available, it will be used to
545
+ construct an alias instance from the value returned by the factory function.
546
+ The second option is to provide two factory functions to ``py::init()``: the
547
+ first will be invoked when no alias class is required (i.e. when the class is
548
+ being used but not inherited from in Python), and the second will be invoked
549
+ when an alias is required.
550
+
551
+ You can also specify a single factory function that always returns an alias
552
+ instance: this will result in behaviour similar to ``py::init_alias<...>()``,
553
+ as described in the :ref:`extended trampoline class documentation
554
+ <extended_aliases>`.
555
+
556
+ The following example shows the different factory approaches for a class with
557
+ an alias:
558
+
559
+ .. code-block:: cpp
560
+
561
+ #include <pybind11/factory.h>
562
+ class Example {
563
+ public:
564
+ // ...
565
+ virtual ~Example() = default;
566
+ };
567
+ class PyExample : public Example, public py::trampoline_self_life_support {
568
+ public:
569
+ using Example::Example;
570
+ PyExample(Example &&base) : Example(std::move(base)) {}
571
+ };
572
+ py::class_<Example, PyExample, py::smart_holder>(m, "Example")
573
+ // Returns an Example pointer. If a PyExample is needed, the Example
574
+ // instance will be moved via the extra constructor in PyExample, above.
575
+ .def(py::init([]() { return new Example(); }))
576
+ // Two callbacks:
577
+ .def(py::init([]() { return new Example(); } /* no alias needed */,
578
+ []() { return new PyExample(); } /* alias needed */))
579
+ // *Always* returns an alias instance (like py::init_alias<>())
580
+ .def(py::init([]() { return new PyExample(); }))
581
+ ;
582
+
583
+ Brace initialization
584
+ --------------------
585
+
586
+ ``pybind11::init<>`` internally uses C++11 brace initialization to call the
587
+ constructor of the target class. This means that it can be used to bind
588
+ *implicit* constructors as well:
589
+
590
+ .. code-block:: cpp
591
+
592
+ struct Aggregate {
593
+ int a;
594
+ std::string b;
595
+ };
596
+
597
+ py::class_<Aggregate>(m, "Aggregate")
598
+ .def(py::init<int, const std::string &>());
599
+
600
+ .. note::
601
+
602
+ Note that brace initialization preferentially invokes constructor overloads
603
+ taking a ``std::initializer_list``. In the rare event that this causes an
604
+ issue, you can work around it by using ``py::init(...)`` with a lambda
605
+ function that constructs the new object as desired.
606
+
607
+ .. _classes_with_non_public_destructors:
608
+
609
+ Non-public destructors
610
+ ======================
611
+
612
+ If a class has a private or protected destructor (as might e.g. be the case in
613
+ a singleton pattern), a compile error will occur when creating bindings via
614
+ pybind11. The underlying issue is that the ``std::unique_ptr`` holder type that
615
+ is responsible for managing the lifetime of instances will reference the
616
+ destructor even if no deallocations ever take place. In order to expose classes
617
+ with private or protected destructors, it is possible to override the holder
618
+ type via a holder type argument to ``py::class_``. Pybind11 provides a helper
619
+ class ``py::nodelete`` that disables any destructor invocations. In this case,
620
+ it is crucial that instances are deallocated on the C++ side to avoid memory
621
+ leaks.
622
+
623
+ .. code-block:: cpp
624
+
625
+ /* ... definition ... */
626
+
627
+ class MyClass {
628
+ private:
629
+ ~MyClass() { }
630
+ };
631
+
632
+ /* ... binding code ... */
633
+
634
+ py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
635
+ .def(py::init<>())
636
+
637
+ .. _destructors_that_call_python:
638
+
639
+ Destructors that call Python
640
+ ============================
641
+
642
+ If a Python function is invoked from a C++ destructor, an exception may be thrown
643
+ of type :class:`error_already_set`. If this error is thrown out of a class destructor,
644
+ ``std::terminate()`` will be called, terminating the process. Class destructors
645
+ must catch all exceptions of type :class:`error_already_set` to discard the Python
646
+ exception using :func:`error_already_set::discard_as_unraisable`.
647
+
648
+ Every Python function should be treated as *possibly throwing*. When a Python generator
649
+ stops yielding items, Python will throw a ``StopIteration`` exception, which can pass
650
+ though C++ destructors if the generator's stack frame holds the last reference to C++
651
+ objects.
652
+
653
+ For more information, see :ref:`the documentation on exceptions <unraisable_exceptions>`.
654
+
655
+ .. code-block:: cpp
656
+
657
+ class MyClass {
658
+ public:
659
+ ~MyClass() {
660
+ try {
661
+ py::print("Even printing is dangerous in a destructor");
662
+ py::exec("raise ValueError('This is an unraisable exception')");
663
+ } catch (py::error_already_set &e) {
664
+ // error_context should be information about where/why the occurred,
665
+ // e.g. use __func__ to get the name of the current function
666
+ e.discard_as_unraisable(__func__);
667
+ }
668
+ }
669
+ };
670
+
671
+ .. note::
672
+
673
+ pybind11 does not support C++ destructors marked ``noexcept(false)``.
674
+
675
+ .. versionadded:: 2.6
676
+
677
+ .. _implicit_conversions:
678
+
679
+ Implicit conversions
680
+ ====================
681
+
682
+ Suppose that instances of two types ``A`` and ``B`` are used in a project, and
683
+ that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
684
+ could be a fixed and an arbitrary precision number type).
685
+
686
+ .. code-block:: cpp
687
+
688
+ py::class_<A>(m, "A")
689
+ /// ... members ...
690
+
691
+ py::class_<B>(m, "B")
692
+ .def(py::init<A>())
693
+ /// ... members ...
694
+
695
+ m.def("func",
696
+ [](const B &) { /* .... */ }
697
+ );
698
+
699
+ To invoke the function ``func`` using a variable ``a`` containing an ``A``
700
+ instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
701
+ will automatically apply an implicit type conversion, which makes it possible
702
+ to directly write ``func(a)``.
703
+
704
+ In this situation (i.e. where ``B`` has a constructor that converts from
705
+ ``A``), the following statement enables similar implicit conversions on the
706
+ Python side:
707
+
708
+ .. code-block:: cpp
709
+
710
+ py::implicitly_convertible<A, B>();
711
+
712
+ .. note::
713
+
714
+ Implicit conversions from ``A`` to ``B`` only work when ``B`` is a custom
715
+ data type that is exposed to Python via pybind11.
716
+
717
+ To prevent runaway recursion, implicit conversions are non-reentrant: an
718
+ implicit conversion invoked as part of another implicit conversion of the
719
+ same type (i.e. from ``A`` to ``B``) will fail.
720
+
721
+ .. _static_properties:
722
+
723
+ Static properties
724
+ =================
725
+
726
+ The section on :ref:`properties` discussed the creation of instance properties
727
+ that are implemented in terms of C++ getters and setters.
728
+
729
+ Static properties can also be created in a similar way to expose getters and
730
+ setters of static class attributes. Note that the implicit ``self`` argument
731
+ also exists in this case and is used to pass the Python ``type`` subclass
732
+ instance. This parameter will often not be needed by the C++ side, and the
733
+ following example illustrates how to instantiate a lambda getter function
734
+ that ignores it:
735
+
736
+ .. code-block:: cpp
737
+
738
+ py::class_<Foo>(m, "Foo")
739
+ .def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
740
+
741
+ Operator overloading
742
+ ====================
743
+
744
+ Suppose that we're given the following ``Vector2`` class with a vector addition
745
+ and scalar multiplication operation, all implemented using overloaded operators
746
+ in C++.
747
+
748
+ .. code-block:: cpp
749
+
750
+ class Vector2 {
751
+ public:
752
+ Vector2(float x, float y) : x(x), y(y) { }
753
+
754
+ Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
755
+ Vector2 operator*(float value) const { return Vector2(x * value, y * value); }
756
+ Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
757
+ Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
758
+
759
+ friend Vector2 operator*(float f, const Vector2 &v) {
760
+ return Vector2(f * v.x, f * v.y);
761
+ }
762
+
763
+ std::string toString() const {
764
+ return "[" + std::to_string(x) + ", " + std::to_string(y) + "]";
765
+ }
766
+ private:
767
+ float x, y;
768
+ };
769
+
770
+ The following snippet shows how the above operators can be conveniently exposed
771
+ to Python.
772
+
773
+ .. code-block:: cpp
774
+
775
+ #include <pybind11/operators.h>
776
+
777
+ PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {
778
+ py::class_<Vector2>(m, "Vector2")
779
+ .def(py::init<float, float>())
780
+ .def(py::self + py::self)
781
+ .def(py::self += py::self)
782
+ .def(py::self *= float())
783
+ .def(float() * py::self)
784
+ .def(py::self * float())
785
+ .def(-py::self)
786
+ .def("__repr__", &Vector2::toString);
787
+ }
788
+
789
+ Note that a line like
790
+
791
+ .. code-block:: cpp
792
+
793
+ .def(py::self * float())
794
+
795
+ is really just short hand notation for
796
+
797
+ .. code-block:: cpp
798
+
799
+ .def("__mul__", [](const Vector2 &a, float b) {
800
+ return a * b;
801
+ }, py::is_operator())
802
+
803
+ This can be useful for exposing additional operators that don't exist on the
804
+ C++ side, or to perform other types of customization. The ``py::is_operator``
805
+ flag marker is needed to inform pybind11 that this is an operator, which
806
+ returns ``NotImplemented`` when invoked with incompatible arguments rather than
807
+ throwing a type error.
808
+
809
+ .. note::
810
+
811
+ To use the more convenient ``py::self`` notation, the additional
812
+ header file :file:`pybind11/operators.h` must be included.
813
+
814
+ .. seealso::
815
+
816
+ The file :file:`tests/test_operator_overloading.cpp` contains a
817
+ complete example that demonstrates how to work with overloaded operators in
818
+ more detail.
819
+
820
+ .. _pickling:
821
+
822
+ Pickling support
823
+ ================
824
+
825
+ Python's ``pickle`` module provides a powerful facility to serialize and
826
+ de-serialize a Python object graph into a binary data stream. To pickle and
827
+ unpickle C++ classes using pybind11, a ``py::pickle()`` definition must be
828
+ provided. Suppose the class in question has the following signature:
829
+
830
+ .. code-block:: cpp
831
+
832
+ class Pickleable {
833
+ public:
834
+ Pickleable(const std::string &value) : m_value(value) { }
835
+ const std::string &value() const { return m_value; }
836
+
837
+ void setExtra(int extra) { m_extra = extra; }
838
+ int extra() const { return m_extra; }
839
+ private:
840
+ std::string m_value;
841
+ int m_extra = 0;
842
+ };
843
+
844
+ Pickling support in Python is enabled by defining the ``__setstate__`` and
845
+ ``__getstate__`` methods [#f3]_. For pybind11 classes, use ``py::pickle()``
846
+ to bind these two functions:
847
+
848
+ .. code-block:: cpp
849
+
850
+ py::class_<Pickleable>(m, "Pickleable")
851
+ .def(py::init<std::string>())
852
+ .def("value", &Pickleable::value)
853
+ .def("extra", &Pickleable::extra)
854
+ .def("setExtra", &Pickleable::setExtra)
855
+ .def(py::pickle(
856
+ [](const Pickleable &p) { // __getstate__
857
+ /* Return a tuple that fully encodes the state of the object */
858
+ return py::make_tuple(p.value(), p.extra());
859
+ },
860
+ [](py::tuple t) { // __setstate__
861
+ if (t.size() != 2)
862
+ throw std::runtime_error("Invalid state!");
863
+
864
+ /* Create a new C++ instance */
865
+ Pickleable p(t[0].cast<std::string>());
866
+
867
+ /* Assign any additional state */
868
+ p.setExtra(t[1].cast<int>());
869
+
870
+ return p;
871
+ }
872
+ ));
873
+
874
+ The ``__setstate__`` part of the ``py::pickle()`` definition follows the same
875
+ rules as the single-argument version of ``py::init()``. The return type can be
876
+ a value, pointer or holder type. See :ref:`custom_constructors` for details.
877
+
878
+ An instance can now be pickled as follows:
879
+
880
+ .. code-block:: python
881
+
882
+ import pickle
883
+
884
+ p = Pickleable("test_value")
885
+ p.setExtra(15)
886
+ data = pickle.dumps(p)
887
+
888
+
889
+ .. note::
890
+ If given, the second argument to ``dumps`` must be 2 or larger - 0 and 1 are
891
+ not supported. Newer versions are also fine; for instance, specify ``-1`` to
892
+ always use the latest available version. Beware: failure to follow these
893
+ instructions will cause important pybind11 memory allocation routines to be
894
+ skipped during unpickling, which will likely lead to memory corruption
895
+ and/or segmentation faults.
896
+
897
+ .. seealso::
898
+
899
+ The file :file:`tests/test_pickling.cpp` contains a complete example
900
+ that demonstrates how to pickle and unpickle types using pybind11 in more
901
+ detail.
902
+
903
+ .. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances
904
+
905
+ Deepcopy support
906
+ ================
907
+
908
+ Python normally uses references in assignments. Sometimes a real copy is needed
909
+ to prevent changing all copies. The ``copy`` module [#f5]_ provides these
910
+ capabilities.
911
+
912
+ A class with pickle support is automatically also (deep)copy
913
+ compatible. However, performance can be improved by adding custom
914
+ ``__copy__`` and ``__deepcopy__`` methods.
915
+
916
+ For simple classes (deep)copy can be enabled by using the copy constructor,
917
+ which should look as follows:
918
+
919
+ .. code-block:: cpp
920
+
921
+ py::class_<Copyable>(m, "Copyable")
922
+ .def("__copy__", [](const Copyable &self) {
923
+ return Copyable(self);
924
+ })
925
+ .def("__deepcopy__", [](const Copyable &self, py::dict) {
926
+ return Copyable(self);
927
+ }, "memo"_a);
928
+
929
+ .. note::
930
+
931
+ Dynamic attributes will not be copied in this example.
932
+
933
+ .. [#f5] https://docs.python.org/3/library/copy.html
934
+
935
+ Multiple Inheritance
936
+ ====================
937
+
938
+ pybind11 can create bindings for types that derive from multiple base types
939
+ (aka. *multiple inheritance*). To do so, specify all bases in the template
940
+ arguments of the ``py::class_`` declaration:
941
+
942
+ .. code-block:: cpp
943
+
944
+ py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, "MyType")
945
+ ...
946
+
947
+ The base types can be specified in arbitrary order, and they can even be
948
+ interspersed with alias types and holder types (discussed earlier in this
949
+ document)---pybind11 will automatically find out which is which. The only
950
+ requirement is that the first template argument is the type to be declared.
951
+
952
+ It is also permitted to inherit multiply from exported C++ classes in Python,
953
+ as well as inheriting from multiple Python and/or pybind11-exported classes.
954
+
955
+ There is one caveat regarding the implementation of this feature:
956
+
957
+ When only one base type is specified for a C++ type that actually has multiple
958
+ bases, pybind11 will assume that it does not participate in multiple
959
+ inheritance, which can lead to undefined behavior. In such cases, add the tag
960
+ ``multiple_inheritance`` to the class constructor:
961
+
962
+ .. code-block:: cpp
963
+
964
+ py::class_<MyType, BaseType2>(m, "MyType", py::multiple_inheritance());
965
+
966
+ The tag is redundant and does not need to be specified when multiple base types
967
+ are listed.
968
+
969
+ .. _module_local:
970
+
971
+ Module-local class bindings
972
+ ===========================
973
+
974
+ When creating a binding for a class, pybind11 by default makes that binding
975
+ "global" across modules. What this means is that instances whose type is
976
+ defined with a ``py::class_`` statement in one module can be passed to or
977
+ returned from a function defined in any other module that is "ABI compatible"
978
+ with the first, i.e., that was built with sufficiently similar versions of
979
+ pybind11 and of the C++ compiler and C++ standard library. The internal data
980
+ structures that pybind11 uses to keep track of its types and instances are
981
+ shared just as they would be if everything were in the same module.
982
+ For example, this allows the following:
983
+
984
+ .. code-block:: cpp
985
+
986
+ // In the module1.cpp binding code for module1:
987
+ py::class_<Pet>(m, "Pet")
988
+ .def(py::init<std::string>())
989
+ .def_readonly("name", &Pet::name);
990
+
991
+ .. code-block:: cpp
992
+
993
+ // In the module2.cpp binding code for module2:
994
+ m.def("create_pet", [](std::string name) { return new Pet(name); });
995
+
996
+ .. code-block:: pycon
997
+
998
+ >>> from module1 import Pet
999
+ >>> from module2 import create_pet
1000
+ >>> pet1 = Pet("Kitty")
1001
+ >>> pet2 = create_pet("Doggy")
1002
+ >>> pet2.name()
1003
+ 'Doggy'
1004
+
1005
+ When writing binding code for a library, this is usually desirable: this
1006
+ allows, for example, splitting up a complex library into multiple Python
1007
+ modules.
1008
+
1009
+ In some cases, however, this can cause conflicts. For example, suppose two
1010
+ unrelated modules make use of an external C++ library and each provide custom
1011
+ bindings for one of that library's classes. This will result in an error when
1012
+ a Python program attempts to import both modules (directly or indirectly)
1013
+ because of conflicting definitions on the external type:
1014
+
1015
+ .. code-block:: cpp
1016
+
1017
+ // dogs.cpp
1018
+
1019
+ // Binding for external library class:
1020
+ py::class_<pets::Pet>(m, "Pet")
1021
+ .def("name", &pets::Pet::name);
1022
+
1023
+ // Binding for local extension class:
1024
+ py::class_<Dog, pets::Pet>(m, "Dog")
1025
+ .def(py::init<std::string>());
1026
+
1027
+ .. code-block:: cpp
1028
+
1029
+ // cats.cpp, in a completely separate project from the above dogs.cpp.
1030
+
1031
+ // Binding for external library class:
1032
+ py::class_<pets::Pet>(m, "Pet")
1033
+ .def("get_name", &pets::Pet::name);
1034
+
1035
+ // Binding for local extending class:
1036
+ py::class_<Cat, pets::Pet>(m, "Cat")
1037
+ .def(py::init<std::string>());
1038
+
1039
+ .. code-block:: pycon
1040
+
1041
+ >>> import cats
1042
+ >>> import dogs
1043
+ Traceback (most recent call last):
1044
+ File "<stdin>", line 1, in <module>
1045
+ ImportError: generic_type: type "Pet" is already registered!
1046
+
1047
+ To get around this, you can tell pybind11 to keep the external class binding
1048
+ localized to the module by passing the ``py::module_local()`` attribute into
1049
+ the ``py::class_`` constructor:
1050
+
1051
+ .. code-block:: cpp
1052
+
1053
+ // Pet binding in dogs.cpp:
1054
+ py::class_<pets::Pet>(m, "Pet", py::module_local())
1055
+ .def("name", &pets::Pet::name);
1056
+
1057
+ .. code-block:: cpp
1058
+
1059
+ // Pet binding in cats.cpp:
1060
+ py::class_<pets::Pet>(m, "Pet", py::module_local())
1061
+ .def("get_name", &pets::Pet::name);
1062
+
1063
+ This makes the Python-side ``dogs.Pet`` and ``cats.Pet`` into distinct classes,
1064
+ avoiding the conflict and allowing both modules to be loaded. C++ code in the
1065
+ ``dogs`` module that casts or returns a ``Pet`` instance will result in a
1066
+ ``dogs.Pet`` Python instance, while C++ code in the ``cats`` module will result
1067
+ in a ``cats.Pet`` Python instance.
1068
+
1069
+ This does come with two caveats, however: First, external modules cannot return
1070
+ or cast a ``Pet`` instance to Python (unless they also provide their own local
1071
+ bindings). Second, from the Python point of view they are two distinct classes.
1072
+
1073
+ Note that the locality only applies in the C++ -> Python direction. When
1074
+ passing such a ``py::module_local`` type into a C++ function, the module-local
1075
+ classes are still considered. This means that if the following function is
1076
+ added to any module (including but not limited to the ``cats`` and ``dogs``
1077
+ modules above) it will be callable with either a ``dogs.Pet`` or ``cats.Pet``
1078
+ argument:
1079
+
1080
+ .. code-block:: cpp
1081
+
1082
+ m.def("pet_name", [](const pets::Pet &pet) { return pet.name(); });
1083
+
1084
+ For example, suppose the above function is added to each of ``cats.cpp``,
1085
+ ``dogs.cpp`` and ``frogs.cpp`` (where ``frogs.cpp`` is some other module that
1086
+ does *not* bind ``Pets`` at all).
1087
+
1088
+ .. code-block:: pycon
1089
+
1090
+ >>> import cats, dogs, frogs # No error because of the added py::module_local()
1091
+ >>> mycat, mydog = cats.Cat("Fluffy"), dogs.Dog("Rover")
1092
+ >>> (cats.pet_name(mycat), dogs.pet_name(mydog))
1093
+ ('Fluffy', 'Rover')
1094
+ >>> (cats.pet_name(mydog), dogs.pet_name(mycat), frogs.pet_name(mycat))
1095
+ ('Rover', 'Fluffy', 'Fluffy')
1096
+
1097
+ It is possible to use ``py::module_local()`` registrations in one module even
1098
+ if another module registers the same type globally: within the module with the
1099
+ module-local definition, all C++ instances will be cast to the associated bound
1100
+ Python type. In other modules any such values are converted to the global
1101
+ Python type created elsewhere.
1102
+
1103
+ .. note::
1104
+
1105
+ STL bindings (as provided via the optional :file:`pybind11/stl_bind.h`
1106
+ header) apply ``py::module_local`` by default when the bound type might
1107
+ conflict with other modules; see :ref:`stl_bind` for details.
1108
+
1109
+ .. note::
1110
+
1111
+ The localization of the bound types is actually tied to the shared object
1112
+ or binary generated by the compiler/linker. For typical modules created
1113
+ with ``PYBIND11_MODULE()``, this distinction is not significant. It is
1114
+ possible, however, when :ref:`embedding` to embed multiple modules in the
1115
+ same binary (see :ref:`embedding_modules`). In such a case, the
1116
+ localization will apply across all embedded modules within the same binary.
1117
+
1118
+ .. seealso::
1119
+
1120
+ The file :file:`tests/test_local_bindings.cpp` contains additional examples
1121
+ that demonstrate how ``py::module_local()`` works.
1122
+
1123
+ Binding protected member functions
1124
+ ==================================
1125
+
1126
+ It's normally not possible to expose ``protected`` member functions to Python:
1127
+
1128
+ .. code-block:: cpp
1129
+
1130
+ class A {
1131
+ protected:
1132
+ int foo() const { return 42; }
1133
+ };
1134
+
1135
+ py::class_<A>(m, "A")
1136
+ .def("foo", &A::foo); // error: 'foo' is a protected member of 'A'
1137
+
1138
+ On one hand, this is good because non-``public`` members aren't meant to be
1139
+ accessed from the outside. But we may want to make use of ``protected``
1140
+ functions in derived Python classes.
1141
+
1142
+ The following pattern makes this possible:
1143
+
1144
+ .. code-block:: cpp
1145
+
1146
+ class A {
1147
+ protected:
1148
+ int foo() const { return 42; }
1149
+ };
1150
+
1151
+ class Publicist : public A { // helper type for exposing protected functions
1152
+ public:
1153
+ using A::foo; // inherited with different access modifier
1154
+ };
1155
+
1156
+ py::class_<A>(m, "A") // bind the primary class
1157
+ .def("foo", &Publicist::foo); // expose protected methods via the publicist
1158
+
1159
+ This works because ``&Publicist::foo`` is exactly the same function as
1160
+ ``&A::foo`` (same signature and address), just with a different access
1161
+ modifier. The only purpose of the ``Publicist`` helper class is to make
1162
+ the function name ``public``.
1163
+
1164
+ If the intent is to expose ``protected`` ``virtual`` functions which can be
1165
+ overridden in Python, the publicist pattern can be combined with the previously
1166
+ described trampoline:
1167
+
1168
+ .. code-block:: cpp
1169
+
1170
+ class A {
1171
+ public:
1172
+ virtual ~A() = default;
1173
+
1174
+ protected:
1175
+ virtual int foo() const { return 42; }
1176
+ };
1177
+
1178
+ class Trampoline : public A, public py::trampoline_self_life_support {
1179
+ public:
1180
+ int foo() const override { PYBIND11_OVERRIDE(int, A, foo, ); }
1181
+ };
1182
+
1183
+ class Publicist : public A {
1184
+ public:
1185
+ using A::foo;
1186
+ };
1187
+
1188
+ py::class_<A, Trampoline, py::smart_holder>(m, "A") // <-- `Trampoline` here
1189
+ .def("foo", &Publicist::foo); // <-- `Publicist` here, not `Trampoline`!
1190
+
1191
+ Binding final classes
1192
+ =====================
1193
+
1194
+ Some classes may not be appropriate to inherit from. In C++11, classes can
1195
+ use the ``final`` specifier to ensure that a class cannot be inherited from.
1196
+ The ``py::is_final`` attribute can be used to ensure that Python classes
1197
+ cannot inherit from a specified type. The underlying C++ type does not need
1198
+ to be declared final.
1199
+
1200
+ .. code-block:: cpp
1201
+
1202
+ class IsFinal final {};
1203
+
1204
+ py::class_<IsFinal>(m, "IsFinal", py::is_final());
1205
+
1206
+ When you try to inherit from such a class in Python, you will now get this
1207
+ error:
1208
+
1209
+ .. code-block:: pycon
1210
+
1211
+ >>> class PyFinalChild(IsFinal):
1212
+ ... pass
1213
+ ...
1214
+ TypeError: type 'IsFinal' is not an acceptable base type
1215
+
1216
+ .. note:: This attribute is currently ignored on PyPy
1217
+
1218
+ .. versionadded:: 2.6
1219
+
1220
+ Binding classes with template parameters
1221
+ ========================================
1222
+
1223
+ pybind11 can also wrap classes that have template parameters. Consider these classes:
1224
+
1225
+ .. code-block:: cpp
1226
+
1227
+ struct Cat {};
1228
+ struct Dog {};
1229
+
1230
+ template <typename PetType>
1231
+ struct Cage {
1232
+ Cage(PetType& pet);
1233
+ PetType& get();
1234
+ };
1235
+
1236
+ C++ templates may only be instantiated at compile time, so pybind11 can only
1237
+ wrap instantiated templated classes. You cannot wrap a non-instantiated template:
1238
+
1239
+ .. code-block:: cpp
1240
+
1241
+ // BROKEN (this will not compile)
1242
+ py::class_<Cage>(m, "Cage");
1243
+ .def("get", &Cage::get);
1244
+
1245
+ You must explicitly specify each template/type combination that you want to
1246
+ wrap separately.
1247
+
1248
+ .. code-block:: cpp
1249
+
1250
+ // ok
1251
+ py::class_<Cage<Cat>>(m, "CatCage")
1252
+ .def("get", &Cage<Cat>::get);
1253
+
1254
+ // ok
1255
+ py::class_<Cage<Dog>>(m, "DogCage")
1256
+ .def("get", &Cage<Dog>::get);
1257
+
1258
+ If your class methods have template parameters you can wrap those as well,
1259
+ but once again each instantiation must be explicitly specified:
1260
+
1261
+ .. code-block:: cpp
1262
+
1263
+ typename <typename T>
1264
+ struct MyClass {
1265
+ template <typename V>
1266
+ T fn(V v);
1267
+ };
1268
+
1269
+ py::class_<MyClass<int>>(m, "MyClassT")
1270
+ .def("fn", &MyClass<int>::fn<std::string>);
1271
+
1272
+ Custom automatic downcasters
1273
+ ============================
1274
+
1275
+ As explained in :ref:`inheritance`, pybind11 comes with built-in
1276
+ understanding of the dynamic type of polymorphic objects in C++; that
1277
+ is, returning a Pet to Python produces a Python object that knows it's
1278
+ wrapping a Dog, if Pet has virtual methods and pybind11 knows about
1279
+ Dog and this Pet is in fact a Dog. Sometimes, you might want to
1280
+ provide this automatic downcasting behavior when creating bindings for
1281
+ a class hierarchy that does not use standard C++ polymorphism, such as
1282
+ LLVM [#f4]_. As long as there's some way to determine at runtime
1283
+ whether a downcast is safe, you can proceed by specializing the
1284
+ ``pybind11::polymorphic_type_hook`` template:
1285
+
1286
+ .. code-block:: cpp
1287
+
1288
+ enum class PetKind { Cat, Dog, Zebra };
1289
+ struct Pet { // Not polymorphic: has no virtual methods
1290
+ const PetKind kind;
1291
+ int age = 0;
1292
+ protected:
1293
+ Pet(PetKind _kind) : kind(_kind) {}
1294
+ };
1295
+ struct Dog : Pet {
1296
+ Dog() : Pet(PetKind::Dog) {}
1297
+ std::string sound = "woof!";
1298
+ std::string bark() const { return sound; }
1299
+ };
1300
+
1301
+ namespace PYBIND11_NAMESPACE {
1302
+ template<> struct polymorphic_type_hook<Pet> {
1303
+ static const void *get(const Pet *src, const std::type_info*& type) {
1304
+ // note that src may be nullptr
1305
+ if (src && src->kind == PetKind::Dog) {
1306
+ type = &typeid(Dog);
1307
+ return static_cast<const Dog*>(src);
1308
+ }
1309
+ return src;
1310
+ }
1311
+ };
1312
+ } // namespace PYBIND11_NAMESPACE
1313
+
1314
+ When pybind11 wants to convert a C++ pointer of type ``Base*`` to a
1315
+ Python object, it calls ``polymorphic_type_hook<Base>::get()`` to
1316
+ determine if a downcast is possible. The ``get()`` function should use
1317
+ whatever runtime information is available to determine if its ``src``
1318
+ parameter is in fact an instance of some class ``Derived`` that
1319
+ inherits from ``Base``. If it finds such a ``Derived``, it sets ``type
1320
+ = &typeid(Derived)`` and returns a pointer to the ``Derived`` object
1321
+ that contains ``src``. Otherwise, it just returns ``src``, leaving
1322
+ ``type`` at its default value of nullptr. If you set ``type`` to a
1323
+ type that pybind11 doesn't know about, no downcasting will occur, and
1324
+ the original ``src`` pointer will be used with its static type
1325
+ ``Base*``.
1326
+
1327
+ It is critical that the returned pointer and ``type`` argument of
1328
+ ``get()`` agree with each other: if ``type`` is set to something
1329
+ non-null, the returned pointer must point to the start of an object
1330
+ whose type is ``type``. If the hierarchy being exposed uses only
1331
+ single inheritance, a simple ``return src;`` will achieve this just
1332
+ fine, but in the general case, you must cast ``src`` to the
1333
+ appropriate derived-class pointer (e.g. using
1334
+ ``static_cast<Derived>(src)``) before allowing it to be returned as a
1335
+ ``void*``.
1336
+
1337
+ .. [#f4] https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html
1338
+
1339
+ .. note::
1340
+
1341
+ pybind11's standard support for downcasting objects whose types
1342
+ have virtual methods is implemented using
1343
+ ``polymorphic_type_hook`` too, using the standard C++ ability to
1344
+ determine the most-derived type of a polymorphic object using
1345
+ ``typeid()`` and to cast a base pointer to that most-derived type
1346
+ (even if you don't know what it is) using ``dynamic_cast<void*>``.
1347
+
1348
+ .. seealso::
1349
+
1350
+ The file :file:`tests/test_tagbased_polymorphic.cpp` contains a
1351
+ more complete example, including a demonstration of how to provide
1352
+ automatic downcasting for an entire class hierarchy without
1353
+ writing one get() function for each class.
1354
+
1355
+ Accessing the type object
1356
+ =========================
1357
+
1358
+ You can get the type object from a C++ class that has already been registered using:
1359
+
1360
+ .. code-block:: cpp
1361
+
1362
+ py::type T_py = py::type::of<T>();
1363
+
1364
+ You can directly use ``py::type::of(ob)`` to get the type object from any python
1365
+ object, just like ``type(ob)`` in Python.
1366
+
1367
+ .. note::
1368
+
1369
+ Other types, like ``py::type::of<int>()``, do not work, see :ref:`type-conversions`.
1370
+
1371
+ .. versionadded:: 2.6
1372
+
1373
+ Custom type setup
1374
+ =================
1375
+
1376
+ For advanced use cases, such as enabling garbage collection support, you may
1377
+ wish to directly manipulate the ``PyHeapTypeObject`` corresponding to a
1378
+ ``py::class_`` definition.
1379
+
1380
+ You can do that using ``py::custom_type_setup``:
1381
+
1382
+ .. code-block:: cpp
1383
+
1384
+ struct OwnsPythonObjects {
1385
+ py::object value = py::none();
1386
+ };
1387
+ py::class_<OwnsPythonObjects> cls(
1388
+ m, "OwnsPythonObjects", py::custom_type_setup([](PyHeapTypeObject *heap_type) {
1389
+ auto *type = &heap_type->ht_type;
1390
+ type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1391
+ type->tp_traverse = [](PyObject *self_base, visitproc visit, void *arg) {
1392
+ // https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
1393
+ #if PY_VERSION_HEX >= 0x03090000
1394
+ Py_VISIT(Py_TYPE(self_base));
1395
+ #endif
1396
+ if (py::detail::is_holder_constructed(self_base)) {
1397
+ auto &self = py::cast<OwnsPythonObjects&>(py::handle(self_base));
1398
+ Py_VISIT(self.value.ptr());
1399
+ }
1400
+ return 0;
1401
+ };
1402
+ type->tp_clear = [](PyObject *self_base) {
1403
+ if (py::detail::is_holder_constructed(self_base)) {
1404
+ auto &self = py::cast<OwnsPythonObjects&>(py::handle(self_base));
1405
+ self.value = py::none();
1406
+ }
1407
+ return 0;
1408
+ };
1409
+ }));
1410
+ cls.def(py::init<>());
1411
+ cls.def_readwrite("value", &OwnsPythonObjects::value);
1412
+
1413
+ .. versionadded:: 2.8
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/deadlock.md ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Double locking, deadlocking, GIL
2
+
3
+ [TOC]
4
+
5
+ ## Introduction
6
+
7
+ ### Overview
8
+
9
+ In concurrent programming with locks, *deadlocks* can arise when more than one
10
+ mutex is locked at the same time, and careful attention has to be paid to lock
11
+ ordering to avoid this. Here we will look at a common situation that occurs in
12
+ native extensions for CPython written in C++.
13
+
14
+ ### Deadlocks
15
+
16
+ A deadlock can occur when more than one thread attempts to lock more than one
17
+ mutex, and two of the threads lock two of the mutexes in different orders. For
18
+ example, consider mutexes `mu1` and `mu2`, and threads T1 and T2, executing:
19
+
20
+ | | T1 | T2 |
21
+ |--- | ------------------- | -------------------|
22
+ |1 | `mu1.lock()`{.good} | `mu2.lock()`{.good}|
23
+ |2 | `mu2.lock()`{.bad} | `mu1.lock()`{.bad} |
24
+ |3 | `/* work */` | `/* work */` |
25
+ |4 | `mu2.unlock()` | `mu1.unlock()` |
26
+ |5 | `mu1.unlock()` | `mu2.unlock()` |
27
+
28
+ Now if T1 manages to lock `mu1` and T2 manages to lock `mu2` (as indicated in
29
+ green), then both threads will block while trying to lock the respective other
30
+ mutex (as indicated in red), but they are also unable to release the mutex that
31
+ they have locked (step 5).
32
+
33
+ **The problem** is that it is possible for one thread to attempt to lock `mu1`
34
+ and then `mu2`, and for another thread to attempt to lock `mu2` and then `mu1`.
35
+ Note that it does not matter if either mutex is unlocked at any intermediate
36
+ point; what matters is only the order of any attempt to *lock* the mutexes. For
37
+ example, the following, more complex series of operations is just as prone to
38
+ deadlock:
39
+
40
+ | | T1 | T2 |
41
+ |--- | ------------------- | -------------------|
42
+ |1 | `mu1.lock()`{.good} | `mu1.lock()`{.good}|
43
+ |2 | waiting for T2 | `mu2.lock()`{.good}|
44
+ |3 | waiting for T2 | `/* work */` |
45
+ |3 | waiting for T2 | `mu1.unlock()` |
46
+ |3 | `mu2.lock()`{.bad} | `/* work */` |
47
+ |3 | `/* work */` | `mu1.lock()`{.bad} |
48
+ |3 | `/* work */` | `/* work */` |
49
+ |4 | `mu2.unlock()` | `mu1.unlock()` |
50
+ |5 | `mu1.unlock()` | `mu2.unlock()` |
51
+
52
+ When the mutexes involved in a locking sequence are known at compile-time, then
53
+ avoiding deadlocks is &ldquo;merely&rdquo; a matter of arranging the lock
54
+ operations carefully so as to only occur in one single, fixed order. However, it
55
+ is also possible for mutexes to only be determined at runtime. A typical example
56
+ of this is a database where each row has its own mutex. An operation that
57
+ modifies two rows in a single transaction (e.g. &ldquo;transferring an amount
58
+ from one account to another&rdquo;) must lock two row mutexes, but the locking
59
+ order cannot be established at compile time. In this case, a dynamic
60
+ &ldquo;deadlock avoidance algorithm&rdquo; is needed. (In C++, `std::lock`
61
+ provides such an algorithm. An algorithm might use a non-blocking `try_lock`
62
+ operation on a mutex, which can either succeed or fail to lock the mutex, but
63
+ returns without blocking.)
64
+
65
+ Conceptually, one could also consider it a deadlock if _the same_ thread
66
+ attempts to lock a mutex that it has already locked (e.g. when some locked
67
+ operation accidentally recurses into itself): `mu.lock();`{.good}
68
+ `mu.lock();`{.bad} However, this is a slightly separate issue: Typical mutexes
69
+ are either of _recursive_ or _non-recursive_ kind. A recursive mutex allows
70
+ repeated locking and requires balanced unlocking. A non-recursive mutex can be
71
+ implemented more efficiently, and/but for efficiency reasons does not actually
72
+ guarantee a deadlock on second lock. Instead, the API simply forbids such use,
73
+ making it a precondition that the thread not already hold the mutex, with
74
+ undefined behaviour on violation.
75
+
76
+ ### &ldquo;Once&rdquo; initialization
77
+
78
+ A common programming problem is to have an operation happen precisely once, even
79
+ if requested concurrently. While it is clear that we need to track in some
80
+ shared state somewhere whether the operation has already happened, it is worth
81
+ noting that this state only ever transitions, once, from `false` to `true`. This
82
+ is considerably simpler than a general shared state that can change values
83
+ arbitrarily. Next, we also need a mechanism for all but one thread to block
84
+ until the initialization has completed, which we can provide with a mutex. The
85
+ simplest solution just always locks the mutex:
86
+
87
+ ```c++
88
+ // The "once" mechanism:
89
+ constinit absl::Mutex mu(absl::kConstInit);
90
+ constinit bool init_done = false;
91
+
92
+ // The operation of interest:
93
+ void f();
94
+
95
+ void InitOnceNaive() {
96
+ absl::MutexLock lock(&mu);
97
+ if (!init_done) {
98
+ f();
99
+ init_done = true;
100
+ }
101
+ }
102
+ ```
103
+
104
+ This works, but the efficiency-minded reader will observe that once the
105
+ operation has completed, all future lock contention on the mutex is
106
+ unnecessary. This leads to the (in)famous &ldquo;double-locking&rdquo;
107
+ algorithm, which was historically hard to write correctly. The idea is to check
108
+ the boolean *before* locking the mutex, and avoid locking if the operation has
109
+ already completed. However, accessing shared state concurrently when at least
110
+ one access is a write is prone to causing a data race and needs to be done
111
+ according to an appropriate concurrent programming model. In C++ we use atomic
112
+ variables:
113
+
114
+ ```c++
115
+ // The "once" mechanism:
116
+ constinit absl::Mutex mu(absl::kConstInit);
117
+ constinit std::atomic<bool> init_done = false;
118
+
119
+ // The operation of interest:
120
+ void f();
121
+
122
+ void InitOnceWithFastPath() {
123
+ if (!init_done.load(std::memory_order_acquire)) {
124
+ absl::MutexLock lock(&mu);
125
+ if (!init_done.load(std::memory_order_relaxed)) {
126
+ f();
127
+ init_done.store(true, std::memory_order_release);
128
+ }
129
+ }
130
+ }
131
+ ```
132
+
133
+ Checking the flag now happens without holding the mutex lock, and if the
134
+ operation has already completed, we return immediately. After locking the mutex,
135
+ we need to check the flag again, since multiple threads can reach this point.
136
+
137
+ *Atomic details.* Since the atomic flag variable is accessed concurrently, we
138
+ have to think about the memory order of the accesses. There are two separate
139
+ cases: The first, outer check outside the mutex lock, and the second, inner
140
+ check under the lock. The outer check and the flag update form an
141
+ acquire/release pair: *if* the load sees the value `true` (which must have been
142
+ written by the store operation), then it also sees everything that happened
143
+ before the store, namely the operation `f()`. By contrast, the inner check can
144
+ use relaxed memory ordering, since in that case the mutex operations provide the
145
+ necessary ordering: if the inner load sees the value `true`, it happened after
146
+ the `lock()`, which happened after the `unlock()`, which happened after the
147
+ store.
148
+
149
+ The C++ standard library, and Abseil, provide a ready-made solution of this
150
+ algorithm called `std::call_once`/`absl::call_once`. (The interface is the same,
151
+ but the Abseil implementation is possibly better.)
152
+
153
+ ```c++
154
+ // The "once" mechanism:
155
+ constinit absl::once_flag init_flag;
156
+
157
+ // The operation of interest:
158
+ void f();
159
+
160
+ void InitOnceWithCallOnce() {
161
+ absl::call_once(once_flag, f);
162
+ }
163
+ ```
164
+
165
+ Even though conceptually this is performing the same algorithm, this
166
+ implementation has some considerable advantages: The `once_flag` type is a small
167
+ and trivial, integer-like type and is trivially destructible. Not only does it
168
+ take up less space than a mutex, it also generates less code since it does not
169
+ have to run a destructor, which would need to be added to the program's global
170
+ destructor list.
171
+
172
+ The final clou comes with the C++ semantics of a `static` variable declared at
173
+ block scope: According to [[stmt.dcl]](https://eel.is/c++draft/stmt.dcl#3):
174
+
175
+ > Dynamic initialization of a block variable with static storage duration or
176
+ > thread storage duration is performed the first time control passes through its
177
+ > declaration; such a variable is considered initialized upon the completion of
178
+ > its initialization. [...] If control enters the declaration concurrently while
179
+ > the variable is being initialized, the concurrent execution shall wait for
180
+ > completion of the initialization.
181
+
182
+ This is saying that the initialization of a local, `static` variable precisely
183
+ has the &ldquo;once&rdquo; semantics that we have been discussing. We can
184
+ therefore write the above example as follows:
185
+
186
+ ```c++
187
+ // The operation of interest:
188
+ void f();
189
+
190
+ void InitOnceWithStatic() {
191
+ static int unused = (f(), 0);
192
+ }
193
+ ```
194
+
195
+ This approach is by far the simplest and easiest, but the big difference is that
196
+ the mutex (or mutex-like object) in this implementation is no longer visible or
197
+ in the user&rsquo;s control. This is perfectly fine if the initializer is
198
+ simple, but if the initializer itself attempts to lock any other mutex
199
+ (including by initializing another static variable!), then we have no control
200
+ over the lock ordering!
201
+
202
+ Finally, you may have noticed the `constinit`s around the earlier code. Both
203
+ `constinit` and `constexpr` specifiers on a declaration mean that the variable
204
+ is *constant-initialized*, which means that no initialization is performed at
205
+ runtime (the initial value is already known at compile time). This in turn means
206
+ that a static variable guard mutex may not be needed, and static initialization
207
+ never blocks. The difference between the two is that a `constexpr`-specified
208
+ variable is also `const`, and a variable cannot be `constexpr` if it has a
209
+ non-trivial destructor. Such a destructor also means that the guard mutex is
210
+ needed after all, since the destructor must be registered to run at exit,
211
+ conditionally on initialization having happened.
212
+
213
+ ## Python, CPython, GIL
214
+
215
+ With CPython, a Python program can call into native code. To this end, the
216
+ native code registers callback functions with the Python runtime via the CPython
217
+ API. In order to ensure that the internal state of the Python runtime remains
218
+ consistent, there is a single, shared mutex called the &ldquo;global interpreter
219
+ lock&rdquo;, or GIL for short. Upon entry of one of the user-provided callback
220
+ functions, the GIL is locked (or &ldquo;held&rdquo;), so that no other mutations
221
+ of the Python runtime state can occur until the native callback returns.
222
+
223
+ Many native extensions do not interact with the Python runtime for at least some
224
+ part of them, and so it is common for native extensions to _release_ the GIL, do
225
+ some work, and then reacquire the GIL before returning. Similarly, when code is
226
+ generally not holding the GIL but needs to interact with the runtime briefly, it
227
+ will first reacquire the GIL. The GIL is reentrant, and constructions to acquire
228
+ and subsequently release the GIL are common, and often don't worry about whether
229
+ the GIL is already held.
230
+
231
+ If the native code is written in C++ and contains local, `static` variables,
232
+ then we are now dealing with at least _two_ mutexes: the static variable guard
233
+ mutex, and the GIL from CPython.
234
+
235
+ A common problem in such code is an operation with &ldquo;only once&rdquo;
236
+ semantics that also ends up requiring the GIL to be held at some point. As per
237
+ the above description of &ldquo;once&rdquo;-style techniques, one might find a
238
+ static variable:
239
+
240
+ ```c++
241
+ // CPython callback, assumes that the GIL is held on entry.
242
+ PyObject* InvokeWidget(PyObject* self) {
243
+ static PyObject* impl = CreateWidget();
244
+ return PyObject_CallOneArg(impl, self);
245
+ }
246
+ ```
247
+
248
+ This seems reasonable, but bear in mind that there are two mutexes (the "guard
249
+ mutex" and "the GIL"), and we must think about the lock order. Otherwise, if the
250
+ callback is called from multiple threads, a deadlock may ensue.
251
+
252
+ Let us consider what we can see here: On entry, the GIL is already locked, and
253
+ we are locking the guard mutex. This is one lock order. Inside the initializer
254
+ `CreateWidget`, with both mutexes already locked, the function can freely access
255
+ the Python runtime.
256
+
257
+ However, it is entirely possible that `CreateWidget` will want to release the
258
+ GIL at one point and reacquire it later:
259
+
260
+ ```c++
261
+ // Assumes that the GIL is held on entry.
262
+ // Ensures that the GIL is held on exit.
263
+ PyObject* CreateWidget() {
264
+ // ...
265
+ Py_BEGIN_ALLOW_THREADS // releases GIL
266
+ // expensive work, not accessing the Python runtime
267
+ Py_END_ALLOW_THREADS // acquires GIL, #!
268
+ // ...
269
+ return result;
270
+ }
271
+ ```
272
+
273
+ Now we have a second lock order: the guard mutex is locked, and then the GIL is
274
+ locked (at `#!`). To see how this deadlocks, consider threads T1 and T2 both
275
+ having the runtime attempt to call `InvokeWidget`. T1 locks the GIL and
276
+ proceeds, locking the guard mutex and calling `CreateWidget`; T2 is blocked
277
+ waiting for the GIL. Then T1 releases the GIL to do &ldquo;expensive
278
+ work&rdquo;, and T2 awakes and locks the GIL. Now T2 is blocked trying to
279
+ acquire the guard mutex, but T1 is blocked reacquiring the GIL (at `#!`).
280
+
281
+ In other words: if we want to support &ldquo;once-called&rdquo; functions that
282
+ can arbitrarily release and reacquire the GIL, as is very common, then the only
283
+ lock order that we can ensure is: guard mutex first, GIL second.
284
+
285
+ To implement this, we must rewrite our code. Naively, we could always release
286
+ the GIL before a `static` variable with blocking initializer:
287
+
288
+ ```c++
289
+ // CPython callback, assumes that the GIL is held on entry.
290
+ PyObject* InvokeWidget(PyObject* self) {
291
+ Py_BEGIN_ALLOW_THREADS // releases GIL
292
+ static PyObject* impl = CreateWidget();
293
+ Py_END_ALLOW_THREADS // acquires GIL
294
+
295
+ return PyObject_CallOneArg(impl, self);
296
+ }
297
+ ```
298
+
299
+ But similar to the `InitOnceNaive` example above, this code cycles the GIL
300
+ (possibly descheduling the thread) even when the static variable has already
301
+ been initialized. If we want to avoid this, we need to abandon the use of a
302
+ static variable, since we do not control the guard mutex well enough. Instead,
303
+ we use an operation whose mutex locking is under our control, such as
304
+ `call_once`. For example:
305
+
306
+ ```c++
307
+ // CPython callback, assumes that the GIL is held on entry.
308
+ PyObject* InvokeWidget(PyObject* self) {
309
+ static constinit PyObject* impl = nullptr;
310
+ static constinit std::atomic<bool> init_done = false;
311
+ static constinit absl::once_flag init_flag;
312
+
313
+ if (!init_done.load(std::memory_order_acquire)) {
314
+ Py_BEGIN_ALLOW_THREADS // releases GIL
315
+ absl::call_once(init_flag, [&]() {
316
+ PyGILState_STATE s = PyGILState_Ensure(); // acquires GIL
317
+ impl = CreateWidget();
318
+ PyGILState_Release(s); // releases GIL
319
+ init_done.store(true, std::memory_order_release);
320
+ });
321
+ Py_END_ALLOW_THREADS // acquires GIL
322
+ }
323
+
324
+ return PyObject_CallOneArg(impl, self);
325
+ }
326
+ ```
327
+
328
+ The lock order is now always guard mutex first, GIL second. Unfortunately we
329
+ have to duplicate the &ldquo;double-checked done flag&rdquo;, effectively
330
+ leading to triple checking, because the flag state inside the `absl::once_flag`
331
+ is not accessible to the user. In other words, we cannot ask `init_flag` whether
332
+ it has been used yet.
333
+
334
+ However, we can perform one last, minor optimisation: since we assume that the
335
+ GIL is held on entry, and again when the initializing operation returns, the GIL
336
+ actually serializes access to our done flag variable, which therefore does not
337
+ need to be atomic. (The difference to the previous, atomic code may be small,
338
+ depending on the architecture. For example, on x86-64, acquire/release on a bool
339
+ is nearly free ([demo](https://godbolt.org/z/P9vYWf4fE)).)
340
+
341
+ ```c++
342
+ // CPython callback, assumes that the GIL is held on entry, and indeed anywhere
343
+ // directly in this function (i.e. the GIL can be released inside CreateWidget,
344
+ // but must be reaqcuired when that call returns).
345
+ PyObject* InvokeWidget(PyObject* self) {
346
+ static constinit PyObject* impl = nullptr;
347
+ static constinit bool init_done = false; // guarded by GIL
348
+ static constinit absl::once_flag init_flag;
349
+
350
+ if (!init_done) {
351
+ Py_BEGIN_ALLOW_THREADS // releases GIL
352
+ // (multiple threads may enter here)
353
+ absl::call_once(init_flag, [&]() {
354
+ // (only one thread enters here)
355
+ PyGILState_STATE s = PyGILState_Ensure(); // acquires GIL
356
+ impl = CreateWidget();
357
+ init_done = true; // (GIL is held)
358
+ PyGILState_Release(s); // releases GIL
359
+ });
360
+
361
+ Py_END_ALLOW_THREADS // acquires GIL
362
+ }
363
+
364
+ return PyObject_CallOneArg(impl, self);
365
+ }
366
+ ```
367
+
368
+ ## Debugging tips
369
+
370
+ * Build with symbols.
371
+ * <kbd>Ctrl</kbd>-<kbd>C</kbd> sends `SIGINT`, <kbd>Ctrl</kbd>-<kbd>\\</kbd>
372
+ sends `SIGQUIT`. Both have their uses.
373
+ * Useful `gdb` commands:
374
+ * `py-bt` prints a Python backtrace if you are in a Python frame.
375
+ * `thread apply all bt 10` prints the top-10 frames for each thread. A
376
+ full backtrace can be prohibitively expensive, and the top few frames
377
+ are often good enough.
378
+ * `p PyGILState_Check()` shows whether a thread is holding the GIL. For
379
+ all threads, run `thread apply all p PyGILState_Check()` to find out
380
+ which thread is holding the GIL.
381
+ * The `static` variable guard mutex is accessed with functions like
382
+ `cxa_guard_acquire` (though this depends on ABI details and can vary).
383
+ The guard mutex itself contains information about which thread is
384
+ currently holding it.
385
+
386
+ ## Links
387
+
388
+ * Article on
389
+ [double-checked locking](https://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/)
390
+ * [The Deadlock Empire](https://deadlockempire.github.io/), hands-on exercises
391
+ to construct deadlocks
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/deprecated.rst ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _deprecated:
2
+
3
+ Deprecated
4
+ ##########
5
+
6
+ Support for Python 3.8 is deprecated and will be removed in 3.1.
7
+
8
+ Support for C++11 is deprecated and will be removed in a future version. Please
9
+ use at least C++14.
10
+
11
+ Support for FindPythonLibs (not available in CMake 3.26+ mode) is deprecated
12
+ and will be removed in a future version. The default mode is also going to
13
+ change to ``"new"`` from ``"compat"`` in the future.
14
+
15
+ The following features were deprecated before pybind11 3.0, and may be removed
16
+ in minor releases of pybind11 3.x.
17
+
18
+ .. list-table:: Deprecated Features
19
+ :header-rows: 1
20
+ :widths: 30 15 10
21
+
22
+ * - Feature
23
+ - Deprecated Version
24
+ - Year
25
+ * - ``py::metaclass()``
26
+ - 2.1
27
+ - 2017
28
+ * - ``PYBIND11_PLUGIN``
29
+ - 2.2
30
+ - 2017
31
+ * - ``py::set_error()`` replacing ``operator()``
32
+ - 2.12
33
+ - 2024
34
+ * - ``get_type_overload``
35
+ - 2.6
36
+ - 2020
37
+ * - ``call()``
38
+ - 2.0
39
+ - 2016
40
+ * - ``.str()``
41
+ - ?
42
+ -
43
+ * - ``.get_type()``
44
+ - 2.6
45
+ -
46
+ * - ``==`` and ``!=``
47
+ - 2.2
48
+ - 2017
49
+ * - ``.check()``
50
+ - ?
51
+ -
52
+ * - ``object(handle, bool)``
53
+ - ?
54
+ -
55
+ * - ``error_already_set.clear()``
56
+ - 2.2
57
+ - 2017
58
+ * - ``obj.attr(…)`` as ``bool``
59
+ - ?
60
+ -
61
+ * - ``.contains``
62
+ - ? (maybe 2.4)
63
+ -
64
+ * - ``py::capsule`` two-argument with destructor
65
+ - ?
66
+ -
67
+
68
+
69
+
70
+ .. _deprecated_enum:
71
+
72
+ ``py::enum_``
73
+ =============
74
+
75
+ This is the original documentation for ``py::enum_``, which is deprecated
76
+ because it is not `PEP 435 compatible <https://peps.python.org/pep-0435/>`_
77
+ (see also `#2332 <https://github.com/pybind/pybind11/issues/2332>`_).
78
+ Please prefer ``py::native_enum`` (added with pybind11v3) when writing
79
+ new bindings. See :ref:`native_enum` for more information.
80
+
81
+ Let's suppose that we have an example class that contains internal types
82
+ like enumerations, e.g.:
83
+
84
+ .. code-block:: cpp
85
+
86
+ struct Pet {
87
+ enum Kind {
88
+ Dog = 0,
89
+ Cat
90
+ };
91
+
92
+ struct Attributes {
93
+ float age = 0;
94
+ };
95
+
96
+ Pet(const std::string &name, Kind type) : name(name), type(type) { }
97
+
98
+ std::string name;
99
+ Kind type;
100
+ Attributes attr;
101
+ };
102
+
103
+ The binding code for this example looks as follows:
104
+
105
+ .. code-block:: cpp
106
+
107
+ py::class_<Pet> pet(m, "Pet");
108
+
109
+ pet.def(py::init<const std::string &, Pet::Kind>())
110
+ .def_readwrite("name", &Pet::name)
111
+ .def_readwrite("type", &Pet::type)
112
+ .def_readwrite("attr", &Pet::attr);
113
+
114
+ py::enum_<Pet::Kind>(pet, "Kind")
115
+ .value("Dog", Pet::Kind::Dog)
116
+ .value("Cat", Pet::Kind::Cat)
117
+ .export_values();
118
+
119
+ py::class_<Pet::Attributes>(pet, "Attributes")
120
+ .def(py::init<>())
121
+ .def_readwrite("age", &Pet::Attributes::age);
122
+
123
+
124
+ To ensure that the nested types ``Kind`` and ``Attributes`` are created within the scope of ``Pet``, the
125
+ ``pet`` ``py::class_`` instance must be supplied to the :class:`enum_` and ``py::class_``
126
+ constructor. The :func:`enum_::export_values` function exports the enum entries
127
+ into the parent scope, which should be skipped for newer C++11-style strongly
128
+ typed enums.
129
+
130
+ .. code-block:: pycon
131
+
132
+ >>> p = Pet("Lucy", Pet.Cat)
133
+ >>> p.type
134
+ Kind.Cat
135
+ >>> int(p.type)
136
+ 1L
137
+
138
+ The entries defined by the enumeration type are exposed in the ``__members__`` property:
139
+
140
+ .. code-block:: pycon
141
+
142
+ >>> Pet.Kind.__members__
143
+ {'Dog': Kind.Dog, 'Cat': Kind.Cat}
144
+
145
+ The ``name`` property returns the name of the enum value as a unicode string.
146
+
147
+ .. note::
148
+
149
+ It is also possible to use ``str(enum)``, however these accomplish different
150
+ goals. The following shows how these two approaches differ.
151
+
152
+ .. code-block:: pycon
153
+
154
+ >>> p = Pet("Lucy", Pet.Cat)
155
+ >>> pet_type = p.type
156
+ >>> pet_type
157
+ Pet.Cat
158
+ >>> str(pet_type)
159
+ 'Pet.Cat'
160
+ >>> pet_type.name
161
+ 'Cat'
162
+
163
+ .. note::
164
+
165
+ When the special tag ``py::arithmetic()`` is specified to the ``enum_``
166
+ constructor, pybind11 creates an enumeration that also supports rudimentary
167
+ arithmetic and bit-level operations like comparisons, and, or, xor, negation,
168
+ etc.
169
+
170
+ .. code-block:: cpp
171
+
172
+ py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
173
+ ...
174
+
175
+ By default, these are omitted to conserve space.
176
+
177
+ .. warning::
178
+
179
+ Contrary to Python customs, enum values from the wrappers should not be compared using ``is``, but with ``==`` (see `#1177 <https://github.com/pybind/pybind11/issues/1177>`_ for background).
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/embedding.rst ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _embedding:
2
+
3
+ Embedding the interpreter
4
+ #########################
5
+
6
+ While pybind11 is mainly focused on extending Python using C++, it's also
7
+ possible to do the reverse: embed the Python interpreter into a C++ program.
8
+ All of the other documentation pages still apply here, so refer to them for
9
+ general pybind11 usage. This section will cover a few extra things required
10
+ for embedding.
11
+
12
+ Getting started
13
+ ===============
14
+
15
+ A basic executable with an embedded interpreter can be created with just a few
16
+ lines of CMake and the ``pybind11::embed`` target, as shown below. For more
17
+ information, see :doc:`/compiling`.
18
+
19
+ .. code-block:: cmake
20
+
21
+ cmake_minimum_required(VERSION 3.15...4.0)
22
+ project(example)
23
+
24
+ find_package(pybind11 REQUIRED) # or `add_subdirectory(pybind11)`
25
+
26
+ add_executable(example main.cpp)
27
+ target_link_libraries(example PRIVATE pybind11::embed)
28
+
29
+ The essential structure of the ``main.cpp`` file looks like this:
30
+
31
+ .. code-block:: cpp
32
+
33
+ #include <pybind11/embed.h> // everything needed for embedding
34
+ namespace py = pybind11;
35
+
36
+ int main() {
37
+ py::scoped_interpreter guard{}; // start the interpreter and keep it alive
38
+
39
+ py::print("Hello, World!"); // use the Python API
40
+ }
41
+
42
+ The interpreter must be initialized before using any Python API, which includes
43
+ all the functions and classes in pybind11. The RAII guard class ``scoped_interpreter``
44
+ takes care of the interpreter lifetime. After the guard is destroyed, the interpreter
45
+ shuts down and clears its memory. No Python functions can be called after this.
46
+
47
+ Executing Python code
48
+ =====================
49
+
50
+ There are a few different ways to run Python code. One option is to use ``eval``,
51
+ ``exec`` or ``eval_file``, as explained in :ref:`eval`. Here is a quick example in
52
+ the context of an executable with an embedded interpreter:
53
+
54
+ .. code-block:: cpp
55
+
56
+ #include <pybind11/embed.h>
57
+ namespace py = pybind11;
58
+
59
+ int main() {
60
+ py::scoped_interpreter guard{};
61
+
62
+ py::exec(R"(
63
+ kwargs = dict(name="World", number=42)
64
+ message = "Hello, {name}! The answer is {number}".format(**kwargs)
65
+ print(message)
66
+ )");
67
+ }
68
+
69
+ Alternatively, similar results can be achieved using pybind11's API (see
70
+ :doc:`/advanced/pycpp/index` for more details).
71
+
72
+ .. code-block:: cpp
73
+
74
+ #include <pybind11/embed.h>
75
+ namespace py = pybind11;
76
+ using namespace py::literals;
77
+
78
+ int main() {
79
+ py::scoped_interpreter guard{};
80
+
81
+ auto kwargs = py::dict("name"_a="World", "number"_a=42);
82
+ auto message = "Hello, {name}! The answer is {number}"_s.format(**kwargs);
83
+ py::print(message);
84
+ }
85
+
86
+ The two approaches can also be combined:
87
+
88
+ .. code-block:: cpp
89
+
90
+ #include <pybind11/embed.h>
91
+ #include <iostream>
92
+
93
+ namespace py = pybind11;
94
+ using namespace py::literals;
95
+
96
+ int main() {
97
+ py::scoped_interpreter guard{};
98
+
99
+ auto locals = py::dict("name"_a="World", "number"_a=42);
100
+ py::exec(R"(
101
+ message = "Hello, {name}! The answer is {number}".format(**locals())
102
+ )", py::globals(), locals);
103
+
104
+ auto message = locals["message"].cast<std::string>();
105
+ std::cout << message;
106
+ }
107
+
108
+ Importing modules
109
+ =================
110
+
111
+ Python modules can be imported using ``module_::import()``:
112
+
113
+ .. code-block:: cpp
114
+
115
+ py::module_ sys = py::module_::import("sys");
116
+ py::print(sys.attr("path"));
117
+
118
+ For convenience, the current working directory is included in ``sys.path`` when
119
+ embedding the interpreter. This makes it easy to import local Python files:
120
+
121
+ .. code-block:: python
122
+
123
+ """calc.py located in the working directory"""
124
+
125
+
126
+ def add(i, j):
127
+ return i + j
128
+
129
+
130
+ .. code-block:: cpp
131
+
132
+ py::module_ calc = py::module_::import("calc");
133
+ py::object result = calc.attr("add")(1, 2);
134
+ int n = result.cast<int>();
135
+ assert(n == 3);
136
+
137
+ Modules can be reloaded using ``module_::reload()`` if the source is modified e.g.
138
+ by an external process. This can be useful in scenarios where the application
139
+ imports a user defined data processing script which needs to be updated after
140
+ changes by the user. Note that this function does not reload modules recursively.
141
+
142
+ .. _embedding_modules:
143
+
144
+ Adding embedded modules
145
+ =======================
146
+
147
+ Embedded binary modules can be added using the ``PYBIND11_EMBEDDED_MODULE`` macro.
148
+ Note that the definition must be placed at global scope. They can be imported
149
+ like any other module.
150
+
151
+ .. code-block:: cpp
152
+
153
+ #include <pybind11/embed.h>
154
+ namespace py = pybind11;
155
+
156
+ PYBIND11_EMBEDDED_MODULE(fast_calc, m) {
157
+ // `m` is a `py::module_` which is used to bind functions and classes
158
+ m.def("add", [](int i, int j) {
159
+ return i + j;
160
+ });
161
+ }
162
+
163
+ int main() {
164
+ py::scoped_interpreter guard{};
165
+
166
+ auto fast_calc = py::module_::import("fast_calc");
167
+ auto result = fast_calc.attr("add")(1, 2).cast<int>();
168
+ assert(result == 3);
169
+ }
170
+
171
+ Unlike extension modules where only a single binary module can be created, on
172
+ the embedded side an unlimited number of modules can be added using multiple
173
+ ``PYBIND11_EMBEDDED_MODULE`` definitions (as long as they have unique names).
174
+
175
+ These modules are added to Python's list of builtins, so they can also be
176
+ imported in pure Python files loaded by the interpreter. Everything interacts
177
+ naturally:
178
+
179
+ .. code-block:: python
180
+
181
+ """py_module.py located in the working directory"""
182
+ import cpp_module
183
+
184
+ a = cpp_module.a
185
+ b = a + 1
186
+
187
+
188
+ .. code-block:: cpp
189
+
190
+ #include <pybind11/embed.h>
191
+ namespace py = pybind11;
192
+
193
+ PYBIND11_EMBEDDED_MODULE(cpp_module, m) {
194
+ m.attr("a") = 1;
195
+ }
196
+
197
+ int main() {
198
+ py::scoped_interpreter guard{};
199
+
200
+ auto py_module = py::module_::import("py_module");
201
+
202
+ auto locals = py::dict("fmt"_a="{} + {} = {}", **py_module.attr("__dict__"));
203
+ assert(locals["a"].cast<int>() == 1);
204
+ assert(locals["b"].cast<int>() == 2);
205
+
206
+ py::exec(R"(
207
+ c = a + b
208
+ message = fmt.format(a, b, c)
209
+ )", py::globals(), locals);
210
+
211
+ assert(locals["c"].cast<int>() == 3);
212
+ assert(locals["message"].cast<std::string>() == "1 + 2 = 3");
213
+ }
214
+
215
+ ``PYBIND11_EMBEDDED_MODULE`` also accepts
216
+ :func:`py::mod_gil_not_used()`,
217
+ :func:`py::multiple_interpreters::per_interpreter_gil()`, and
218
+ :func:`py::multiple_interpreters::shared_gil()` tags just like ``PYBIND11_MODULE``.
219
+ See :ref:`misc_subinterp` and :ref:`misc_free_threading` for more information.
220
+
221
+ Interpreter lifetime
222
+ ====================
223
+
224
+ The Python interpreter shuts down when ``scoped_interpreter`` is destroyed. After
225
+ this, creating a new instance will restart the interpreter. Alternatively, the
226
+ ``initialize_interpreter`` / ``finalize_interpreter`` pair of functions can be used
227
+ to directly set the state at any time.
228
+
229
+ Modules created with pybind11 can be safely re-initialized after the interpreter
230
+ has been restarted. However, this may not apply to third-party extension modules.
231
+ The issue is that Python itself cannot completely unload extension modules and
232
+ there are several caveats with regard to interpreter restarting. In short, not
233
+ all memory may be freed, either due to Python reference cycles or user-created
234
+ global data. All the details can be found in the CPython documentation.
235
+
236
+ .. warning::
237
+
238
+ Creating two concurrent ``scoped_interpreter`` guards is a fatal error. So is
239
+ calling ``initialize_interpreter`` for a second time after the interpreter
240
+ has already been initialized. Use :class:`scoped_subinterpreter` to create
241
+ a sub-interpreter. See :ref:`subinterp` for important details on sub-interpreters.
242
+
243
+ Do not use the raw CPython API functions ``Py_Initialize`` and
244
+ ``Py_Finalize`` as these do not properly handle the lifetime of
245
+ pybind11's internal data.
246
+
247
+
248
+ .. _subinterp:
249
+
250
+ Embedding Sub-interpreters
251
+ ==========================
252
+
253
+ A sub-interpreter is a separate interpreter instance which provides a
254
+ separate, isolated interpreter environment within the same process as the main
255
+ interpreter. Sub-interpreters are created and managed with a separate API from
256
+ the main interpreter. Beginning in Python 3.12, sub-interpreters each have
257
+ their own Global Interpreter Lock (GIL), which means that running a
258
+ sub-interpreter in a separate thread from the main interpreter can achieve true
259
+ concurrency.
260
+
261
+ pybind11's sub-interpreter API can be found in ``pybind11/subinterpreter.h``.
262
+
263
+ pybind11 :class:`subinterpreter` instances can be safely moved and shared between
264
+ threads as needed. However, managing multiple threads and the lifetimes of multiple
265
+ interpreters and their GILs can be challenging.
266
+ Proceed with caution (and lots of testing)!
267
+
268
+ The main interpreter must be initialized before creating a sub-interpreter, and
269
+ the main interpreter must outlive all sub-interpreters. Sub-interpreters are
270
+ managed through a different API than the main interpreter.
271
+
272
+ The :class:`subinterpreter` class manages the lifetime of sub-interpreters.
273
+ Instances are movable, but not copyable. Default constructing this class does
274
+ *not* create a sub-interpreter (it creates an empty holder). To create a
275
+ sub-interpreter, call :func:`subinterpreter::create()`.
276
+
277
+ .. warning::
278
+
279
+ Sub-interpreter creation acquires (and subsequently releases) the main
280
+ interpreter GIL. If another thread holds the main GIL, the function will
281
+ block until the main GIL can be acquired.
282
+
283
+ Sub-interpreter destruction temporarily activates the sub-interpreter. The
284
+ sub-interpreter must not be active (on any threads) at the time the
285
+ :class:`subinterpreter` destructor is called.
286
+
287
+ Both actions will re-acquire any interpreter's GIL that was held prior to
288
+ the call before returning (or return to no active interpreter if none was
289
+ active at the time of the call).
290
+
291
+ Each sub-interpreter will import a separate copy of each ``PYBIND11_EMBEDDED_MODULE``
292
+ when those modules specify a ``multiple_interpreters`` tag. If a module does not
293
+ specify a ``multiple_interpreters`` tag, then Python will report an ``ImportError``
294
+ if it is imported in a sub-interpreter.
295
+
296
+ pybind11 also has a :class:`scoped_subinterpreter` class, which creates and
297
+ activates a sub-interpreter when it is constructed, and deactivates and deletes
298
+ it when it goes out of scope.
299
+
300
+ Activating a Sub-interpreter
301
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
302
+
303
+ Once a sub-interpreter is created, you can "activate" it on a thread (and
304
+ acquire its GIL) by creating a :class:`subinterpreter_scoped_activate`
305
+ instance and passing it the sub-intepreter to be activated. The function
306
+ will acquire the sub-interpreter's GIL and make the sub-interpreter the
307
+ current active interpreter on the current thread for the lifetime of the
308
+ instance. When the :class:`subinterpreter_scoped_activate` instance goes out
309
+ of scope, the sub-interpreter GIL is released and the prior interpreter that
310
+ was active on the thread (if any) is reactivated and it's GIL is re-acquired.
311
+
312
+ When using ``subinterpreter_scoped_activate``:
313
+
314
+ 1. If the thread holds any interpreter's GIL:
315
+ - That GIL is released
316
+ 2. The new sub-interpreter's GIL is acquired
317
+ 3. The new sub-interpreter is made active.
318
+ 4. When the scope ends:
319
+ - The sub-interpreter's GIL is released
320
+ - If there was a previous interpreter:
321
+ - The old interpreter's GIL is re-acquired
322
+ - The old interpreter is made active
323
+ - Otherwise, no interpreter is currently active and no GIL is held.
324
+
325
+ Example:
326
+
327
+ .. code-block:: cpp
328
+
329
+ py::initialize_interpreter();
330
+ // Main GIL is held
331
+ {
332
+ py::subinterpreter sub = py::subinterpreter::create();
333
+ // Main interpreter is still active, main GIL re-acquired
334
+ {
335
+ py::subinterpreter_scoped_activate guard(sub);
336
+ // Sub-interpreter active, thread holds sub's GIL
337
+ {
338
+ py::subinterpreter_scoped_activate main_guard(py);
339
+ // Sub's GIL was automatically released
340
+ // Main interpreter active, thread holds main's GIL
341
+ }
342
+ // Back to sub-interpreter, thread holds sub's GIL again
343
+ }
344
+ // Main interpreter is active, main's GIL is held
345
+ }
346
+
347
+
348
+ GIL API for sub-interpreters
349
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
350
+
351
+ :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be used to
352
+ manage the GIL of a sub-interpreter just as they do for the main interpreter.
353
+ They both manage the GIL of the currently active interpreter, without the
354
+ programmer having to do anything special or different. There is one important
355
+ caveat:
356
+
357
+ .. note::
358
+
359
+ When no interpreter is active through a
360
+ :class:`subinterpreter_scoped_activate` instance (such as on a new thread),
361
+ :class:`gil_scoped_acquire` will acquire the **main** GIL and
362
+ activate the **main** interpreter.
363
+
364
+
365
+ Full Sub-interpreter example
366
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
367
+
368
+ Here is an example showing how to create and activate sub-interpreters:
369
+
370
+ .. code-block:: cpp
371
+
372
+ #include <iostream>
373
+ #include <pybind11/embed.h>
374
+ #include <pybind11/subinterpreter.h>
375
+
376
+ namespace py = pybind11;
377
+
378
+ PYBIND11_EMBEDDED_MODULE(printer, m, py::multiple_interpreters::per_interpreter_gil()) {
379
+ m.def("which", [](const std::string& when) {
380
+ std::cout << when << "; Current Interpreter is "
381
+ << py::subinterpreter::current().id()
382
+ << std::endl;
383
+ });
384
+ }
385
+
386
+ int main() {
387
+ py::scoped_interpreter main_interp;
388
+
389
+ py::module_::import("printer").attr("which")("First init");
390
+
391
+ {
392
+ py::subinterpreter sub = py::subinterpreter::create();
393
+
394
+ py::module_::import("printer").attr("which")("Created sub");
395
+
396
+ {
397
+ py::subinterpreter_scoped_activate guard(sub);
398
+ try {
399
+ py::module_::import("printer").attr("which")("Activated sub");
400
+ }
401
+ catch (py::error_already_set &e) {
402
+ std::cerr << "EXCEPTION " << e.what() << std::endl;
403
+ return 1;
404
+ }
405
+ }
406
+
407
+ py::module_::import("printer").attr("which")("Deactivated sub");
408
+
409
+ {
410
+ py::gil_scoped_release nogil;
411
+ {
412
+ py::subinterpreter_scoped_activate guard(sub);
413
+ try {
414
+ {
415
+ py::subinterpreter_scoped_activate main_guard(py::subinterpreter::main());
416
+ try {
417
+ py::module_::import("printer").attr("which")("Main within sub");
418
+ }
419
+ catch (py::error_already_set &e) {
420
+ std::cerr << "EXCEPTION " << e.what() << std::endl;
421
+ return 1;
422
+ }
423
+ }
424
+ py::module_::import("printer").attr("which")("After Main, still within sub");
425
+ }
426
+ catch (py::error_already_set &e) {
427
+ std::cerr << "EXCEPTION " << e.what() << std::endl;
428
+ return 1;
429
+ }
430
+ }
431
+ }
432
+ }
433
+
434
+ py::module_::import("printer").attr("which")("At end");
435
+
436
+ return 0;
437
+ }
438
+
439
+ Expected output:
440
+
441
+ .. code-block:: text
442
+
443
+ First init; Current Interpreter is 0
444
+ Created sub; Current Interpreter is 0
445
+ Activated sub; Current Interpreter is 1
446
+ Deactivated sub; Current Interpreter is 0
447
+ Main within sub; Current Interpreter is 0
448
+ After Main, still within sub; Current Interpreter is 1
449
+ At end; Current Interpreter is 0
450
+
451
+ .. warning::
452
+
453
+ In Python 3.12 sub-interpreters must be destroyed in the same OS thread
454
+ that created them. Failure to follow this rule may result in deadlocks
455
+ or crashes when destroying the sub-interpreter on the wrong thread.
456
+
457
+ This constraint is not present in Python 3.13+.
458
+
459
+
460
+ Best Practices for sub-interpreter safety
461
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
462
+
463
+ - Never share Python objects across different interpreters.
464
+
465
+ - :class:`error_already_set` objects contain a reference to the Python exception type,
466
+ and :func:`error_already_set::what()` acquires the GIL. So Python exceptions must
467
+ **never** be allowed to propagate past the enclosing
468
+ :class:`subinterpreter_scoped_activate` instance!
469
+ (So your try/catch should be *just inside* the scope covered by the
470
+ :class:`subinterpreter_scoped_activate`.)
471
+
472
+ - Avoid global/static state whenever possible. Instead, keep state within each interpreter,
473
+ such as within the interpreter state dict, which can be accessed via
474
+ ``subinterpreter::current().state_dict()``, or within instance members and tied to
475
+ Python objects.
476
+
477
+ - Avoid trying to "cache" Python objects in C++ variables across function calls (this is an easy
478
+ way to accidentally introduce sub-interpreter bugs). In the code example above, note that we
479
+ did not save the result of :func:`module_::import`, in order to avoid accidentally using the
480
+ resulting Python object when the wrong interpreter was active.
481
+
482
+ - Avoid moving or disarming RAII objects managing GIL and sub-interpreter lifetimes. Doing so can
483
+ lead to confusion about lifetimes. (For example, accidentally extending a
484
+ :class:`subinterpreter_scoped_activate` past the lifetime of it's :class:`subinterpreter`.)
485
+
486
+ - While sub-interpreters each have their own GIL, there can now be multiple independent GILs in one
487
+ program so you need to consider the possibility of deadlocks caused by multiple GILs and/or the
488
+ interactions of the GIL(s) and your C++ code's own locking.
489
+
490
+ - When using multiple threads to run independent sub-interpreters, the independent GILs allow
491
+ concurrent calls from different interpreters into the same C++ code from different threads.
492
+ So you must still consider the thread safety of your C++ code. Remember, in Python 3.12
493
+ sub-interpreters must be destroyed on the same thread that they were created on.
494
+
495
+ - Familiarize yourself with :ref:`misc_concurrency`.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/exceptions.rst ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Exceptions
2
+ ##########
3
+
4
+ Built-in C++ to Python exception translation
5
+ ============================================
6
+
7
+ When Python calls C++ code through pybind11, pybind11 provides a C++ exception handler
8
+ that will trap C++ exceptions, translate them to the corresponding Python exception,
9
+ and raise them so that Python code can handle them.
10
+
11
+ pybind11 defines translations for ``std::exception`` and its standard
12
+ subclasses, and several special exception classes that translate to specific
13
+ Python exceptions. Note that these are not actually Python exceptions, so they
14
+ cannot be examined using the Python C API. Instead, they are pure C++ objects
15
+ that pybind11 will translate the corresponding Python exception when they arrive
16
+ at its exception handler.
17
+
18
+ .. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
19
+
20
+ +--------------------------------------+--------------------------------------+
21
+ | Exception thrown by C++ | Translated to Python exception type |
22
+ +======================================+======================================+
23
+ | :class:`std::exception` | ``RuntimeError`` |
24
+ +--------------------------------------+--------------------------------------+
25
+ | :class:`std::bad_alloc` | ``MemoryError`` |
26
+ +--------------------------------------+--------------------------------------+
27
+ | :class:`std::domain_error` | ``ValueError`` |
28
+ +--------------------------------------+--------------------------------------+
29
+ | :class:`std::invalid_argument` | ``ValueError`` |
30
+ +--------------------------------------+--------------------------------------+
31
+ | :class:`std::length_error` | ``ValueError`` |
32
+ +--------------------------------------+--------------------------------------+
33
+ | :class:`std::out_of_range` | ``IndexError`` |
34
+ +--------------------------------------+--------------------------------------+
35
+ | :class:`std::range_error` | ``ValueError`` |
36
+ +--------------------------------------+--------------------------------------+
37
+ | :class:`std::overflow_error` | ``OverflowError`` |
38
+ +--------------------------------------+--------------------------------------+
39
+ | :class:`pybind11::stop_iteration` | ``StopIteration`` (used to implement |
40
+ | | custom iterators) |
41
+ +--------------------------------------+--------------------------------------+
42
+ | :class:`pybind11::index_error` | ``IndexError`` (used to indicate out |
43
+ | | of bounds access in ``__getitem__``, |
44
+ | | ``__setitem__``, etc.) |
45
+ +--------------------------------------+--------------------------------------+
46
+ | :class:`pybind11::key_error` | ``KeyError`` (used to indicate out |
47
+ | | of bounds access in ``__getitem__``, |
48
+ | | ``__setitem__`` in dict-like |
49
+ | | objects, etc.) |
50
+ +--------------------------------------+--------------------------------------+
51
+ | :class:`pybind11::value_error` | ``ValueError`` (used to indicate |
52
+ | | wrong value passed in |
53
+ | | ``container.remove(...)``) |
54
+ +--------------------------------------+--------------------------------------+
55
+ | :class:`pybind11::type_error` | ``TypeError`` |
56
+ +--------------------------------------+--------------------------------------+
57
+ | :class:`pybind11::buffer_error` | ``BufferError`` |
58
+ +--------------------------------------+--------------------------------------+
59
+ | :class:`pybind11::import_error` | ``ImportError`` |
60
+ +--------------------------------------+--------------------------------------+
61
+ | :class:`pybind11::attribute_error` | ``AttributeError`` |
62
+ +--------------------------------------+--------------------------------------+
63
+ | Any other exception | ``RuntimeError`` |
64
+ +--------------------------------------+--------------------------------------+
65
+
66
+ Exception translation is not bidirectional. That is, *catching* the C++
67
+ exceptions defined above will not trap exceptions that originate from
68
+ Python. For that, catch :class:`pybind11::error_already_set`. See :ref:`below
69
+ <handling_python_exceptions_cpp>` for further details.
70
+
71
+ There is also a special exception :class:`cast_error` that is thrown by
72
+ :func:`handle::call` when the input arguments cannot be converted to Python
73
+ objects.
74
+
75
+ Registering custom translators
76
+ ==============================
77
+
78
+ If the default exception conversion policy described above is insufficient,
79
+ pybind11 also provides support for registering custom exception translators.
80
+ Similar to pybind11 classes, exception translators can be local to the module
81
+ they are defined in or global to the entire python session. To register a simple
82
+ exception conversion that translates a C++ exception into a new Python exception
83
+ using the C++ exception's ``what()`` method, a helper function is available:
84
+
85
+ .. code-block:: cpp
86
+
87
+ py::register_exception<CppExp>(module, "PyExp");
88
+
89
+ This call creates a Python exception class with the name ``PyExp`` in the given
90
+ module and automatically converts any encountered exceptions of type ``CppExp``
91
+ into Python exceptions of type ``PyExp``.
92
+
93
+ A matching function is available for registering a local exception translator:
94
+
95
+ .. code-block:: cpp
96
+
97
+ py::register_local_exception<CppExp>(module, "PyExp");
98
+
99
+
100
+ It is possible to specify base class for the exception using the third
101
+ parameter, a ``handle``:
102
+
103
+ .. code-block:: cpp
104
+
105
+ py::register_exception<CppExp>(module, "PyExp", PyExc_RuntimeError);
106
+ py::register_local_exception<CppExp>(module, "PyExp", PyExc_RuntimeError);
107
+
108
+ Then ``PyExp`` can be caught both as ``PyExp`` and ``RuntimeError``.
109
+
110
+ The class objects of the built-in Python exceptions are listed in the Python
111
+ documentation on `Standard Exceptions <https://docs.python.org/3/c-api/exceptions.html#standard-exceptions>`_.
112
+ The default base class is ``PyExc_Exception``.
113
+
114
+ When more advanced exception translation is needed, the functions
115
+ ``py::register_exception_translator(translator)`` and
116
+ ``py::register_local_exception_translator(translator)`` can be used to register
117
+ functions that can translate arbitrary exception types (and which may include
118
+ additional logic to do so). The functions takes a stateless callable (e.g. a
119
+ function pointer or a lambda function without captured variables) with the call
120
+ signature ``void(std::exception_ptr)``.
121
+
122
+ When a C++ exception is thrown, the registered exception translators are tried
123
+ in reverse order of registration (i.e. the last registered translator gets the
124
+ first shot at handling the exception). All local translators will be tried
125
+ before a global translator is tried.
126
+
127
+ Inside the translator, ``std::rethrow_exception`` should be used within
128
+ a try block to re-throw the exception. One or more catch clauses to catch
129
+ the appropriate exceptions should then be used with each clause using
130
+ ``py::set_error()`` (see below).
131
+
132
+ To declare a custom Python exception type, declare a ``py::exception`` variable
133
+ and use this in the associated exception translator (note: it is often useful
134
+ to make this a static declaration when using it inside a lambda expression
135
+ without requiring capturing).
136
+
137
+ The following example demonstrates this for a hypothetical exception classes
138
+ ``MyCustomException`` and ``OtherException``: the first is translated to a
139
+ custom python exception ``MyCustomError``, while the second is translated to a
140
+ standard python RuntimeError:
141
+
142
+ .. code-block:: cpp
143
+
144
+ PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> exc_storage;
145
+ exc_storage.call_once_and_store_result(
146
+ [&]() { return py::exception<MyCustomException>(m, "MyCustomError"); });
147
+ py::register_exception_translator([](std::exception_ptr p) {
148
+ try {
149
+ if (p) std::rethrow_exception(p);
150
+ } catch (const MyCustomException &e) {
151
+ py::set_error(exc_storage.get_stored(), e.what());
152
+ } catch (const OtherException &e) {
153
+ py::set_error(PyExc_RuntimeError, e.what());
154
+ }
155
+ });
156
+
157
+ Multiple exceptions can be handled by a single translator, as shown in the
158
+ example above. If the exception is not caught by the current translator, the
159
+ previously registered one gets a chance.
160
+
161
+ If none of the registered exception translators is able to handle the
162
+ exception, it is handled by the default converter as described in the previous
163
+ section.
164
+
165
+ .. seealso::
166
+
167
+ The file :file:`tests/test_exceptions.cpp` contains examples
168
+ of various custom exception translators and custom exception types.
169
+
170
+ .. note::
171
+
172
+ Call ``py::set_error()`` for every exception caught in a custom exception
173
+ translator. Failure to do so will cause Python to crash with ``SystemError:
174
+ error return without exception set``.
175
+
176
+ Exceptions that you do not plan to handle should simply not be caught, or
177
+ may be explicitly (re-)thrown to delegate it to the other,
178
+ previously-declared existing exception translators.
179
+
180
+ Note that ``libc++`` and ``libstdc++`` `behave differently under macOS
181
+ <https://stackoverflow.com/questions/19496643/using-clang-fvisibility-hidden-and-typeinfo-and-type-erasure/28827430>`_
182
+ with ``-fvisibility=hidden``. Therefore exceptions that are used across ABI
183
+ boundaries need to be explicitly exported, as exercised in
184
+ ``tests/test_exceptions.h``. See also:
185
+ "Problems with C++ exceptions" under `GCC Wiki <https://gcc.gnu.org/wiki/Visibility>`_.
186
+
187
+
188
+ Local vs Global Exception Translators
189
+ =====================================
190
+
191
+ When a global exception translator is registered, it will be applied across all
192
+ modules in the reverse order of registration. This can create behavior where the
193
+ order of module import influences how exceptions are translated.
194
+
195
+ If module1 has the following translator:
196
+
197
+ .. code-block:: cpp
198
+
199
+ py::register_exception_translator([](std::exception_ptr p) {
200
+ try {
201
+ if (p) std::rethrow_exception(p);
202
+ } catch (const std::invalid_argument &e) {
203
+ py::set_error(PyExc_ArgumentError, "module1 handled this");
204
+ }
205
+ }
206
+
207
+ and module2 has the following similar translator:
208
+
209
+ .. code-block:: cpp
210
+
211
+ py::register_exception_translator([](std::exception_ptr p) {
212
+ try {
213
+ if (p) std::rethrow_exception(p);
214
+ } catch (const std::invalid_argument &e) {
215
+ py::set_error(PyExc_ArgumentError, "module2 handled this");
216
+ }
217
+ }
218
+
219
+ then which translator handles the invalid_argument will be determined by the
220
+ order that module1 and module2 are imported. Since exception translators are
221
+ applied in the reverse order of registration, which ever module was imported
222
+ last will "win" and that translator will be applied.
223
+
224
+ If there are multiple pybind11 modules that share exception types (either
225
+ standard built-in or custom) loaded into a single python instance and
226
+ consistent error handling behavior is needed, then local translators should be
227
+ used.
228
+
229
+ Changing the previous example to use ``register_local_exception_translator``
230
+ would mean that when invalid_argument is thrown in the module2 code, the
231
+ module2 translator will always handle it, while in module1, the module1
232
+ translator will do the same.
233
+
234
+ .. _handling_python_exceptions_cpp:
235
+
236
+ Handling exceptions from Python in C++
237
+ ======================================
238
+
239
+ When C++ calls Python functions, such as in a callback function or when
240
+ manipulating Python objects, and Python raises an ``Exception``, pybind11
241
+ converts the Python exception into a C++ exception of type
242
+ :class:`pybind11::error_already_set` whose payload contains a C++ string textual
243
+ summary and the actual Python exception. ``error_already_set`` is used to
244
+ propagate Python exception back to Python (or possibly, handle them in C++).
245
+
246
+ .. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
247
+
248
+ +--------------------------------------+--------------------------------------+
249
+ | Exception raised in Python | Thrown as C++ exception type |
250
+ +======================================+======================================+
251
+ | Any Python ``Exception`` | :class:`pybind11::error_already_set` |
252
+ +--------------------------------------+--------------------------------------+
253
+
254
+ For example:
255
+
256
+ .. code-block:: cpp
257
+
258
+ try {
259
+ // open("missing.txt", "r")
260
+ auto file = py::module_::import("io").attr("open")("missing.txt", "r");
261
+ auto text = file.attr("read")();
262
+ file.attr("close")();
263
+ } catch (py::error_already_set &e) {
264
+ if (e.matches(PyExc_FileNotFoundError)) {
265
+ py::print("missing.txt not found");
266
+ } else if (e.matches(PyExc_PermissionError)) {
267
+ py::print("missing.txt found but not accessible");
268
+ } else {
269
+ throw;
270
+ }
271
+ }
272
+
273
+ Note that C++ to Python exception translation does not apply here, since that is
274
+ a method for translating C++ exceptions to Python, not vice versa. The error raised
275
+ from Python is always ``error_already_set``.
276
+
277
+ This example illustrates this behavior:
278
+
279
+ .. code-block:: cpp
280
+
281
+ try {
282
+ py::eval("raise ValueError('The Ring')");
283
+ } catch (py::value_error &boromir) {
284
+ // Boromir never gets the ring
285
+ assert(false);
286
+ } catch (py::error_already_set &frodo) {
287
+ // Frodo gets the ring
288
+ py::print("I will take the ring");
289
+ }
290
+
291
+ try {
292
+ // py::value_error is a request for pybind11 to raise a Python exception
293
+ throw py::value_error("The ball");
294
+ } catch (py::error_already_set &cat) {
295
+ // cat won't catch the ball since
296
+ // py::value_error is not a Python exception
297
+ assert(false);
298
+ } catch (py::value_error &dog) {
299
+ // dog will catch the ball
300
+ py::print("Run Spot run");
301
+ throw; // Throw it again (pybind11 will raise ValueError)
302
+ }
303
+
304
+ Handling errors from the Python C API
305
+ =====================================
306
+
307
+ Where possible, use :ref:`pybind11 wrappers <wrappers>` instead of calling
308
+ the Python C API directly. When calling the Python C API directly, in
309
+ addition to manually managing reference counts, one must follow the pybind11
310
+ error protocol, which is outlined here.
311
+
312
+ After calling the Python C API, if Python returns an error,
313
+ ``throw py::error_already_set();``, which allows pybind11 to deal with the
314
+ exception and pass it back to the Python interpreter. This includes calls to
315
+ the error setting functions such as ``py::set_error()``.
316
+
317
+ .. code-block:: cpp
318
+
319
+ py::set_error(PyExc_TypeError, "C API type error demo");
320
+ throw py::error_already_set();
321
+
322
+ // But it would be easier to simply...
323
+ throw py::type_error("pybind11 wrapper type error");
324
+
325
+ Alternately, to ignore the error, call `PyErr_Clear
326
+ <https://docs.python.org/3/c-api/exceptions.html#c.PyErr_Clear>`_.
327
+
328
+ Any Python error must be thrown or cleared, or Python/pybind11 will be left in
329
+ an invalid state.
330
+
331
+ Handling warnings from the Python C API
332
+ =======================================
333
+
334
+ Wrappers for handling Python warnings are provided in ``pybind11/warnings.h``.
335
+ This header must be included explicitly; it is not transitively included via
336
+ ``pybind11/pybind11.h``.
337
+
338
+ Warnings can be raised with the ``warn`` function:
339
+
340
+ .. code-block:: cpp
341
+
342
+ py::warnings::warn("This is a warning!", PyExc_Warning);
343
+
344
+ // Optionally, a `stack_level` can be specified.
345
+ py::warnings::warn("Another one!", PyExc_DeprecationWarning, 3);
346
+
347
+ New warning types can be registered at the module level using ``new_warning_type``:
348
+
349
+ .. code-block:: cpp
350
+
351
+ py::warnings::new_warning_type(m, "CustomWarning", PyExc_RuntimeWarning);
352
+
353
+ Chaining exceptions ('raise from')
354
+ ==================================
355
+
356
+ Python has a mechanism for indicating that exceptions were caused by other
357
+ exceptions:
358
+
359
+ .. code-block:: py
360
+
361
+ try:
362
+ print(1 / 0)
363
+ except Exception as exc:
364
+ raise RuntimeError("could not divide by zero") from exc
365
+
366
+ To do a similar thing in pybind11, you can use the ``py::raise_from`` function. It
367
+ sets the current python error indicator, so to continue propagating the exception
368
+ you should ``throw py::error_already_set()``.
369
+
370
+ .. code-block:: cpp
371
+
372
+ try {
373
+ py::eval("print(1 / 0"));
374
+ } catch (py::error_already_set &e) {
375
+ py::raise_from(e, PyExc_RuntimeError, "could not divide by zero");
376
+ throw py::error_already_set();
377
+ }
378
+
379
+ .. versionadded:: 2.8
380
+
381
+ .. _unraisable_exceptions:
382
+
383
+ Handling unraisable exceptions
384
+ ==============================
385
+
386
+ If a Python function invoked from a C++ destructor or any function marked
387
+ ``noexcept(true)`` (collectively, "noexcept functions") throws an exception, there
388
+ is no way to propagate the exception, as such functions may not throw.
389
+ Should they throw or fail to catch any exceptions in their call graph,
390
+ the C++ runtime calls ``std::terminate()`` to abort immediately.
391
+
392
+ Similarly, Python exceptions raised in a class's ``__del__`` method do not
393
+ propagate, but ``sys.unraisablehook()`` `is triggered
394
+ <https://docs.python.org/3/library/sys.html#sys.unraisablehook>`_
395
+ and an auditing event is logged.
396
+
397
+ Any noexcept function should have a try-catch block that traps
398
+ class:`error_already_set` (or any other exception that can occur). Note that
399
+ pybind11 wrappers around Python exceptions such as
400
+ :class:`pybind11::value_error` are *not* Python exceptions; they are C++
401
+ exceptions that pybind11 catches and converts to Python exceptions. Noexcept
402
+ functions cannot propagate these exceptions either. A useful approach is to
403
+ convert them to Python exceptions and then ``discard_as_unraisable`` as shown
404
+ below.
405
+
406
+ .. code-block:: cpp
407
+
408
+ void nonthrowing_func() noexcept(true) {
409
+ try {
410
+ // ...
411
+ } catch (py::error_already_set &eas) {
412
+ // Discard the Python error using Python APIs, using the C++ magic
413
+ // variable __func__. Python already knows the type and value and of the
414
+ // exception object.
415
+ eas.discard_as_unraisable(__func__);
416
+ } catch (const std::exception &e) {
417
+ // Log and discard C++ exceptions.
418
+ third_party::log(e);
419
+ }
420
+ }
421
+
422
+ .. versionadded:: 2.6
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/functions.rst ADDED
@@ -0,0 +1,616 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Functions
2
+ #########
3
+
4
+ Before proceeding with this section, make sure that you are already familiar
5
+ with the basics of binding functions and classes, as explained in :doc:`/basics`
6
+ and :doc:`/classes`. The following guide is applicable to both free and member
7
+ functions, i.e. *methods* in Python.
8
+
9
+ .. _return_value_policies:
10
+
11
+ Return value policies
12
+ =====================
13
+
14
+ Python and C++ use fundamentally different ways of managing the memory and
15
+ lifetime of objects managed by them. This can lead to issues when creating
16
+ bindings for functions that return a non-trivial type. Just by looking at the
17
+ type information, it is not clear whether Python should take charge of the
18
+ returned value and eventually free its resources, or if this is handled on the
19
+ C++ side. For this reason, pybind11 provides several *return value policy*
20
+ annotations that can be passed to the :func:`module_::def` and
21
+ :func:`class_::def` functions. The default policy is
22
+ :enum:`return_value_policy::automatic`.
23
+
24
+ Return value policies are tricky, and it's very important to get them right.
25
+ Just to illustrate what can go wrong, consider the following simple example:
26
+
27
+ .. code-block:: cpp
28
+
29
+ /* Function declaration */
30
+ Data *get_data() { return _data; /* (pointer to a static data structure) */ }
31
+ ...
32
+
33
+ /* Binding code */
34
+ m.def("get_data", &get_data); // <-- KABOOM, will cause crash when called from Python
35
+
36
+ What's going on here? When ``get_data()`` is called from Python, the return
37
+ value (a native C++ type) must be wrapped to turn it into a usable Python type.
38
+ In this case, the default return value policy (:enum:`return_value_policy::automatic`)
39
+ causes pybind11 to assume ownership of the static ``_data`` instance.
40
+
41
+ When Python's garbage collector eventually deletes the Python
42
+ wrapper, pybind11 will also attempt to delete the C++ instance (via ``operator
43
+ delete()``) due to the implied ownership. At this point, the entire application
44
+ will come crashing down, though errors could also be more subtle and involve
45
+ silent data corruption.
46
+
47
+ In the above example, the policy :enum:`return_value_policy::reference` should have
48
+ been specified so that the global data instance is only *referenced* without any
49
+ implied transfer of ownership, i.e.:
50
+
51
+ .. code-block:: cpp
52
+
53
+ m.def("get_data", &get_data, py::return_value_policy::reference);
54
+
55
+ On the other hand, this is not the right policy for many other situations,
56
+ where ignoring ownership could lead to resource leaks.
57
+ As a developer using pybind11, it's important to be familiar with the different
58
+ return value policies, including which situation calls for which one of them.
59
+ The following table provides an overview of available policies:
60
+
61
+ .. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
62
+
63
+ +--------------------------------------------------+----------------------------------------------------------------------------+
64
+ | Return value policy | Description |
65
+ +==================================================+============================================================================+
66
+ | :enum:`return_value_policy::take_ownership` | Reference an existing object (i.e. do not create a new copy) and take |
67
+ | | ownership. Python will call the destructor and delete operator when the |
68
+ | | object's reference count reaches zero. Undefined behavior ensues when the |
69
+ | | C++ side does the same, or when the data was not dynamically allocated. |
70
+ +--------------------------------------------------+----------------------------------------------------------------------------+
71
+ | :enum:`return_value_policy::copy` | Create a new copy of the returned object, which will be owned by Python. |
72
+ | | This policy is comparably safe because the lifetimes of the two instances |
73
+ | | are decoupled. |
74
+ +--------------------------------------------------+----------------------------------------------------------------------------+
75
+ | :enum:`return_value_policy::move` | Use ``std::move`` to move the return value contents into a new instance |
76
+ | | that will be owned by Python. This policy is comparably safe because the |
77
+ | | lifetimes of the two instances (move source and destination) are decoupled.|
78
+ +--------------------------------------------------+----------------------------------------------------------------------------+
79
+ | :enum:`return_value_policy::reference` | Reference an existing object, but do not take ownership. The C++ side is |
80
+ | | responsible for managing the object's lifetime and deallocating it when |
81
+ | | it is no longer used. Warning: undefined behavior will ensue when the C++ |
82
+ | | side deletes an object that is still referenced and used by Python. |
83
+ +--------------------------------------------------+----------------------------------------------------------------------------+
84
+ | :enum:`return_value_policy::reference_internal` | If the return value is an lvalue reference or a pointer, the parent object |
85
+ | | (the implicit ``this``, or ``self`` argument of the called method or |
86
+ | | property) is kept alive for at least the lifespan of the return value. |
87
+ | | **Otherwise this policy falls back to :enum:`return_value_policy::move` |
88
+ | | (see #5528).** Internally, this policy works just like |
89
+ | | :enum:`return_value_policy::reference` but additionally applies a |
90
+ | | ``keep_alive<0, 1>`` *call policy* (described in the next section) that |
91
+ | | prevents the parent object from being garbage collected as long as the |
92
+ | | return value is referenced by Python. This is the default policy for |
93
+ | | property getters created via ``def_property``, ``def_readwrite``, etc. |
94
+ +--------------------------------------------------+----------------------------------------------------------------------------+
95
+ | :enum:`return_value_policy::automatic` | This policy falls back to the policy |
96
+ | | :enum:`return_value_policy::take_ownership` when the return value is a |
97
+ | | pointer. Otherwise, it uses :enum:`return_value_policy::move` or |
98
+ | | :enum:`return_value_policy::copy` for rvalue and lvalue references, |
99
+ | | respectively. See above for a description of what all of these different |
100
+ | | policies do. This is the default policy for ``py::class_``-wrapped types. |
101
+ +--------------------------------------------------+----------------------------------------------------------------------------+
102
+ | :enum:`return_value_policy::automatic_reference` | As above, but use policy :enum:`return_value_policy::reference` when the |
103
+ | | return value is a pointer. This is the default conversion policy for |
104
+ | | function arguments when calling Python functions manually from C++ code |
105
+ | | (i.e. via ``handle::operator()``) and the casters in ``pybind11/stl.h``. |
106
+ | | You probably won't need to use this explicitly. |
107
+ +--------------------------------------------------+----------------------------------------------------------------------------+
108
+
109
+ Return value policies can also be applied to properties:
110
+
111
+ .. code-block:: cpp
112
+
113
+ class_<MyClass>(m, "MyClass")
114
+ .def_property("data", &MyClass::getData, &MyClass::setData,
115
+ py::return_value_policy::copy);
116
+
117
+ Technically, the code above applies the policy to both the getter and the
118
+ setter function, however, the setter doesn't really care about *return*
119
+ value policies which makes this a convenient terse syntax. Alternatively,
120
+ targeted arguments can be passed through the :class:`cpp_function` constructor:
121
+
122
+ .. code-block:: cpp
123
+
124
+ class_<MyClass>(m, "MyClass")
125
+ .def_property("data",
126
+ py::cpp_function(&MyClass::getData, py::return_value_policy::copy),
127
+ py::cpp_function(&MyClass::setData)
128
+ );
129
+
130
+ .. warning::
131
+
132
+ Code with invalid return value policies might access uninitialized memory or
133
+ free data structures multiple times, which can lead to hard-to-debug
134
+ non-determinism and segmentation faults, hence it is worth spending the
135
+ time to understand all the different options in the table above.
136
+
137
+ .. note::
138
+
139
+ One important aspect of the above policies is that they only apply to
140
+ instances which pybind11 has *not* seen before, in which case the policy
141
+ clarifies essential questions about the return value's lifetime and
142
+ ownership. When pybind11 knows the instance already (as identified by its
143
+ type and address in memory), it will return the existing Python object
144
+ wrapper rather than creating a new copy.
145
+
146
+ .. note::
147
+
148
+ The next section on :ref:`call_policies` discusses *call policies* that can be
149
+ specified *in addition* to a return value policy from the list above. Call
150
+ policies indicate reference relationships that can involve both return values
151
+ and parameters of functions.
152
+
153
+ .. note::
154
+
155
+ As an alternative to elaborate call policies and lifetime management logic,
156
+ consider using smart pointers (see the section on :ref:`smart_pointers` for
157
+ details). Smart pointers can tell whether an object is still referenced from
158
+ C++ or Python, which generally eliminates the kinds of inconsistencies that
159
+ can lead to crashes or undefined behavior. For functions returning smart
160
+ pointers, it is not necessary to specify a return value policy.
161
+
162
+ .. _call_policies:
163
+
164
+ Additional call policies
165
+ ========================
166
+
167
+ In addition to the above return value policies, further *call policies* can be
168
+ specified to indicate dependencies between parameters or ensure a certain state
169
+ for the function call.
170
+
171
+ Keep alive
172
+ ----------
173
+
174
+ In general, this policy is required when the C++ object is any kind of container
175
+ and another object is being added to the container. ``keep_alive<Nurse, Patient>``
176
+ indicates that the argument with index ``Patient`` should be kept alive at least
177
+ until the argument with index ``Nurse`` is freed by the garbage collector. Argument
178
+ indices start at one, while zero refers to the return value. For methods, index
179
+ ``1`` refers to the implicit ``this`` pointer, while regular arguments begin at
180
+ index ``2``. Arbitrarily many call policies can be specified. When a ``Nurse``
181
+ with value ``None`` is detected at runtime, the call policy does nothing.
182
+
183
+ When the nurse is not a pybind11-registered type, the implementation internally
184
+ relies on the ability to create a *weak reference* to the nurse object. When
185
+ the nurse object is not a pybind11-registered type and does not support weak
186
+ references, an exception will be thrown.
187
+
188
+ If you use an incorrect argument index, you will get a ``RuntimeError`` saying
189
+ ``Could not activate keep_alive!``. You should review the indices you're using.
190
+
191
+ Consider the following example: here, the binding code for a list append
192
+ operation ties the lifetime of the newly added element to the underlying
193
+ container:
194
+
195
+ .. code-block:: cpp
196
+
197
+ py::class_<List>(m, "List")
198
+ .def("append", &List::append, py::keep_alive<1, 2>());
199
+
200
+ For consistency, the argument indexing is identical for constructors. Index
201
+ ``1`` still refers to the implicit ``this`` pointer, i.e. the object which is
202
+ being constructed. Index ``0`` refers to the return type which is presumed to
203
+ be ``void`` when a constructor is viewed like a function. The following example
204
+ ties the lifetime of the constructor element to the constructed object:
205
+
206
+ .. code-block:: cpp
207
+
208
+ py::class_<Nurse>(m, "Nurse")
209
+ .def(py::init<Patient &>(), py::keep_alive<1, 2>());
210
+
211
+ .. note::
212
+
213
+ ``keep_alive`` is analogous to the ``with_custodian_and_ward`` (if Nurse,
214
+ Patient != 0) and ``with_custodian_and_ward_postcall`` (if Nurse/Patient ==
215
+ 0) policies from Boost.Python.
216
+
217
+ Call guard
218
+ ----------
219
+
220
+ The ``call_guard<T>`` policy allows any scope guard type ``T`` to be placed
221
+ around the function call. For example, this definition:
222
+
223
+ .. code-block:: cpp
224
+
225
+ m.def("foo", foo, py::call_guard<T>());
226
+
227
+ is equivalent to the following pseudocode:
228
+
229
+ .. code-block:: cpp
230
+
231
+ m.def("foo", [](args...) {
232
+ T scope_guard;
233
+ return foo(args...); // forwarded arguments
234
+ });
235
+
236
+ The only requirement is that ``T`` is default-constructible, but otherwise any
237
+ scope guard will work. This is very useful in combination with ``gil_scoped_release``.
238
+ See :ref:`gil`.
239
+
240
+ Multiple guards can also be specified as ``py::call_guard<T1, T2, T3...>``. The
241
+ constructor order is left to right and destruction happens in reverse.
242
+
243
+ .. seealso::
244
+
245
+ The file :file:`tests/test_call_policies.cpp` contains a complete example
246
+ that demonstrates using `keep_alive` and `call_guard` in more detail.
247
+
248
+ .. _python_objects_as_args:
249
+
250
+ Python objects as arguments
251
+ ===========================
252
+
253
+ pybind11 exposes all major Python types using thin C++ wrapper classes. These
254
+ wrapper classes can also be used as parameters of functions in bindings, which
255
+ makes it possible to directly work with native Python types on the C++ side.
256
+ For instance, the following statement iterates over a Python ``dict``:
257
+
258
+ .. code-block:: cpp
259
+
260
+ void print_dict(const py::dict& dict) {
261
+ /* Easily interact with Python types */
262
+ for (auto item : dict)
263
+ std::cout << "key=" << std::string(py::str(item.first)) << ", "
264
+ << "value=" << std::string(py::str(item.second)) << std::endl;
265
+ }
266
+
267
+ It can be exported:
268
+
269
+ .. code-block:: cpp
270
+
271
+ m.def("print_dict", &print_dict);
272
+
273
+ And used in Python as usual:
274
+
275
+ .. code-block:: pycon
276
+
277
+ >>> print_dict({"foo": 123, "bar": "hello"})
278
+ key=foo, value=123
279
+ key=bar, value=hello
280
+
281
+ For more information on using Python objects in C++, see :doc:`/advanced/pycpp/index`.
282
+
283
+ Accepting \*args and \*\*kwargs
284
+ ===============================
285
+
286
+ Python provides a useful mechanism to define functions that accept arbitrary
287
+ numbers of arguments and keyword arguments:
288
+
289
+ .. code-block:: python
290
+
291
+ def generic(*args, **kwargs):
292
+ ... # do something with args and kwargs
293
+
294
+ Such functions can also be created using pybind11:
295
+
296
+ .. code-block:: cpp
297
+
298
+ void generic(py::args args, const py::kwargs& kwargs) {
299
+ /// .. do something with args
300
+ if (kwargs)
301
+ /// .. do something with kwargs
302
+ }
303
+
304
+ /// Binding code
305
+ m.def("generic", &generic);
306
+
307
+ The class ``py::args`` derives from ``py::tuple`` and ``py::kwargs`` derives
308
+ from ``py::dict``.
309
+
310
+ You may also use just one or the other, and may combine these with other
311
+ arguments. Note, however, that ``py::kwargs`` must always be the last argument
312
+ of the function, and ``py::args`` implies that any further arguments are
313
+ keyword-only (see :ref:`keyword_only_arguments`).
314
+
315
+ Please refer to the other examples for details on how to iterate over these,
316
+ and on how to cast their entries into C++ objects. A demonstration is also
317
+ available in ``tests/test_kwargs_and_defaults.cpp``.
318
+
319
+ .. note::
320
+
321
+ When combining \*args or \*\*kwargs with :ref:`keyword_args` you should
322
+ *not* include ``py::arg`` tags for the ``py::args`` and ``py::kwargs``
323
+ arguments.
324
+
325
+ Default arguments revisited
326
+ ===========================
327
+
328
+ The section on :ref:`default_args` previously discussed basic usage of default
329
+ arguments using pybind11. One noteworthy aspect of their implementation is that
330
+ default arguments are converted to Python objects right at declaration time.
331
+ Consider the following example:
332
+
333
+ .. code-block:: cpp
334
+
335
+ py::class_<MyClass>("MyClass")
336
+ .def("myFunction", py::arg("arg") = SomeType(123));
337
+
338
+ In this case, pybind11 must already be set up to deal with values of the type
339
+ ``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an
340
+ exception will be thrown.
341
+
342
+ Another aspect worth highlighting is that the "preview" of the default argument
343
+ in the function signature is generated using the object's ``__repr__`` method.
344
+ If not available, the signature may not be very helpful, e.g.:
345
+
346
+ .. code-block:: pycon
347
+
348
+ FUNCTIONS
349
+ ...
350
+ | myFunction(...)
351
+ | Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType
352
+ ...
353
+
354
+ The first way of addressing this is by defining ``SomeType.__repr__``.
355
+ Alternatively, it is possible to specify the human-readable preview of the
356
+ default argument manually using the ``arg_v`` notation:
357
+
358
+ .. code-block:: cpp
359
+
360
+ py::class_<MyClass>("MyClass")
361
+ .def("myFunction", py::arg_v("arg", SomeType(123), "SomeType(123)"));
362
+
363
+ Sometimes it may be necessary to pass a null pointer value as a default
364
+ argument. In this case, remember to cast it to the underlying type in question,
365
+ like so:
366
+
367
+ .. code-block:: cpp
368
+
369
+ py::class_<MyClass>("MyClass")
370
+ .def("myFunction", py::arg("arg") = static_cast<SomeType *>(nullptr));
371
+
372
+ .. _keyword_only_arguments:
373
+
374
+ Keyword-only arguments
375
+ ======================
376
+
377
+ Python implements keyword-only arguments by specifying an unnamed ``*``
378
+ argument in a function definition:
379
+
380
+ .. code-block:: python
381
+
382
+ def f(a, *, b): # a can be positional or via keyword; b must be via keyword
383
+ pass
384
+
385
+
386
+ f(a=1, b=2) # good
387
+ f(b=2, a=1) # good
388
+ f(1, b=2) # good
389
+ f(1, 2) # TypeError: f() takes 1 positional argument but 2 were given
390
+
391
+ Pybind11 provides a ``py::kw_only`` object that allows you to implement
392
+ the same behaviour by specifying the object between positional and keyword-only
393
+ argument annotations when registering the function:
394
+
395
+ .. code-block:: cpp
396
+
397
+ m.def("f", [](int a, int b) { /* ... */ },
398
+ py::arg("a"), py::kw_only(), py::arg("b"));
399
+
400
+ .. versionadded:: 2.6
401
+
402
+ A ``py::args`` argument implies that any following arguments are keyword-only,
403
+ as if ``py::kw_only()`` had been specified in the same relative location of the
404
+ argument list as the ``py::args`` argument. The ``py::kw_only()`` may be
405
+ included to be explicit about this, but is not required.
406
+
407
+ .. versionchanged:: 2.9
408
+ This can now be combined with ``py::args``. Before, ``py::args`` could only
409
+ occur at the end of the argument list, or immediately before a ``py::kwargs``
410
+ argument at the end.
411
+
412
+
413
+ Positional-only arguments
414
+ =========================
415
+
416
+ Python 3.8 introduced a new positional-only argument syntax, using ``/`` in the
417
+ function definition (note that this has been a convention for CPython
418
+ positional arguments, such as in ``pow()``, since Python 2). You can
419
+ do the same thing in any version of Python using ``py::pos_only()``:
420
+
421
+ .. code-block:: cpp
422
+
423
+ m.def("f", [](int a, int b) { /* ... */ },
424
+ py::arg("a"), py::pos_only(), py::arg("b"));
425
+
426
+ You now cannot give argument ``a`` by keyword. This can be combined with
427
+ keyword-only arguments, as well.
428
+
429
+ .. versionadded:: 2.6
430
+
431
+ .. _nonconverting_arguments:
432
+
433
+ Non-converting arguments
434
+ ========================
435
+
436
+ Certain argument types may support conversion from one type to another. Some
437
+ examples of conversions are:
438
+
439
+ * :ref:`implicit_conversions` declared using ``py::implicitly_convertible<A,B>()``
440
+ * Calling a method accepting a double with an integer argument
441
+ * Calling a ``std::complex<float>`` argument with a non-complex python type
442
+ (for example, with a float). (Requires the optional ``pybind11/complex.h``
443
+ header).
444
+ * Calling a function taking an Eigen matrix reference with a numpy array of the
445
+ wrong type or of an incompatible data layout. (Requires the optional
446
+ ``pybind11/eigen.h`` header).
447
+
448
+ This behaviour is sometimes undesirable: the binding code may prefer to raise
449
+ an error rather than convert the argument. This behaviour can be obtained
450
+ through ``py::arg`` by calling the ``.noconvert()`` method of the ``py::arg``
451
+ object, such as:
452
+
453
+ .. code-block:: cpp
454
+
455
+ m.def("floats_only", [](double f) { return 0.5 * f; }, py::arg("f").noconvert());
456
+ m.def("floats_preferred", [](double f) { return 0.5 * f; }, py::arg("f"));
457
+
458
+ Attempting the call the second function (the one without ``.noconvert()``) with
459
+ an integer will succeed, but attempting to call the ``.noconvert()`` version
460
+ will fail with a ``TypeError``:
461
+
462
+ .. code-block:: pycon
463
+
464
+ >>> floats_preferred(4)
465
+ 2.0
466
+ >>> floats_only(4)
467
+ Traceback (most recent call last):
468
+ File "<stdin>", line 1, in <module>
469
+ TypeError: floats_only(): incompatible function arguments. The following argument types are supported:
470
+ 1. (f: float) -> float
471
+
472
+ Invoked with: 4
473
+
474
+ You may, of course, combine this with the :var:`_a` shorthand notation (see
475
+ :ref:`keyword_args`) and/or :ref:`default_args`. It is also permitted to omit
476
+ the argument name by using the ``py::arg()`` constructor without an argument
477
+ name, i.e. by specifying ``py::arg().noconvert()``.
478
+
479
+ .. note::
480
+
481
+ When specifying ``py::arg`` options it is necessary to provide the same
482
+ number of options as the bound function has arguments. Thus if you want to
483
+ enable no-convert behaviour for just one of several arguments, you will
484
+ need to specify a ``py::arg()`` annotation for each argument with the
485
+ no-convert argument modified to ``py::arg().noconvert()``.
486
+
487
+ .. _none_arguments:
488
+
489
+ Allow/Prohibiting None arguments
490
+ ================================
491
+
492
+ When a C++ type registered with :class:`py::class_` is passed as an argument to
493
+ a function taking the instance as pointer or shared holder (e.g. ``shared_ptr``
494
+ or a custom, copyable holder as described in :ref:`smart_pointers`), pybind
495
+ allows ``None`` to be passed from Python which results in calling the C++
496
+ function with ``nullptr`` (or an empty holder) for the argument.
497
+
498
+ To explicitly enable or disable this behaviour, using the
499
+ ``.none`` method of the :class:`py::arg` object:
500
+
501
+ .. code-block:: cpp
502
+
503
+ py::class_<Dog>(m, "Dog").def(py::init<>());
504
+ py::class_<Cat>(m, "Cat").def(py::init<>());
505
+ m.def("bark", [](Dog *dog) -> std::string {
506
+ if (dog) return "woof!"; /* Called with a Dog instance */
507
+ else return "(no dog)"; /* Called with None, dog == nullptr */
508
+ }, py::arg("dog").none(true));
509
+ m.def("meow", [](Cat *cat) -> std::string {
510
+ // Can't be called with None argument
511
+ return "meow";
512
+ }, py::arg("cat").none(false));
513
+
514
+ With the above, the Python call ``bark(None)`` will return the string ``"(no
515
+ dog)"``, while attempting to call ``meow(None)`` will raise a ``TypeError``:
516
+
517
+ .. code-block:: pycon
518
+
519
+ >>> from animals import Dog, Cat, bark, meow
520
+ >>> bark(Dog())
521
+ 'woof!'
522
+ >>> meow(Cat())
523
+ 'meow'
524
+ >>> bark(None)
525
+ '(no dog)'
526
+ >>> meow(None)
527
+ Traceback (most recent call last):
528
+ File "<stdin>", line 1, in <module>
529
+ TypeError: meow(): incompatible function arguments. The following argument types are supported:
530
+ 1. (cat: animals.Cat) -> str
531
+
532
+ Invoked with: None
533
+
534
+ The default behaviour when the tag is unspecified is to allow ``None``.
535
+
536
+ .. note::
537
+
538
+ Even when ``.none(true)`` is specified for an argument, ``None`` will be converted to a
539
+ ``nullptr`` *only* for custom and :ref:`opaque <opaque>` types. Pointers to built-in types
540
+ (``double *``, ``int *``, ...) and STL types (``std::vector<T> *``, ...; if ``pybind11/stl.h``
541
+ is included) are copied when converted to C++ (see :doc:`/advanced/cast/overview`) and will
542
+ not allow ``None`` as argument. To pass optional argument of these copied types consider
543
+ using ``std::optional<T>``
544
+
545
+ .. _overload_resolution:
546
+
547
+ Overload resolution order
548
+ =========================
549
+
550
+ When a function or method with multiple overloads is called from Python,
551
+ pybind11 determines which overload to call in two passes. The first pass
552
+ attempts to call each overload without allowing argument conversion (as if
553
+ every argument had been specified as ``py::arg().noconvert()`` as described
554
+ above).
555
+
556
+ If no overload succeeds in the no-conversion first pass, a second pass is
557
+ attempted in which argument conversion is allowed (except where prohibited via
558
+ an explicit ``py::arg().noconvert()`` attribute in the function definition).
559
+
560
+ If the second pass also fails a ``TypeError`` is raised.
561
+
562
+ Within each pass, overloads are tried in the order they were registered with
563
+ pybind11. If the ``py::prepend()`` tag is added to the definition, a function
564
+ can be placed at the beginning of the overload sequence instead, allowing user
565
+ overloads to proceed built in functions.
566
+
567
+ What this means in practice is that pybind11 will prefer any overload that does
568
+ not require conversion of arguments to an overload that does, but otherwise
569
+ prefers earlier-defined overloads to later-defined ones.
570
+
571
+ .. note::
572
+
573
+ pybind11 does *not* further prioritize based on the number/pattern of
574
+ overloaded arguments. That is, pybind11 does not prioritize a function
575
+ requiring one conversion over one requiring three, but only prioritizes
576
+ overloads requiring no conversion at all to overloads that require
577
+ conversion of at least one argument.
578
+
579
+ .. versionadded:: 2.6
580
+
581
+ The ``py::prepend()`` tag.
582
+
583
+ Binding functions with template parameters
584
+ ==========================================
585
+
586
+ You can bind functions that have template parameters. Here's a function:
587
+
588
+ .. code-block:: cpp
589
+
590
+ template <typename T>
591
+ void set(T t);
592
+
593
+ C++ templates cannot be instantiated at runtime, so you cannot bind the
594
+ non-instantiated function:
595
+
596
+ .. code-block:: cpp
597
+
598
+ // BROKEN (this will not compile)
599
+ m.def("set", &set);
600
+
601
+ You must bind each instantiated function template separately. You may bind
602
+ each instantiation with the same name, which will be treated the same as
603
+ an overloaded function:
604
+
605
+ .. code-block:: cpp
606
+
607
+ m.def("set", &set<int>);
608
+ m.def("set", &set<std::string>);
609
+
610
+ Sometimes it's more clear to bind them with separate names, which is also
611
+ an option:
612
+
613
+ .. code-block:: cpp
614
+
615
+ m.def("setInt", &set<int>);
616
+ m.def("setString", &set<std::string>);
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/misc.rst ADDED
@@ -0,0 +1,615 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Miscellaneous
2
+ #############
3
+
4
+ .. _macro_notes:
5
+
6
+ General notes regarding convenience macros
7
+ ==========================================
8
+
9
+ pybind11 provides a few convenience macros such as
10
+ :func:`PYBIND11_DECLARE_HOLDER_TYPE` and ``PYBIND11_OVERRIDE_*``. Since these
11
+ are "just" macros that are evaluated in the preprocessor (which has no concept
12
+ of types), they *will* get confused by commas in a template argument; for
13
+ example, consider:
14
+
15
+ .. code-block:: cpp
16
+
17
+ PYBIND11_OVERRIDE(MyReturnType<T1, T2>, Class<T3, T4>, func)
18
+
19
+ The limitation of the C preprocessor interprets this as five arguments (with new
20
+ arguments beginning after each comma) rather than three. To get around this,
21
+ there are two alternatives: you can use a type alias, or you can wrap the type
22
+ using the ``PYBIND11_TYPE`` macro:
23
+
24
+ .. code-block:: cpp
25
+
26
+ // Version 1: using a type alias
27
+ using ReturnType = MyReturnType<T1, T2>;
28
+ using ClassType = Class<T3, T4>;
29
+ PYBIND11_OVERRIDE(ReturnType, ClassType, func);
30
+
31
+ // Version 2: using the PYBIND11_TYPE macro:
32
+ PYBIND11_OVERRIDE(PYBIND11_TYPE(MyReturnType<T1, T2>),
33
+ PYBIND11_TYPE(Class<T3, T4>), func)
34
+
35
+ The ``PYBIND11_MAKE_OPAQUE`` macro does *not* require the above workarounds.
36
+
37
+ .. _gil:
38
+
39
+ Global Interpreter Lock (GIL)
40
+ =============================
41
+
42
+ The Python C API dictates that the Global Interpreter Lock (GIL) must always
43
+ be held by the current thread to safely access Python objects. As a result,
44
+ when Python calls into C++ via pybind11 the GIL must be held, and pybind11
45
+ will never implicitly release the GIL.
46
+
47
+ .. code-block:: cpp
48
+
49
+ void my_function() {
50
+ /* GIL is held when this function is called from Python */
51
+ }
52
+
53
+ PYBIND11_MODULE(example, m) {
54
+ m.def("my_function", &my_function);
55
+ }
56
+
57
+ pybind11 will ensure that the GIL is held when it knows that it is calling
58
+ Python code. For example, if a Python callback is passed to C++ code via
59
+ ``std::function``, when C++ code calls the function the built-in wrapper
60
+ will acquire the GIL before calling the Python callback. Similarly, the
61
+ ``PYBIND11_OVERRIDE`` family of macros will acquire the GIL before calling
62
+ back into Python.
63
+
64
+ When writing C++ code that is called from other C++ code, if that code accesses
65
+ Python state, it must explicitly acquire and release the GIL. A separate
66
+ document on deadlocks [#f8]_ elaborates on a particularly subtle interaction
67
+ with C++'s block-scope static variable initializer guard mutexes.
68
+
69
+ .. [#f8] See docs/advanced/deadlock.md
70
+
71
+ The classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be
72
+ used to acquire and release the global interpreter lock in the body of a C++
73
+ function call. In this way, long-running C++ code can be parallelized using
74
+ multiple Python threads, **but great care must be taken** when any
75
+ :class:`gil_scoped_release` appear: if there is any way that the C++ code
76
+ can access Python objects, :class:`gil_scoped_acquire` should be used to
77
+ reacquire the GIL. Taking :ref:`overriding_virtuals` as an example, this
78
+ could be realized as follows (important changes highlighted):
79
+
80
+ .. code-block:: cpp
81
+ :emphasize-lines: 8,30,31
82
+
83
+ class PyAnimal : public Animal, public py::trampoline_self_life_support {
84
+ public:
85
+ /* Inherit the constructors */
86
+ using Animal::Animal;
87
+
88
+ /* Trampoline (need one for each virtual function) */
89
+ std::string go(int n_times) {
90
+ /* PYBIND11_OVERRIDE_PURE will acquire the GIL before accessing Python state */
91
+ PYBIND11_OVERRIDE_PURE(
92
+ std::string, /* Return type */
93
+ Animal, /* Parent class */
94
+ go, /* Name of function */
95
+ n_times /* Argument(s) */
96
+ );
97
+ }
98
+ };
99
+
100
+ PYBIND11_MODULE(example, m) {
101
+ py::class_<Animal, PyAnimal, py::smart_holder> animal(m, "Animal");
102
+ animal
103
+ .def(py::init<>())
104
+ .def("go", &Animal::go);
105
+
106
+ py::class_<Dog, py::smart_holder>(m, "Dog", animal)
107
+ .def(py::init<>());
108
+
109
+ m.def("call_go", [](Animal *animal) -> std::string {
110
+ // GIL is held when called from Python code. Release GIL before
111
+ // calling into (potentially long-running) C++ code
112
+ py::gil_scoped_release release;
113
+ return call_go(animal);
114
+ });
115
+ }
116
+
117
+ The ``call_go`` wrapper can also be simplified using the ``call_guard`` policy
118
+ (see :ref:`call_policies`) which yields the same result:
119
+
120
+ .. code-block:: cpp
121
+
122
+ m.def("call_go", &call_go, py::call_guard<py::gil_scoped_release>());
123
+
124
+
125
+ .. _commongilproblems:
126
+
127
+ Common Sources Of Global Interpreter Lock Errors
128
+ ==================================================================
129
+
130
+ Failing to properly hold the Global Interpreter Lock (GIL) is one of the
131
+ more common sources of bugs within code that uses pybind11. If you are
132
+ running into GIL related errors, we highly recommend you consult the
133
+ following checklist.
134
+
135
+ - Do you have any global variables that are pybind11 objects or invoke
136
+ pybind11 functions in either their constructor or destructor? You are generally
137
+ not allowed to invoke any Python function in a global static context. We recommend
138
+ using lazy initialization and then intentionally leaking at the end of the program.
139
+
140
+ - Do you have any pybind11 objects that are members of other C++ structures? One
141
+ commonly overlooked requirement is that pybind11 objects have to increase their reference count
142
+ whenever their copy constructor is called. Thus, you need to be holding the GIL to invoke
143
+ the copy constructor of any C++ class that has a pybind11 member. This can sometimes be very
144
+ tricky to track for complicated programs Think carefully when you make a pybind11 object
145
+ a member in another struct.
146
+
147
+ - C++ destructors that invoke Python functions can be particularly troublesome as
148
+ destructors can sometimes get invoked in weird and unexpected circumstances as a result
149
+ of exceptions.
150
+
151
+ - C++ static block-scope variable initialization that calls back into Python can
152
+ cause deadlocks; see [#f8]_ for a detailed discussion.
153
+
154
+ - You should try running your code in a debug build. That will enable additional assertions
155
+ within pybind11 that will throw exceptions on certain GIL handling errors
156
+ (reference counting operations).
157
+
158
+ .. _misc_free_threading:
159
+
160
+ Free-threading support
161
+ ==================================================================
162
+
163
+ pybind11 supports the experimental free-threaded builds of Python versions 3.13+.
164
+ pybind11's internal data structures are thread safe. To enable your modules to be used with
165
+ free-threading, pass the :class:`mod_gil_not_used` tag as the third argument to
166
+ ``PYBIND11_MODULE``.
167
+
168
+ For example:
169
+
170
+ .. code-block:: cpp
171
+ :emphasize-lines: 1
172
+
173
+ PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {
174
+ py::class_<Animal> animal(m, "Animal");
175
+ // etc
176
+ }
177
+
178
+ Importantly, enabling your module to be used with free-threading is also your promise that
179
+ your code is thread safe. Modules must still be built against the Python free-threading branch to
180
+ enable free-threading, even if they specify this tag. Adding this tag does not break
181
+ compatibility with non-free-threaded Python.
182
+
183
+ .. _misc_subinterp:
184
+
185
+ Sub-interpreter support
186
+ ==================================================================
187
+
188
+ pybind11 supports isolated sub-interpreters, which are stable in Python 3.12+. pybind11's
189
+ internal data structures are sub-interpreter safe. To enable your modules to be imported in
190
+ isolated sub-interpreters, pass the :func:`multiple_interpreters::per_interpreter_gil()`
191
+ tag as the third or later argument to ``PYBIND11_MODULE``.
192
+
193
+ For example:
194
+
195
+ .. code-block:: cpp
196
+ :emphasize-lines: 1
197
+
198
+ PYBIND11_MODULE(example, m, py::multiple_interpreters::per_interpreter_gil()) {
199
+ py::class_<Animal> animal(m, "Animal");
200
+ // etc
201
+ }
202
+
203
+ Best Practices for Sub-interpreter Safety:
204
+
205
+ - Your initialization function will run for each interpreter that imports your module.
206
+
207
+ - Never share Python objects across different sub-interpreters.
208
+
209
+ - Avoid global/static state whenever possible. Instead, keep state within each interpreter,
210
+ such as in instance members tied to Python objects, :func:`globals()`, and the interpreter
211
+ state dict.
212
+
213
+ - Modules without any global/static state in their C++ code may already be sub-interpreter safe
214
+ without any additional work!
215
+
216
+ - Avoid trying to "cache" Python objects in C++ variables across function calls (this is an easy
217
+ way to accidentally introduce sub-interpreter bugs).
218
+
219
+ - While sub-interpreters each have their own GIL, there can now be multiple independent GILs in one
220
+ program, so concurrent calls into a module from two different sub-interpreters are still
221
+ possible. Therefore, your module still needs to consider thread safety.
222
+
223
+ pybind11 also supports "legacy" sub-interpreters which shared a single global GIL. You can enable
224
+ legacy-only behavior by using the :func:`multiple_interpreters::shared_gil()` tag in
225
+ ``PYBIND11_MODULE``.
226
+
227
+ You can explicitly disable sub-interpreter support in your module by using the
228
+ :func:`multiple_interpreters::not_supported()` tag. This is the default behavior if you do not
229
+ specify a multiple_interpreters tag.
230
+
231
+ .. _misc_concurrency:
232
+
233
+ Concurrency and Parallelism in Python with pybind11
234
+ ===================================================
235
+
236
+ Sub-interpreter support does not imply free-threading support or vice versa. Free-threading safe
237
+ modules can still have global/static state (as long as access to them is thread-safe), but
238
+ sub-interpreter safe modules cannot. Likewise, sub-interpreter safe modules can still rely on the
239
+ GIL, but free-threading safe modules cannot.
240
+
241
+ Here is a simple example module which has a function that calculates a value and returns the result
242
+ of the previous calculation.
243
+
244
+ .. code-block:: cpp
245
+
246
+ PYBIND11_MODULE(example, m) {
247
+ static size_t seed = 0;
248
+ m.def("calc_next", []() {
249
+ auto old = seed;
250
+ seed = (seed + 1) * 10;
251
+ return old;
252
+ });
253
+
254
+ This module is not free-threading safe because there is no synchronization on the number variable.
255
+ It is relatively easy to make this free-threading safe. One way is by using atomics, like this:
256
+
257
+ .. code-block:: cpp
258
+ :emphasize-lines: 1,2
259
+
260
+ PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {
261
+ static std::atomic<size_t> seed(0);
262
+ m.def("calc_next", []() {
263
+ size_t old, next;
264
+ do {
265
+ old = seed.load();
266
+ next = (old + 1) * 10;
267
+ } while (!seed.compare_exchange_weak(old, next));
268
+ return old;
269
+ });
270
+ }
271
+
272
+ The atomic variable and the compare-exchange guarantee a consistent behavior from this function even
273
+ when called currently from multiple threads at the same time.
274
+
275
+ However, the global/static integer is not sub-interpreter safe, because the calls in one
276
+ sub-interpreter will change what is seen in another. To fix it, the state needs to be specific to
277
+ each interpreter. One way to do that is by storing the state on another Python object, such as a
278
+ member of a class. For this simple example, we will store it in :func:`globals`.
279
+
280
+ .. code-block:: cpp
281
+ :emphasize-lines: 1,6
282
+
283
+ PYBIND11_MODULE(example, m, py::multiple_interpreters::per_interpreter_gil()) {
284
+ m.def("calc_next", []() {
285
+ if (!py::globals().contains("myseed"))
286
+ py::globals()["myseed"] = 0;
287
+ size_t old = py::globals()["myseed"];
288
+ py::globals()["myseed"] = (old + 1) * 10;
289
+ return old;
290
+ });
291
+ }
292
+
293
+ This module is sub-interpreter safe, for both ``shared_gil`` ("legacy") and
294
+ ``per_interpreter_gil`` ("default") varieties. Multiple sub-interpreters could each call this same
295
+ function concurrently from different threads. This is safe because each sub-interpreter's GIL
296
+ protects it's own Python objects from concurrent access.
297
+
298
+ However, the module is no longer free-threading safe, for the same reason as
299
+ before, because the calculation is not synchronized. We can synchronize it
300
+ using a Python critical section. This will do nothing if not in free-threaded
301
+ Python. You can have it lock one or two Python objects. You cannot nest it.
302
+
303
+ .. warning::
304
+
305
+ When using a ``py::scoped_critical_section``, make sure it is not nested and
306
+ that no other synchronization primitives (such as a ``std::mutex``) are
307
+ held, which could lead to deadlocks. In 3.13, taking the same lock causes it
308
+ to release then reacquire, which means you can't use it to, for example, read
309
+ and write to a dictionary, because the dictionary uses a critical section
310
+ internally in CPython. Use a ``std::mutex`` instead if you need this on
311
+ Python 3.13. In 3.14, taking a lock on a locked object no longer releases
312
+ and relocks as an optimization, which also fixes this case.
313
+
314
+ .. code-block:: cpp
315
+ :emphasize-lines: 1,4,8
316
+
317
+ #include <pybind11/critical_section.h>
318
+ // ...
319
+
320
+ PYBIND11_MODULE(example, m, py::multiple_interpreters::per_interpreter_gil(), py::mod_gil_not_used()) {
321
+ m.def("calc_next", []() {
322
+ size_t old;
323
+ py::dict g = py::globals();
324
+ py::scoped_critical_section guard(g);
325
+ if (!g.contains("myseed"))
326
+ g["myseed"] = 0;
327
+ old = g["myseed"];
328
+ g["myseed"] = (old + 1) * 10;
329
+ return old;
330
+ });
331
+ }
332
+
333
+ The module is now both sub-interpreter safe and free-threading safe.
334
+
335
+ Binding sequence data types, iterators, the slicing protocol, etc.
336
+ ==================================================================
337
+
338
+ Please refer to the supplemental example for details.
339
+
340
+ .. seealso::
341
+
342
+ The file :file:`tests/test_sequences_and_iterators.cpp` contains a
343
+ complete example that shows how to bind a sequence data type, including
344
+ length queries (``__len__``), iterators (``__iter__``), the slicing
345
+ protocol and other kinds of useful operations.
346
+
347
+
348
+ Partitioning code over multiple extension modules
349
+ =================================================
350
+
351
+ It's straightforward to split binding code over multiple extension modules,
352
+ while referencing types that are declared elsewhere. Everything "just" works
353
+ without any special precautions. One exception to this rule occurs when
354
+ extending a type declared in another extension module. Recall the basic example
355
+ from Section :ref:`inheritance`.
356
+
357
+ .. code-block:: cpp
358
+
359
+ py::class_<Pet> pet(m, "Pet");
360
+ pet.def(py::init<const std::string &>())
361
+ .def_readwrite("name", &Pet::name);
362
+
363
+ py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
364
+ .def(py::init<const std::string &>())
365
+ .def("bark", &Dog::bark);
366
+
367
+ Suppose now that ``Pet`` bindings are defined in a module named ``basic``,
368
+ whereas the ``Dog`` bindings are defined somewhere else. The challenge is of
369
+ course that the variable ``pet`` is not available anymore though it is needed
370
+ to indicate the inheritance relationship to the constructor of ``py::class_<Dog>``.
371
+ However, it can be acquired as follows:
372
+
373
+ .. code-block:: cpp
374
+
375
+ py::object pet = (py::object) py::module_::import("basic").attr("Pet");
376
+
377
+ py::class_<Dog>(m, "Dog", pet)
378
+ .def(py::init<const std::string &>())
379
+ .def("bark", &Dog::bark);
380
+
381
+ Alternatively, you can specify the base class as a template parameter option to
382
+ ``py::class_``, which performs an automated lookup of the corresponding Python
383
+ type. Like the above code, however, this also requires invoking the ``import``
384
+ function once to ensure that the pybind11 binding code of the module ``basic``
385
+ has been executed:
386
+
387
+ .. code-block:: cpp
388
+
389
+ py::module_::import("basic");
390
+
391
+ py::class_<Dog, Pet>(m, "Dog")
392
+ .def(py::init<const std::string &>())
393
+ .def("bark", &Dog::bark);
394
+
395
+ Naturally, both methods will fail when there are cyclic dependencies.
396
+
397
+ Note that pybind11 code compiled with hidden-by-default symbol visibility (e.g.
398
+ via the command line flag ``-fvisibility=hidden`` on GCC/Clang), which is
399
+ required for proper pybind11 functionality, can interfere with the ability to
400
+ access types defined in another extension module. Working around this requires
401
+ manually exporting types that are accessed by multiple extension modules;
402
+ pybind11 provides a macro to do just this:
403
+
404
+ .. code-block:: cpp
405
+
406
+ class PYBIND11_EXPORT Dog : public Animal {
407
+ ...
408
+ };
409
+
410
+ Note also that it is possible (although would rarely be required) to share arbitrary
411
+ C++ objects between extension modules at runtime. Internal library data is shared
412
+ between modules using capsule machinery [#f6]_ which can be also utilized for
413
+ storing, modifying and accessing user-defined data. Note that an extension module
414
+ will "see" other extensions' data if and only if they were built with the same
415
+ pybind11 version. Consider the following example:
416
+
417
+ .. code-block:: cpp
418
+
419
+ auto data = reinterpret_cast<MyData *>(py::get_shared_data("mydata"));
420
+ if (!data)
421
+ data = static_cast<MyData *>(py::set_shared_data("mydata", new MyData(42)));
422
+
423
+ If the above snippet was used in several separately compiled extension modules,
424
+ the first one to be imported would create a ``MyData`` instance and associate
425
+ a ``"mydata"`` key with a pointer to it. Extensions that are imported later
426
+ would be then able to access the data behind the same pointer.
427
+
428
+ .. [#f6] https://docs.python.org/3/extending/extending.html#using-capsules
429
+
430
+ Module Destructors
431
+ ==================
432
+
433
+ pybind11 does not provide an explicit mechanism to invoke cleanup code at
434
+ module destruction time. In rare cases where such functionality is required, it
435
+ is possible to emulate it using Python capsules or weak references with a
436
+ destruction callback.
437
+
438
+ .. code-block:: cpp
439
+
440
+ auto cleanup_callback = []() {
441
+ // perform cleanup here -- this function is called with the GIL held
442
+ };
443
+
444
+ m.add_object("_cleanup", py::capsule(cleanup_callback));
445
+
446
+ This approach has the potential downside that instances of classes exposed
447
+ within the module may still be alive when the cleanup callback is invoked
448
+ (whether this is acceptable will generally depend on the application).
449
+
450
+ Alternatively, the capsule may also be stashed within a type object, which
451
+ ensures that it not called before all instances of that type have been
452
+ collected:
453
+
454
+ .. code-block:: cpp
455
+
456
+ auto cleanup_callback = []() { /* ... */ };
457
+ m.attr("BaseClass").attr("_cleanup") = py::capsule(cleanup_callback);
458
+
459
+ Both approaches also expose a potentially dangerous ``_cleanup`` attribute in
460
+ Python, which may be undesirable from an API standpoint (a premature explicit
461
+ call from Python might lead to undefined behavior). Yet another approach that
462
+ avoids this issue involves weak reference with a cleanup callback:
463
+
464
+ .. code-block:: cpp
465
+
466
+ // Register a callback function that is invoked when the BaseClass object is collected
467
+ py::cpp_function cleanup_callback(
468
+ [](py::handle weakref) {
469
+ // perform cleanup here -- this function is called with the GIL held
470
+
471
+ weakref.dec_ref(); // release weak reference
472
+ }
473
+ );
474
+
475
+ // Create a weak reference with a cleanup callback and initially leak it
476
+ (void) py::weakref(m.attr("BaseClass"), cleanup_callback).release();
477
+
478
+ .. note::
479
+
480
+ PyPy does not garbage collect objects when the interpreter exits. An alternative
481
+ approach (which also works on CPython) is to use the :py:mod:`atexit` module [#f7]_,
482
+ for example:
483
+
484
+ .. code-block:: cpp
485
+
486
+ auto atexit = py::module_::import("atexit");
487
+ atexit.attr("register")(py::cpp_function([]() {
488
+ // perform cleanup here -- this function is called with the GIL held
489
+ }));
490
+
491
+ .. [#f7] https://docs.python.org/3/library/atexit.html
492
+
493
+
494
+ Generating documentation using Sphinx
495
+ =====================================
496
+
497
+ Sphinx [#f4]_ has the ability to inspect the signatures and documentation
498
+ strings in pybind11-based extension modules to automatically generate beautiful
499
+ documentation in a variety formats. The python_example repository [#f5]_ contains a
500
+ simple example repository which uses this approach.
501
+
502
+ There are two potential gotchas when using this approach: first, make sure that
503
+ the resulting strings do not contain any :kbd:`TAB` characters, which break the
504
+ docstring parsing routines. You may want to use C++11 raw string literals,
505
+ which are convenient for multi-line comments. Conveniently, any excess
506
+ indentation will be automatically be removed by Sphinx. However, for this to
507
+ work, it is important that all lines are indented consistently, i.e.:
508
+
509
+ .. code-block:: cpp
510
+
511
+ // ok
512
+ m.def("foo", &foo, R"mydelimiter(
513
+ The foo function
514
+
515
+ Parameters
516
+ ----------
517
+ )mydelimiter");
518
+
519
+ // *not ok*
520
+ m.def("foo", &foo, R"mydelimiter(The foo function
521
+
522
+ Parameters
523
+ ----------
524
+ )mydelimiter");
525
+
526
+ By default, pybind11 automatically generates and prepends a signature to the docstring of a function
527
+ registered with ``module_::def()`` and ``class_::def()``. Sometimes this
528
+ behavior is not desirable, because you want to provide your own signature or remove
529
+ the docstring completely to exclude the function from the Sphinx documentation.
530
+ The class ``options`` allows you to selectively suppress auto-generated signatures:
531
+
532
+ .. code-block:: cpp
533
+
534
+ PYBIND11_MODULE(example, m) {
535
+ py::options options;
536
+ options.disable_function_signatures();
537
+
538
+ m.def("add", [](int a, int b) { return a + b; }, "A function which adds two numbers");
539
+ }
540
+
541
+ pybind11 also appends all members of an enum to the resulting enum docstring.
542
+ This default behavior can be disabled by using the ``disable_enum_members_docstring()``
543
+ function of the ``options`` class.
544
+
545
+ With ``disable_user_defined_docstrings()`` all user defined docstrings of
546
+ ``module_::def()``, ``class_::def()`` and ``enum_()`` are disabled, but the
547
+ function signatures and enum members are included in the docstring, unless they
548
+ are disabled separately.
549
+
550
+ Note that changes to the settings affect only function bindings created during the
551
+ lifetime of the ``options`` instance. When it goes out of scope at the end of the module's init function,
552
+ the default settings are restored to prevent unwanted side effects.
553
+
554
+ .. [#f4] http://www.sphinx-doc.org
555
+ .. [#f5] http://github.com/pybind/python_example
556
+
557
+ .. _avoiding-cpp-types-in-docstrings:
558
+
559
+ Avoiding C++ types in docstrings
560
+ ================================
561
+
562
+ Docstrings are generated at the time of the declaration, e.g. when ``.def(...)`` is called.
563
+ At this point parameter and return types should be known to pybind11.
564
+ If a custom type is not exposed yet through a ``py::class_`` constructor or a custom type caster,
565
+ its C++ type name will be used instead to generate the signature in the docstring:
566
+
567
+ .. code-block:: text
568
+
569
+ | __init__(...)
570
+ | __init__(self: example.Foo, arg0: ns::Bar) -> None
571
+ ^^^^^^^
572
+
573
+
574
+ This limitation can be circumvented by ensuring that C++ classes are registered with pybind11
575
+ before they are used as a parameter or return type of a function:
576
+
577
+ .. code-block:: cpp
578
+
579
+ PYBIND11_MODULE(example, m) {
580
+
581
+ auto pyFoo = py::class_<ns::Foo>(m, "Foo");
582
+ auto pyBar = py::class_<ns::Bar>(m, "Bar");
583
+
584
+ pyFoo.def(py::init<const ns::Bar&>());
585
+ pyBar.def(py::init<const ns::Foo&>());
586
+ }
587
+
588
+ Setting inner type hints in docstrings
589
+ ======================================
590
+
591
+ When you use pybind11 wrappers for ``list``, ``dict``, and other generic python
592
+ types, the docstring will just display the generic type. You can convey the
593
+ inner types in the docstring by using a special 'typed' version of the generic
594
+ type.
595
+
596
+ .. code-block:: cpp
597
+
598
+ PYBIND11_MODULE(example, m) {
599
+ m.def("pass_list_of_str", [](py::typing::List<py::str> arg) {
600
+ // arg can be used just like py::list
601
+ ));
602
+ }
603
+
604
+ The resulting docstring will be ``pass_list_of_str(arg0: list[str]) -> None``.
605
+
606
+ The following special types are available in ``pybind11/typing.h``:
607
+
608
+ * ``py::Tuple<Args...>``
609
+ * ``py::Dict<K, V>``
610
+ * ``py::List<V>``
611
+ * ``py::Set<V>``
612
+ * ``py::Callable<Signature>``
613
+
614
+ .. warning:: Just like in python, these are merely hints. They don't actually
615
+ enforce the types of their contents at runtime or compile time.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/pycpp/index.rst ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Python C++ interface
2
+ ####################
3
+
4
+ pybind11 exposes Python types and functions using thin C++ wrappers, which
5
+ makes it possible to conveniently call Python code from C++ without resorting
6
+ to Python's C API.
7
+
8
+ .. toctree::
9
+ :maxdepth: 2
10
+
11
+ object
12
+ numpy
13
+ utilities
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/pycpp/numpy.rst ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _numpy:
2
+
3
+ NumPy
4
+ #####
5
+
6
+ Buffer protocol
7
+ ===============
8
+
9
+ Python supports an extremely general and convenient approach for exchanging
10
+ data between plugin libraries. Types can expose a buffer view [#f2]_, which
11
+ provides fast direct access to the raw internal data representation. Suppose we
12
+ want to bind the following simplistic Matrix class:
13
+
14
+ .. code-block:: cpp
15
+
16
+ class Matrix {
17
+ public:
18
+ Matrix(size_t rows, size_t cols) : m_rows(rows), m_cols(cols) {
19
+ m_data = new float[rows*cols];
20
+ }
21
+ float *data() { return m_data; }
22
+ size_t rows() const { return m_rows; }
23
+ size_t cols() const { return m_cols; }
24
+ private:
25
+ size_t m_rows, m_cols;
26
+ float *m_data;
27
+ };
28
+
29
+ The following binding code exposes the ``Matrix`` contents as a buffer object,
30
+ making it possible to cast Matrices into NumPy arrays. It is even possible to
31
+ completely avoid copy operations with Python expressions like
32
+ ``np.array(matrix_instance, copy = False)``.
33
+
34
+ .. code-block:: cpp
35
+
36
+ py::class_<Matrix>(m, "Matrix", py::buffer_protocol())
37
+ .def_buffer([](Matrix &m) -> py::buffer_info {
38
+ return py::buffer_info(
39
+ m.data(), /* Pointer to buffer */
40
+ sizeof(float), /* Size of one scalar */
41
+ py::format_descriptor<float>::format(), /* Python struct-style format descriptor */
42
+ 2, /* Number of dimensions */
43
+ { m.rows(), m.cols() }, /* Buffer dimensions */
44
+ { sizeof(float) * m.cols(), /* Strides (in bytes) for each index */
45
+ sizeof(float) }
46
+ );
47
+ });
48
+
49
+ Supporting the buffer protocol in a new type involves specifying the special
50
+ ``py::buffer_protocol()`` tag in the ``py::class_`` constructor and calling the
51
+ ``def_buffer()`` method with a lambda function that creates a
52
+ ``py::buffer_info`` description record on demand describing a given matrix
53
+ instance. The contents of ``py::buffer_info`` mirror the Python buffer protocol
54
+ specification.
55
+
56
+ .. code-block:: cpp
57
+
58
+ struct buffer_info {
59
+ void *ptr;
60
+ py::ssize_t itemsize;
61
+ std::string format;
62
+ py::ssize_t ndim;
63
+ std::vector<py::ssize_t> shape;
64
+ std::vector<py::ssize_t> strides;
65
+ };
66
+
67
+ To create a C++ function that can take a Python buffer object as an argument,
68
+ simply use the type ``py::buffer`` as one of its arguments. Buffers can exist
69
+ in a great variety of configurations, hence some safety checks are usually
70
+ necessary in the function body. Below, you can see a basic example on how to
71
+ define a custom constructor for the Eigen double precision matrix
72
+ (``Eigen::MatrixXd``) type, which supports initialization from compatible
73
+ buffer objects (e.g. a NumPy matrix).
74
+
75
+ .. code-block:: cpp
76
+
77
+ /* Bind MatrixXd (or some other Eigen type) to Python */
78
+ typedef Eigen::MatrixXd Matrix;
79
+
80
+ typedef Matrix::Scalar Scalar;
81
+ constexpr bool rowMajor = Matrix::Flags & Eigen::RowMajorBit;
82
+
83
+ py::class_<Matrix>(m, "Matrix", py::buffer_protocol())
84
+ .def(py::init([](py::buffer b) {
85
+ typedef Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic> Strides;
86
+
87
+ /* Request a buffer descriptor from Python */
88
+ py::buffer_info info = b.request();
89
+
90
+ /* Some basic validation checks ... */
91
+ if (!info.item_type_is_equivalent_to<Scalar>())
92
+ throw std::runtime_error("Incompatible format: expected a double array!");
93
+
94
+ if (info.ndim != 2)
95
+ throw std::runtime_error("Incompatible buffer dimension!");
96
+
97
+ auto strides = Strides(
98
+ info.strides[rowMajor ? 0 : 1] / (py::ssize_t)sizeof(Scalar),
99
+ info.strides[rowMajor ? 1 : 0] / (py::ssize_t)sizeof(Scalar));
100
+
101
+ auto map = Eigen::Map<Matrix, 0, Strides>(
102
+ static_cast<Scalar *>(info.ptr), info.shape[0], info.shape[1], strides);
103
+
104
+ return Matrix(map);
105
+ }));
106
+
107
+ For reference, the ``def_buffer()`` call for this Eigen data type should look
108
+ as follows:
109
+
110
+ .. code-block:: cpp
111
+
112
+ .def_buffer([](Matrix &m) -> py::buffer_info {
113
+ return py::buffer_info(
114
+ m.data(), /* Pointer to buffer */
115
+ sizeof(Scalar), /* Size of one scalar */
116
+ py::format_descriptor<Scalar>::format(), /* Python struct-style format descriptor */
117
+ 2, /* Number of dimensions */
118
+ { m.rows(), m.cols() }, /* Buffer dimensions */
119
+ { sizeof(Scalar) * (rowMajor ? m.cols() : 1),
120
+ sizeof(Scalar) * (rowMajor ? 1 : m.rows()) }
121
+ /* Strides (in bytes) for each index */
122
+ );
123
+ })
124
+
125
+ For a much easier approach of binding Eigen types (although with some
126
+ limitations), refer to the section on :doc:`/advanced/cast/eigen`.
127
+
128
+ .. seealso::
129
+
130
+ The file :file:`tests/test_buffers.cpp` contains a complete example
131
+ that demonstrates using the buffer protocol with pybind11 in more detail.
132
+
133
+ .. [#f2] http://docs.python.org/3/c-api/buffer.html
134
+
135
+ Arrays
136
+ ======
137
+
138
+ By exchanging ``py::buffer`` with ``py::array`` in the above snippet, we can
139
+ restrict the function so that it only accepts NumPy arrays (rather than any
140
+ type of Python object satisfying the buffer protocol).
141
+
142
+ In many situations, we want to define a function which only accepts a NumPy
143
+ array of a certain data type. This is possible via the ``py::array_t<T>``
144
+ template. For instance, the following function requires the argument to be a
145
+ NumPy array containing double precision values.
146
+
147
+ .. code-block:: cpp
148
+
149
+ void f(py::array_t<double> array);
150
+
151
+ When it is invoked with a different type (e.g. an integer or a list of
152
+ integers), the binding code will attempt to cast the input into a NumPy array
153
+ of the requested type. This feature requires the :file:`pybind11/numpy.h`
154
+ header to be included. Note that :file:`pybind11/numpy.h` does not depend on
155
+ the NumPy headers, and thus can be used without declaring a build-time
156
+ dependency on NumPy; NumPy>=1.7.0 is a runtime dependency.
157
+
158
+ Data in NumPy arrays is not guaranteed to packed in a dense manner;
159
+ furthermore, entries can be separated by arbitrary column and row strides.
160
+ Sometimes, it can be useful to require a function to only accept dense arrays
161
+ using either the C (row-major) or Fortran (column-major) ordering. This can be
162
+ accomplished via a second template argument with values ``py::array::c_style``
163
+ or ``py::array::f_style``.
164
+
165
+ .. code-block:: cpp
166
+
167
+ void f(py::array_t<double, py::array::c_style | py::array::forcecast> array);
168
+
169
+ The ``py::array::forcecast`` argument is the default value of the second
170
+ template parameter, and it ensures that non-conforming arguments are converted
171
+ into an array satisfying the specified requirements instead of trying the next
172
+ function overload.
173
+
174
+ There are several methods on arrays; the methods listed below under references
175
+ work, as well as the following functions based on the NumPy API:
176
+
177
+ - ``.dtype()`` returns the type of the contained values.
178
+
179
+ - ``.strides()`` returns a pointer to the strides of the array (optionally pass
180
+ an integer axis to get a number).
181
+
182
+ - ``.flags()`` returns the flag settings. ``.writable()`` and ``.owndata()``
183
+ are directly available.
184
+
185
+ - ``.offset_at()`` returns the offset (optionally pass indices).
186
+
187
+ - ``.squeeze()`` returns a view with length-1 axes removed.
188
+
189
+ - ``.view(dtype)`` returns a view of the array with a different dtype.
190
+
191
+ - ``.reshape({i, j, ...})`` returns a view of the array with a different shape.
192
+ ``.resize({...})`` is also available.
193
+
194
+ - ``.index_at(i, j, ...)`` gets the count from the beginning to a given index.
195
+
196
+
197
+ There are also several methods for getting references (described below).
198
+
199
+ Structured types
200
+ ================
201
+
202
+ In order for ``py::array_t`` to work with structured (record) types, we first
203
+ need to register the memory layout of the type. This can be done via
204
+ ``PYBIND11_NUMPY_DTYPE`` macro, called in the plugin definition code, which
205
+ expects the type followed by field names:
206
+
207
+ .. code-block:: cpp
208
+
209
+ struct A {
210
+ int x;
211
+ double y;
212
+ };
213
+
214
+ struct B {
215
+ int z;
216
+ A a;
217
+ };
218
+
219
+ // ...
220
+ PYBIND11_MODULE(test, m, py::mod_gil_not_used()) {
221
+ // ...
222
+
223
+ PYBIND11_NUMPY_DTYPE(A, x, y);
224
+ PYBIND11_NUMPY_DTYPE(B, z, a);
225
+ /* now both A and B can be used as template arguments to py::array_t */
226
+ }
227
+
228
+ The structure should consist of fundamental arithmetic types, ``std::complex``,
229
+ previously registered substructures, and arrays of any of the above. Both C++
230
+ arrays and ``std::array`` are supported. While there is a static assertion to
231
+ prevent many types of unsupported structures, it is still the user's
232
+ responsibility to use only "plain" structures that can be safely manipulated as
233
+ raw memory without violating invariants.
234
+
235
+ Scalar types
236
+ ============
237
+
238
+ In some cases we may want to accept or return NumPy scalar values such as
239
+ ``np.float32`` or ``np.float64``. We hope to be able to handle single-precision
240
+ and double-precision on the C-side. However, both are bound to Python's
241
+ double-precision builtin float by default, so they cannot be processed separately.
242
+ We used the ``py::buffer`` trick to implement the previous approach, which
243
+ will cause the readability of the code to drop significantly.
244
+
245
+ Luckily, there's a helper type for this occasion - ``py::numpy_scalar``:
246
+
247
+ .. code-block:: cpp
248
+
249
+ m.def("add", [](py::numpy_scalar<float> a, py::numpy_scalar<float> b) {
250
+ return py::make_scalar(a + b);
251
+ });
252
+ m.def("add", [](py::numpy_scalar<double> a, py::numpy_scalar<double> b) {
253
+ return py::make_scalar(a + b);
254
+ });
255
+
256
+ This type is trivially convertible to and from the type it wraps; currently
257
+ supported scalar types are NumPy arithmetic types: ``bool_``, ``int8``,
258
+ ``int16``, ``int32``, ``int64``, ``uint8``, ``uint16``, ``uint32``,
259
+ ``uint64``, ``float32``, ``float64``, ``complex64``, ``complex128``, all of
260
+ them mapping to respective C++ counterparts.
261
+
262
+ .. note::
263
+
264
+ ``py::numpy_scalar<T>`` strictly matches NumPy scalar types. For example,
265
+ ``py::numpy_scalar<int64_t>`` will accept ``np.int64(123)``,
266
+ but **not** a regular Python ``int`` like ``123``.
267
+
268
+ .. note::
269
+
270
+ Native C types are mapped to NumPy types in a platform specific way: for
271
+ instance, ``char`` may be mapped to either ``np.int8`` or ``np.uint8``
272
+ and ``long`` may use 4 or 8 bytes depending on the platform. Unless you
273
+ clearly understand the difference and your needs, please use ``<cstdint>``.
274
+
275
+ Vectorizing functions
276
+ =====================
277
+
278
+ Suppose we want to bind a function with the following signature to Python so
279
+ that it can process arbitrary NumPy array arguments (vectors, matrices, general
280
+ N-D arrays) in addition to its normal arguments:
281
+
282
+ .. code-block:: cpp
283
+
284
+ double my_func(int x, float y, double z);
285
+
286
+ After including the ``pybind11/numpy.h`` header, this is extremely simple:
287
+
288
+ .. code-block:: cpp
289
+
290
+ m.def("vectorized_func", py::vectorize(my_func));
291
+
292
+ Invoking the function like below causes 4 calls to be made to ``my_func`` with
293
+ each of the array elements. The significant advantage of this compared to
294
+ solutions like ``numpy.vectorize()`` is that the loop over the elements runs
295
+ entirely on the C++ side and can be crunched down into a tight, optimized loop
296
+ by the compiler. The result is returned as a NumPy array of type
297
+ ``numpy.dtype.float64``.
298
+
299
+ .. code-block:: pycon
300
+
301
+ >>> x = np.array([[1, 3], [5, 7]])
302
+ >>> y = np.array([[2, 4], [6, 8]])
303
+ >>> z = 3
304
+ >>> result = vectorized_func(x, y, z)
305
+
306
+ The scalar argument ``z`` is transparently replicated 4 times. The input
307
+ arrays ``x`` and ``y`` are automatically converted into the right types (they
308
+ are of type ``numpy.dtype.int64`` but need to be ``numpy.dtype.int32`` and
309
+ ``numpy.dtype.float32``, respectively).
310
+
311
+ .. note::
312
+
313
+ Only arithmetic, complex, and POD types passed by value or by ``const &``
314
+ reference are vectorized; all other arguments are passed through as-is.
315
+ Functions taking rvalue reference arguments cannot be vectorized.
316
+
317
+ In cases where the computation is too complicated to be reduced to
318
+ ``vectorize``, it will be necessary to create and access the buffer contents
319
+ manually. The following snippet contains a complete example that shows how this
320
+ works (the code is somewhat contrived, since it could have been done more
321
+ simply using ``vectorize``).
322
+
323
+ .. code-block:: cpp
324
+
325
+ #include <pybind11/pybind11.h>
326
+ #include <pybind11/numpy.h>
327
+
328
+ namespace py = pybind11;
329
+
330
+ py::array_t<double> add_arrays(py::array_t<double> input1, py::array_t<double> input2) {
331
+ py::buffer_info buf1 = input1.request(), buf2 = input2.request();
332
+
333
+ if (buf1.ndim != 1 || buf2.ndim != 1)
334
+ throw std::runtime_error("Number of dimensions must be one");
335
+
336
+ if (buf1.size != buf2.size)
337
+ throw std::runtime_error("Input shapes must match");
338
+
339
+ /* No pointer is passed, so NumPy will allocate the buffer */
340
+ auto result = py::array_t<double>(buf1.size);
341
+
342
+ py::buffer_info buf3 = result.request();
343
+
344
+ double *ptr1 = static_cast<double *>(buf1.ptr);
345
+ double *ptr2 = static_cast<double *>(buf2.ptr);
346
+ double *ptr3 = static_cast<double *>(buf3.ptr);
347
+
348
+ for (size_t idx = 0; idx < buf1.shape[0]; idx++)
349
+ ptr3[idx] = ptr1[idx] + ptr2[idx];
350
+
351
+ return result;
352
+ }
353
+
354
+ PYBIND11_MODULE(test, m, py::mod_gil_not_used()) {
355
+ m.def("add_arrays", &add_arrays, "Add two NumPy arrays");
356
+ }
357
+
358
+ .. seealso::
359
+
360
+ The file :file:`tests/test_numpy_vectorize.cpp` contains a complete
361
+ example that demonstrates using :func:`vectorize` in more detail.
362
+
363
+ Direct access
364
+ =============
365
+
366
+ For performance reasons, particularly when dealing with very large arrays, it
367
+ is often desirable to directly access array elements without internal checking
368
+ of dimensions and bounds on every access when indices are known to be already
369
+ valid. To avoid such checks, the ``array`` class and ``array_t<T>`` template
370
+ class offer an unchecked proxy object that can be used for this unchecked
371
+ access through the ``unchecked<N>`` and ``mutable_unchecked<N>`` methods,
372
+ where ``N`` gives the required dimensionality of the array:
373
+
374
+ .. code-block:: cpp
375
+
376
+ m.def("sum_3d", [](py::array_t<double> x) {
377
+ auto r = x.unchecked<3>(); // x must have ndim = 3; can be non-writeable
378
+ double sum = 0;
379
+ for (py::ssize_t i = 0; i < r.shape(0); i++)
380
+ for (py::ssize_t j = 0; j < r.shape(1); j++)
381
+ for (py::ssize_t k = 0; k < r.shape(2); k++)
382
+ sum += r(i, j, k);
383
+ return sum;
384
+ });
385
+ m.def("increment_3d", [](py::array_t<double> x) {
386
+ auto r = x.mutable_unchecked<3>(); // Will throw if ndim != 3 or flags.writeable is false
387
+ for (py::ssize_t i = 0; i < r.shape(0); i++)
388
+ for (py::ssize_t j = 0; j < r.shape(1); j++)
389
+ for (py::ssize_t k = 0; k < r.shape(2); k++)
390
+ r(i, j, k) += 1.0;
391
+ }, py::arg().noconvert());
392
+
393
+ To obtain the proxy from an ``array`` object, you must specify both the data
394
+ type and number of dimensions as template arguments, such as ``auto r =
395
+ myarray.mutable_unchecked<float, 2>()``.
396
+
397
+ If the number of dimensions is not known at compile time, you can omit the
398
+ dimensions template parameter (i.e. calling ``arr_t.unchecked()`` or
399
+ ``arr.unchecked<T>()``. This will give you a proxy object that works in the
400
+ same way, but results in less optimizable code and thus a small efficiency
401
+ loss in tight loops.
402
+
403
+ Note that the returned proxy object directly references the array's data, and
404
+ only reads its shape, strides, and writeable flag when constructed. You must
405
+ take care to ensure that the referenced array is not destroyed or reshaped for
406
+ the duration of the returned object, typically by limiting the scope of the
407
+ returned instance.
408
+
409
+ The returned proxy object supports some of the same methods as ``py::array`` so
410
+ that it can be used as a drop-in replacement for some existing, index-checked
411
+ uses of ``py::array``:
412
+
413
+ - ``.ndim()`` returns the number of dimensions
414
+
415
+ - ``.data(1, 2, ...)`` and ``r.mutable_data(1, 2, ...)``` returns a pointer to
416
+ the ``const T`` or ``T`` data, respectively, at the given indices. The
417
+ latter is only available to proxies obtained via ``a.mutable_unchecked()``.
418
+
419
+ - ``.itemsize()`` returns the size of an item in bytes, i.e. ``sizeof(T)``.
420
+
421
+ - ``.shape(n)`` returns the size of dimension ``n``
422
+
423
+ - ``.size()`` returns the total number of elements (i.e. the product of the shapes).
424
+
425
+ - ``.nbytes()`` returns the number of bytes used by the referenced elements
426
+ (i.e. ``itemsize()`` times ``size()``).
427
+
428
+ .. seealso::
429
+
430
+ The file :file:`tests/test_numpy_array.cpp` contains additional examples
431
+ demonstrating the use of this feature.
432
+
433
+ Ellipsis
434
+ ========
435
+
436
+ Python provides a convenient ``...`` ellipsis notation that is often used to
437
+ slice multidimensional arrays. For instance, the following snippet extracts the
438
+ middle dimensions of a tensor with the first and last index set to zero.
439
+
440
+ .. code-block:: python
441
+
442
+ a = ... # a NumPy array
443
+ b = a[0, ..., 0]
444
+
445
+ The function ``py::ellipsis()`` function can be used to perform the same
446
+ operation on the C++ side:
447
+
448
+ .. code-block:: cpp
449
+
450
+ py::array a = /* A NumPy array */;
451
+ py::array b = a[py::make_tuple(0, py::ellipsis(), 0)];
452
+
453
+
454
+ Memory view
455
+ ===========
456
+
457
+ For a case when we simply want to provide a direct accessor to C/C++ buffer
458
+ without a concrete class object, we can return a ``memoryview`` object. Suppose
459
+ we wish to expose a ``memoryview`` for 2x4 uint8_t array, we can do the
460
+ following:
461
+
462
+ .. code-block:: cpp
463
+
464
+ const uint8_t buffer[] = {
465
+ 0, 1, 2, 3,
466
+ 4, 5, 6, 7
467
+ };
468
+ m.def("get_memoryview2d", []() {
469
+ return py::memoryview::from_buffer(
470
+ buffer, // buffer pointer
471
+ { 2, 4 }, // shape (rows, cols)
472
+ { sizeof(uint8_t) * 4, sizeof(uint8_t) } // strides in bytes
473
+ );
474
+ });
475
+
476
+ This approach is meant for providing a ``memoryview`` for a C/C++ buffer not
477
+ managed by Python. The user is responsible for managing the lifetime of the
478
+ buffer. Using a ``memoryview`` created in this way after deleting the buffer in
479
+ C++ side results in undefined behavior.
480
+
481
+ We can also use ``memoryview::from_memory`` for a simple 1D contiguous buffer:
482
+
483
+ .. code-block:: cpp
484
+
485
+ m.def("get_memoryview1d", []() {
486
+ return py::memoryview::from_memory(
487
+ buffer, // buffer pointer
488
+ sizeof(uint8_t) * 8 // buffer size
489
+ );
490
+ });
491
+
492
+ .. versionchanged:: 2.6
493
+ ``memoryview::from_memory`` added.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/pycpp/object.rst ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Python types
2
+ ############
3
+
4
+ .. _wrappers:
5
+
6
+ Available wrappers
7
+ ==================
8
+
9
+ All major Python types are available as thin C++ wrapper classes. These
10
+ can also be used as function parameters -- see :ref:`python_objects_as_args`.
11
+
12
+ Available types include :class:`handle`, :class:`object`, :class:`bool_`,
13
+ :class:`int_`, :class:`float_`, :class:`str`, :class:`bytes`, :class:`tuple`,
14
+ :class:`list`, :class:`dict`, :class:`slice`, :class:`none`, :class:`capsule`,
15
+ :class:`iterable`, :class:`iterator`, :class:`function`, :class:`buffer`,
16
+ :class:`array`, and :class:`array_t`.
17
+
18
+ .. warning::
19
+
20
+ Be sure to review the :ref:`pytypes_gotchas` before using this heavily in
21
+ your C++ API.
22
+
23
+ .. _instantiating_compound_types:
24
+
25
+ Instantiating compound Python types from C++
26
+ ============================================
27
+
28
+ Dictionaries can be initialized in the :class:`dict` constructor:
29
+
30
+ .. code-block:: cpp
31
+
32
+ using namespace pybind11::literals; // to bring in the `_a` literal
33
+ py::dict d("spam"_a=py::none(), "eggs"_a=42);
34
+
35
+ A tuple of python objects can be instantiated using :func:`py::make_tuple`:
36
+
37
+ .. code-block:: cpp
38
+
39
+ py::tuple tup = py::make_tuple(42, py::none(), "spam");
40
+
41
+ Each element is converted to a supported Python type.
42
+
43
+ A `simple namespace`_ can be instantiated using
44
+
45
+ .. code-block:: cpp
46
+
47
+ using namespace pybind11::literals; // to bring in the `_a` literal
48
+ py::object SimpleNamespace = py::module_::import("types").attr("SimpleNamespace");
49
+ py::object ns = SimpleNamespace("spam"_a=py::none(), "eggs"_a=42);
50
+
51
+ Attributes on a namespace can be modified with the :func:`py::delattr`,
52
+ :func:`py::getattr`, and :func:`py::setattr` functions. Simple namespaces can
53
+ be useful as lightweight stand-ins for class instances.
54
+
55
+ .. _simple namespace: https://docs.python.org/3/library/types.html#types.SimpleNamespace
56
+
57
+ .. _casting_back_and_forth:
58
+
59
+ Casting back and forth
60
+ ======================
61
+
62
+ In this kind of mixed code, it is often necessary to convert arbitrary C++
63
+ types to Python, which can be done using :func:`py::cast`:
64
+
65
+ .. code-block:: cpp
66
+
67
+ MyClass *cls = ...;
68
+ py::object obj = py::cast(cls);
69
+
70
+ The reverse direction uses the following syntax:
71
+
72
+ .. code-block:: cpp
73
+
74
+ py::object obj = ...;
75
+ MyClass *cls = obj.cast<MyClass *>();
76
+
77
+ When conversion fails, both directions throw the exception :class:`cast_error`.
78
+
79
+ .. _python_libs:
80
+
81
+ Accessing Python libraries from C++
82
+ ===================================
83
+
84
+ It is also possible to import objects defined in the Python standard
85
+ library or available in the current Python environment (``sys.path``) and work
86
+ with these in C++.
87
+
88
+ This example obtains a reference to the Python ``Decimal`` class.
89
+
90
+ .. code-block:: cpp
91
+
92
+ // Equivalent to "from decimal import Decimal"
93
+ py::object Decimal = py::module_::import("decimal").attr("Decimal");
94
+
95
+ .. code-block:: cpp
96
+
97
+ // Try to import scipy
98
+ py::object scipy = py::module_::import("scipy");
99
+ return scipy.attr("__version__");
100
+
101
+
102
+ .. _calling_python_functions:
103
+
104
+ Calling Python functions
105
+ ========================
106
+
107
+ It is also possible to call Python classes, functions and methods
108
+ via ``operator()``.
109
+
110
+ .. code-block:: cpp
111
+
112
+ // Construct a Python object of class Decimal
113
+ py::object pi = Decimal("3.14159");
114
+
115
+ .. code-block:: cpp
116
+
117
+ // Use Python to make our directories
118
+ py::object os = py::module_::import("os");
119
+ py::object makedirs = os.attr("makedirs");
120
+ makedirs("/tmp/path/to/somewhere");
121
+
122
+ One can convert the result obtained from Python to a pure C++ version
123
+ if a ``py::class_`` or type conversion is defined.
124
+
125
+ .. code-block:: cpp
126
+
127
+ py::function f = <...>;
128
+ py::object result_py = f(1234, "hello", some_instance);
129
+ MyClass &result = result_py.cast<MyClass>();
130
+
131
+ .. _calling_python_methods:
132
+
133
+ Calling Python methods
134
+ ========================
135
+
136
+ To call an object's method, one can again use ``.attr`` to obtain access to the
137
+ Python method.
138
+
139
+ .. code-block:: cpp
140
+
141
+ // Calculate e^π in decimal
142
+ py::object exp_pi = pi.attr("exp")();
143
+ py::print(py::str(exp_pi));
144
+
145
+ In the example above ``pi.attr("exp")`` is a *bound method*: it will always call
146
+ the method for that same instance of the class. Alternately one can create an
147
+ *unbound method* via the Python class (instead of instance) and pass the ``self``
148
+ object explicitly, followed by other arguments.
149
+
150
+ .. code-block:: cpp
151
+
152
+ py::object decimal_exp = Decimal.attr("exp");
153
+
154
+ // Compute the e^n for n=0..4
155
+ for (int n = 0; n < 5; n++) {
156
+ py::print(decimal_exp(Decimal(n));
157
+ }
158
+
159
+ Keyword arguments
160
+ =================
161
+
162
+ Keyword arguments are also supported. In Python, there is the usual call syntax:
163
+
164
+ .. code-block:: python
165
+
166
+ def f(number, say, to):
167
+ ... # function code
168
+
169
+
170
+ f(1234, say="hello", to=some_instance) # keyword call in Python
171
+
172
+ In C++, the same call can be made using:
173
+
174
+ .. code-block:: cpp
175
+
176
+ using namespace pybind11::literals; // to bring in the `_a` literal
177
+ f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
178
+
179
+ Unpacking arguments
180
+ ===================
181
+
182
+ Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with
183
+ other arguments:
184
+
185
+ .. code-block:: cpp
186
+
187
+ // * unpacking
188
+ py::tuple args = py::make_tuple(1234, "hello", some_instance);
189
+ f(*args);
190
+
191
+ // ** unpacking
192
+ py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance);
193
+ f(**kwargs);
194
+
195
+ // mixed keywords, * and ** unpacking
196
+ py::tuple args = py::make_tuple(1234);
197
+ py::dict kwargs = py::dict("to"_a=some_instance);
198
+ f(*args, "say"_a="hello", **kwargs);
199
+
200
+ Generalized unpacking according to PEP448_ is also supported:
201
+
202
+ .. code-block:: cpp
203
+
204
+ py::dict kwargs1 = py::dict("number"_a=1234);
205
+ py::dict kwargs2 = py::dict("to"_a=some_instance);
206
+ f(**kwargs1, "say"_a="hello", **kwargs2);
207
+
208
+ .. seealso::
209
+
210
+ The file :file:`tests/test_pytypes.cpp` contains a complete
211
+ example that demonstrates passing native Python types in more detail. The
212
+ file :file:`tests/test_callbacks.cpp` presents a few examples of calling
213
+ Python functions from C++, including keywords arguments and unpacking.
214
+
215
+ .. _PEP448: https://www.python.org/dev/peps/pep-0448/
216
+
217
+ .. _implicit_casting:
218
+
219
+ Implicit casting
220
+ ================
221
+
222
+ When using the C++ interface for Python types, or calling Python functions,
223
+ objects of type :class:`object` are returned. It is possible to invoke implicit
224
+ conversions to subclasses like :class:`dict`. The same holds for the proxy objects
225
+ returned by ``operator[]`` or ``obj.attr()``.
226
+ Casting to subtypes improves code readability and allows values to be passed to
227
+ C++ functions that require a specific subtype rather than a generic :class:`object`.
228
+
229
+ .. code-block:: cpp
230
+
231
+ #include <pybind11/numpy.h>
232
+ using namespace pybind11::literals;
233
+
234
+ py::module_ os = py::module_::import("os");
235
+ py::module_ path = py::module_::import("os.path"); // like 'import os.path as path'
236
+ py::module_ np = py::module_::import("numpy"); // like 'import numpy as np'
237
+
238
+ py::str curdir_abs = path.attr("abspath")(path.attr("curdir"));
239
+ py::print(py::str("Current directory: ") + curdir_abs);
240
+ py::dict environ = os.attr("environ");
241
+ py::print(environ["HOME"]);
242
+ py::array_t<float> arr = np.attr("ones")(3, "dtype"_a="float32");
243
+ py::print(py::repr(arr + py::int_(1)));
244
+
245
+ These implicit conversions are available for subclasses of :class:`object`; there
246
+ is no need to call ``obj.cast()`` explicitly as for custom classes, see
247
+ :ref:`casting_back_and_forth`.
248
+
249
+ .. note::
250
+ If a trivial conversion via move constructor is not possible, both implicit and
251
+ explicit casting (calling ``obj.cast()``) will attempt a "rich" conversion.
252
+ For instance, ``py::list env = os.attr("environ");`` will succeed and is
253
+ equivalent to the Python code ``env = list(os.environ)`` that produces a
254
+ list of the dict keys.
255
+
256
+ .. TODO: Adapt text once PR #2349 has landed
257
+
258
+ Handling exceptions
259
+ ===================
260
+
261
+ Python exceptions from wrapper classes will be thrown as a ``py::error_already_set``.
262
+ See :ref:`Handling exceptions from Python in C++
263
+ <handling_python_exceptions_cpp>` for more information on handling exceptions
264
+ raised when calling C++ wrapper classes.
265
+
266
+ .. _pytypes_gotchas:
267
+
268
+ Gotchas
269
+ =======
270
+
271
+ Default-Constructed Wrappers
272
+ ----------------------------
273
+
274
+ When a wrapper type is default-constructed, it is **not** a valid Python object (i.e. it is not ``py::none()``). It is simply the same as
275
+ ``PyObject*`` null pointer. To check for this, use
276
+ ``static_cast<bool>(my_wrapper)``.
277
+
278
+ Assigning py::none() to wrappers
279
+ --------------------------------
280
+
281
+ You may be tempted to use types like ``py::str`` and ``py::dict`` in C++
282
+ signatures (either pure C++, or in bound signatures), and assign them default
283
+ values of ``py::none()``. However, in a best case scenario, it will fail fast
284
+ because ``None`` is not convertible to that type (e.g. ``py::dict``), or in a
285
+ worse case scenario, it will silently work but corrupt the types you want to
286
+ work with (e.g. ``py::str(py::none())`` will yield ``"None"`` in Python).
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/pycpp/utilities.rst ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Utilities
2
+ #########
3
+
4
+ Using Python's print function in C++
5
+ ====================================
6
+
7
+ The usual way to write output in C++ is using ``std::cout`` while in Python one
8
+ would use ``print``. Since these methods use different buffers, mixing them can
9
+ lead to output order issues. To resolve this, pybind11 modules can use the
10
+ :func:`py::print` function which writes to Python's ``sys.stdout`` for consistency.
11
+
12
+ Python's ``print`` function is replicated in the C++ API including optional
13
+ keyword arguments ``sep``, ``end``, ``file``, ``flush``. Everything works as
14
+ expected in Python:
15
+
16
+ .. code-block:: cpp
17
+
18
+ py::print(1, 2.0, "three"); // 1 2.0 three
19
+ py::print(1, 2.0, "three", "sep"_a="-"); // 1-2.0-three
20
+
21
+ auto args = py::make_tuple("unpacked", true);
22
+ py::print("->", *args, "end"_a="<-"); // -> unpacked True <-
23
+
24
+ .. _ostream_redirect:
25
+
26
+ Capturing standard output from ostream
27
+ ======================================
28
+
29
+ Often, a library will use the streams ``std::cout`` and ``std::cerr`` to print,
30
+ but this does not play well with Python's standard ``sys.stdout`` and ``sys.stderr``
31
+ redirection. Replacing a library's printing with ``py::print <print>`` may not
32
+ be feasible. This can be fixed using a guard around the library function that
33
+ redirects output to the corresponding Python streams:
34
+
35
+ .. code-block:: cpp
36
+
37
+ #include <pybind11/iostream.h>
38
+
39
+ ...
40
+
41
+ // Add a scoped redirect for your noisy code
42
+ m.def("noisy_func", []() {
43
+ py::scoped_ostream_redirect stream(
44
+ std::cout, // std::ostream&
45
+ py::module_::import("sys").attr("stdout") // Python output
46
+ );
47
+ call_noisy_func();
48
+ });
49
+
50
+ .. warning::
51
+
52
+ The implementation in ``pybind11/iostream.h`` is NOT thread safe. Multiple
53
+ threads writing to a redirected ostream concurrently cause data races
54
+ and potentially buffer overflows. Therefore it is currently a requirement
55
+ that all (possibly) concurrent redirected ostream writes are protected by
56
+ a mutex. #HelpAppreciated: Work on iostream.h thread safety. For more
57
+ background see the discussions under
58
+ `PR #2982 <https://github.com/pybind/pybind11/pull/2982>`_ and
59
+ `PR #2995 <https://github.com/pybind/pybind11/pull/2995>`_.
60
+
61
+ This method respects flushes on the output streams and will flush if needed
62
+ when the scoped guard is destroyed. This allows the output to be redirected in
63
+ real time, such as to a Jupyter notebook. The two arguments, the C++ stream and
64
+ the Python output, are optional, and default to standard output if not given. An
65
+ extra type, ``py::scoped_estream_redirect <scoped_estream_redirect>``, is identical
66
+ except for defaulting to ``std::cerr`` and ``sys.stderr``; this can be useful with
67
+ ``py::call_guard``, which allows multiple items, but uses the default constructor:
68
+
69
+ .. code-block:: cpp
70
+
71
+ // Alternative: Call single function using call guard
72
+ m.def("noisy_func", &call_noisy_function,
73
+ py::call_guard<py::scoped_ostream_redirect,
74
+ py::scoped_estream_redirect>());
75
+
76
+ The redirection can also be done in Python with the addition of a context
77
+ manager, using the ``py::add_ostream_redirect() <add_ostream_redirect>`` function:
78
+
79
+ .. code-block:: cpp
80
+
81
+ py::add_ostream_redirect(m, "ostream_redirect");
82
+
83
+ The name in Python defaults to ``ostream_redirect`` if no name is passed. This
84
+ creates the following context manager in Python:
85
+
86
+ .. code-block:: python
87
+
88
+ with ostream_redirect(stdout=True, stderr=True):
89
+ noisy_function()
90
+
91
+ It defaults to redirecting both streams, though you can use the keyword
92
+ arguments to disable one of the streams if needed.
93
+
94
+ .. note::
95
+
96
+ The above methods will not redirect C-level output to file descriptors, such
97
+ as ``fprintf``. For those cases, you'll need to redirect the file
98
+ descriptors either directly in C or with Python's ``os.dup2`` function
99
+ in an operating-system dependent way.
100
+
101
+ .. _eval:
102
+
103
+ Evaluating Python expressions from strings and files
104
+ ====================================================
105
+
106
+ pybind11 provides the ``eval``, ``exec`` and ``eval_file`` functions to evaluate
107
+ Python expressions and statements. The following example illustrates how they
108
+ can be used.
109
+
110
+ .. code-block:: cpp
111
+
112
+ // At beginning of file
113
+ #include <pybind11/eval.h>
114
+
115
+ ...
116
+
117
+ // Evaluate in scope of main module
118
+ py::object scope = py::module_::import("__main__").attr("__dict__");
119
+
120
+ // Evaluate an isolated expression
121
+ int result = py::eval("my_variable + 10", scope).cast<int>();
122
+
123
+ // Evaluate a sequence of statements
124
+ py::exec(
125
+ "print('Hello')\n"
126
+ "print('world!');",
127
+ scope);
128
+
129
+ // Evaluate the statements in an separate Python file on disk
130
+ py::eval_file("script.py", scope);
131
+
132
+ C++11 raw string literals are also supported and quite handy for this purpose.
133
+ The only requirement is that the first statement must be on a new line following
134
+ the raw string delimiter ``R"(``, ensuring all lines have common leading indent:
135
+
136
+ .. code-block:: cpp
137
+
138
+ py::exec(R"(
139
+ x = get_answer()
140
+ if x == 42:
141
+ print('Hello World!')
142
+ else:
143
+ print('Bye!')
144
+ )", scope
145
+ );
146
+
147
+ .. note::
148
+
149
+ `eval` and `eval_file` accept a template parameter that describes how the
150
+ string/file should be interpreted. Possible choices include ``eval_expr``
151
+ (isolated expression), ``eval_single_statement`` (a single statement, return
152
+ value is always ``none``), and ``eval_statements`` (sequence of statements,
153
+ return value is always ``none``). `eval` defaults to ``eval_expr``,
154
+ `eval_file` defaults to ``eval_statements`` and `exec` is just a shortcut
155
+ for ``eval<eval_statements>``.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/advanced/smart_ptrs.rst ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _py_class_holder:
2
+
3
+ Smart pointers & ``py::class_``
4
+ ###############################
5
+
6
+ The binding generator for classes, ``py::class_``, can be passed a template
7
+ type that denotes a special *holder* type that is used to manage references to
8
+ the object. If no such holder type template argument is given, the default for
9
+ a type ``T`` is ``std::unique_ptr<T>``.
10
+
11
+ .. note::
12
+
13
+ A ``py::class_`` for a given C++ type ``T`` — and all its derived types —
14
+ can only use a single holder type.
15
+
16
+
17
+ .. _smart_holder:
18
+
19
+ ``py::smart_holder``
20
+ ====================
21
+
22
+ Starting with pybind11v3, ``py::smart_holder`` is built into pybind11. It is
23
+ the recommended ``py::class_`` holder for most situations. However, for
24
+ backward compatibility it is **not** the default holder, and there are no
25
+ plans to make it the default holder in the future.
26
+
27
+ It is extremely easy to use the safer and more versatile ``py::smart_holder``:
28
+ simply add ``py::smart_holder`` to ``py::class_``:
29
+
30
+ * ``py::class_<T>`` to
31
+
32
+ * ``py::class_<T, py::smart_holder>``.
33
+
34
+ .. note::
35
+
36
+ A shorthand, ``py::classh<T>``, is provided for
37
+ ``py::class_<T, py::smart_holder>``. The ``h`` in ``py::classh`` stands
38
+ for **smart_holder** but is shortened for brevity, ensuring it has the
39
+ same number of characters as ``py::class_``. This design choice facilitates
40
+ easy experimentation with ``py::smart_holder`` without introducing
41
+ distracting whitespace noise in diffs.
42
+
43
+ The ``py::smart_holder`` functionality includes the following:
44
+
45
+ * Support for **two-way** Python/C++ conversions for both
46
+ ``std::unique_ptr<T>`` and ``std::shared_ptr<T>`` **simultaneously**.
47
+
48
+ * Passing a Python object back to C++ via ``std::unique_ptr<T>``, safely
49
+ **disowning** the Python object.
50
+
51
+ * Safely passing "trampoline" objects (objects with C++ virtual function
52
+ overrides implemented in Python, see :ref:`overriding_virtuals`) via
53
+ ``std::unique_ptr<T>`` or ``std::shared_ptr<T>`` back to C++:
54
+ associated Python objects are automatically kept alive for the lifetime
55
+ of the smart-pointer.
56
+
57
+ * Full support for ``std::enable_shared_from_this`` (`cppreference
58
+ <http://en.cppreference.com/w/cpp/memory/enable_shared_from_this>`_).
59
+
60
+
61
+ ``std::unique_ptr``
62
+ ===================
63
+
64
+ This is the default ``py::class_`` holder and works as expected in
65
+ most situations. However, handling base-and-derived classes involves a
66
+ ``reinterpret_cast``, which is, strictly speaking, undefined behavior.
67
+ Also note that the ``std::unique_ptr`` holder only supports passing a
68
+ ``std::unique_ptr`` from C++ to Python, but not the other way around.
69
+ For example, the following code works as expected with ``py::class_<Example>``:
70
+
71
+ .. code-block:: cpp
72
+
73
+ std::unique_ptr<Example> create_example() { return std::unique_ptr<Example>(new Example()); }
74
+
75
+ .. code-block:: cpp
76
+
77
+ m.def("create_example", &create_example);
78
+
79
+ However, this will fail with ``py::class_<Example>`` (but works with
80
+ ``py::class_<Example, py::smart_holder>``):
81
+
82
+ .. code-block:: cpp
83
+
84
+ void do_something_with_example(std::unique_ptr<Example> ex) { ... }
85
+
86
+ .. note::
87
+
88
+ The ``reinterpret_cast`` mentioned above is `here
89
+ <https://github.com/pybind/pybind11/blob/30eb39ed79d1e2eeff15219ac00773034300a5e6/include/pybind11/cast.h#L235>`_.
90
+ For completeness: The same cast is also applied to ``py::smart_holder``,
91
+ but that is safe, because ``py::smart_holder`` is not templated.
92
+
93
+
94
+ ``std::shared_ptr``
95
+ ===================
96
+
97
+ It is possible to use ``std::shared_ptr`` as the holder, for example:
98
+
99
+ .. code-block:: cpp
100
+
101
+ py::class_<Example, std::shared_ptr<Example> /* <- holder type */>(m, "Example");
102
+
103
+ Compared to using ``py::class_<Example, py::smart_holder>``, there are two noteworthy disadvantages:
104
+
105
+ * Because a ``py::class_`` for a given C++ type ``T`` can only use a
106
+ single holder type, ``std::unique_ptr<T>`` cannot even be passed from C++
107
+ to Python. This will become apparent only at runtime, often through a
108
+ segmentation fault.
109
+
110
+ * Similar to the ``std::unique_ptr`` holder, the handling of base-and-derived
111
+ classes involves a ``reinterpret_cast`` that has strictly speaking undefined
112
+ behavior, although it works as expected in most situations.
113
+
114
+
115
+ .. _smart_pointers:
116
+
117
+ Custom smart pointers
118
+ =====================
119
+
120
+ For custom smart pointers (e.g. ``c10::intrusive_ptr`` in pytorch), transparent
121
+ conversions can be enabled using a macro invocation similar to the following.
122
+ It must be declared at the top namespace level before any binding code:
123
+
124
+ .. code-block:: cpp
125
+
126
+ PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>)
127
+
128
+ The first argument of :func:`PYBIND11_DECLARE_HOLDER_TYPE` should be a
129
+ placeholder name that is used as a template parameter of the second argument.
130
+ Thus, feel free to use any identifier, but use it consistently on both sides;
131
+ also, don't use the name of a type that already exists in your codebase.
132
+
133
+ The macro also accepts a third optional boolean parameter that is set to false
134
+ by default. Specify
135
+
136
+ .. code-block:: cpp
137
+
138
+ PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>, true)
139
+
140
+ if ``SmartPtr<T>`` can always be initialized from a ``T*`` pointer without the
141
+ risk of inconsistencies (such as multiple independent ``SmartPtr`` instances
142
+ believing that they are the sole owner of the ``T*`` pointer). A common
143
+ situation where ``true`` should be passed is when the ``T`` instances use
144
+ *intrusive* reference counting.
145
+
146
+ Please take a look at the :ref:`macro_notes` before using this feature.
147
+
148
+ By default, pybind11 assumes that your custom smart pointer has a standard
149
+ interface, i.e. provides a ``.get()`` member function to access the underlying
150
+ raw pointer. If this is not the case, pybind11's ``holder_helper`` must be
151
+ specialized:
152
+
153
+ .. code-block:: cpp
154
+
155
+ // Always needed for custom holder types
156
+ PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>)
157
+
158
+ // Only needed if the type's `.get()` goes by another name
159
+ namespace PYBIND11_NAMESPACE { namespace detail {
160
+ template <typename T>
161
+ struct holder_helper<SmartPtr<T>> { // <-- specialization
162
+ static const T *get(const SmartPtr<T> &p) { return p.getPointer(); }
163
+ };
164
+ }}
165
+
166
+ The above specialization informs pybind11 that the custom ``SmartPtr`` class
167
+ provides ``.get()`` functionality via ``.getPointer()``.
168
+
169
+ .. note::
170
+
171
+ The two noteworthy disadvantages mentioned under the ``std::shared_ptr``
172
+ section apply similarly to custom smart pointer holders, but there is no
173
+ established safe alternative in this case.
174
+
175
+ .. seealso::
176
+
177
+ The file :file:`tests/test_smart_ptr.cpp` contains a complete example
178
+ that demonstrates how to work with custom reference-counting holder types
179
+ in more detail.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/basics.rst ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _basics:
2
+
3
+ First steps
4
+ ###########
5
+
6
+ This sections demonstrates the basic features of pybind11. Before getting
7
+ started, make sure that development environment is set up to compile the
8
+ included set of test cases.
9
+
10
+
11
+ Compiling the test cases
12
+ ========================
13
+
14
+ Linux/macOS
15
+ -----------
16
+
17
+ On Linux you'll need to install the **python-dev** or **python3-dev** packages as
18
+ well as **cmake**. On macOS, the included python version works out of the box,
19
+ but **cmake** must still be installed.
20
+
21
+ After installing the prerequisites, run
22
+
23
+ .. code-block:: bash
24
+
25
+ mkdir build
26
+ cd build
27
+ cmake ..
28
+ make check -j 4
29
+
30
+ The last line will both compile and run the tests.
31
+
32
+ Windows
33
+ -------
34
+
35
+ On Windows, only **Visual Studio 2017** and newer are supported.
36
+
37
+ .. Note::
38
+
39
+ To use the C++17 in Visual Studio 2017 (MSVC 14.1), pybind11 requires the flag
40
+ ``/permissive-`` to be passed to the compiler `to enforce standard conformance`_. When
41
+ building with Visual Studio 2019, this is not strictly necessary, but still advised.
42
+
43
+ .. _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017
44
+
45
+ To compile and run the tests:
46
+
47
+ .. code-block:: batch
48
+
49
+ mkdir build
50
+ cd build
51
+ cmake ..
52
+ cmake --build . --config Release --target check
53
+
54
+ This will create a Visual Studio project, compile and run the target, all from the
55
+ command line.
56
+
57
+ .. Note::
58
+
59
+ If all tests fail, make sure that the Python binary and the testcases are compiled
60
+ for the same processor type and bitness (i.e. either **i386** or **x86_64**). You
61
+ can specify **x86_64** as the target architecture for the generated Visual Studio
62
+ project using ``cmake -A x64 ..``.
63
+
64
+ .. seealso::
65
+
66
+ Advanced users who are already familiar with Boost.Python may want to skip
67
+ the tutorial and look at the test cases in the :file:`tests` directory,
68
+ which exercise all features of pybind11.
69
+
70
+ Header and namespace conventions
71
+ ================================
72
+
73
+ For brevity, all code examples assume that the following two lines are present:
74
+
75
+ .. code-block:: cpp
76
+
77
+ #include <pybind11/pybind11.h>
78
+
79
+ namespace py = pybind11;
80
+
81
+ .. note::
82
+
83
+ ``pybind11/pybind11.h`` includes ``Python.h``, as such it must be the first file
84
+ included in any source file or header for `the same reasons as Python.h`_.
85
+
86
+ .. _`the same reasons as Python.h`: https://docs.python.org/3/extending/extending.html#a-simple-example
87
+
88
+ Some features may require additional headers, but those will be specified as needed.
89
+
90
+ .. _simple_example:
91
+
92
+ Creating bindings for a simple function
93
+ =======================================
94
+
95
+ Let's start by creating Python bindings for an extremely simple function, which
96
+ adds two numbers and returns their result:
97
+
98
+ .. code-block:: cpp
99
+
100
+ int add(int i, int j) {
101
+ return i + j;
102
+ }
103
+
104
+ For simplicity [#f1]_, we'll put both this function and the binding code into
105
+ a file named :file:`example.cpp` with the following contents:
106
+
107
+ .. code-block:: cpp
108
+
109
+ #include <pybind11/pybind11.h>
110
+
111
+ namespace py = pybind11;
112
+
113
+ int add(int i, int j) {
114
+ return i + j;
115
+ }
116
+
117
+ PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {
118
+ m.doc() = "pybind11 example plugin"; // optional module docstring
119
+
120
+ m.def("add", &add, "A function that adds two numbers");
121
+ }
122
+
123
+ .. [#f1] In practice, implementation and binding code will generally be located
124
+ in separate files.
125
+
126
+ The :func:`PYBIND11_MODULE` macro creates a function that will be called when an
127
+ ``import`` statement is issued from within Python. The module name (``example``)
128
+ is given as the first macro argument (it should not be in quotes). The second
129
+ argument (``m``) defines a variable of type :class:`py::module_ <module>` which
130
+ is the main interface for creating bindings. The method :func:`module_::def`
131
+ generates binding code that exposes the ``add()`` function to Python.
132
+
133
+ .. note::
134
+
135
+ Notice how little code was needed to expose our function to Python: all
136
+ details regarding the function's parameters and return value were
137
+ automatically inferred using template metaprogramming. This overall
138
+ approach and the used syntax are borrowed from Boost.Python, though the
139
+ underlying implementation is very different.
140
+
141
+ pybind11 is a header-only library, hence it is not necessary to link against
142
+ any special libraries and there are no intermediate (magic) translation steps.
143
+ On Linux, the above example can be compiled using the following command:
144
+
145
+ .. code-block:: bash
146
+
147
+ $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3 -m pybind11 --extension-suffix)
148
+
149
+ .. note::
150
+
151
+ If you used :ref:`include_as_a_submodule` to get the pybind11 source, then
152
+ use ``$(python3-config --includes) -Iextern/pybind11/include`` instead of
153
+ ``$(python3 -m pybind11 --includes)`` in the above compilation, as
154
+ explained in :ref:`building_manually`.
155
+
156
+ For more details on the required compiler flags on Linux and macOS, see
157
+ :ref:`building_manually`. For complete cross-platform compilation instructions,
158
+ refer to the :ref:`compiling` page.
159
+
160
+ The `python_example`_ and `cmake_example`_ repositories are also a good place
161
+ to start. They are both complete project examples with cross-platform build
162
+ systems. The only difference between the two is that `python_example`_ uses
163
+ Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake
164
+ (which may be preferable for existing C++ projects).
165
+
166
+ .. _python_example: https://github.com/pybind/python_example
167
+ .. _cmake_example: https://github.com/pybind/cmake_example
168
+
169
+ Building the above C++ code will produce a binary module file that can be
170
+ imported to Python. Assuming that the compiled module is located in the
171
+ current directory, the following interactive Python session shows how to
172
+ load and execute the example:
173
+
174
+ .. code-block:: pycon
175
+
176
+ $ python
177
+ Python 3.9.10 (main, Jan 15 2022, 11:48:04)
178
+ [Clang 13.0.0 (clang-1300.0.29.3)] on darwin
179
+ Type "help", "copyright", "credits" or "license" for more information.
180
+ >>> import example
181
+ >>> example.add(1, 2)
182
+ 3
183
+ >>>
184
+
185
+ .. _keyword_args:
186
+
187
+ Keyword arguments
188
+ =================
189
+
190
+ With a simple code modification, it is possible to inform Python about the
191
+ names of the arguments ("i" and "j" in this case).
192
+
193
+ .. code-block:: cpp
194
+
195
+ m.def("add", &add, "A function which adds two numbers",
196
+ py::arg("i"), py::arg("j"));
197
+
198
+ :class:`arg` is one of several special tag classes which can be used to pass
199
+ metadata into :func:`module_::def`. With this modified binding code, we can now
200
+ call the function using keyword arguments, which is a more readable alternative
201
+ particularly for functions taking many parameters:
202
+
203
+ .. code-block:: pycon
204
+
205
+ >>> import example
206
+ >>> example.add(i=1, j=2)
207
+ 3L
208
+
209
+ The keyword names also appear in the function signatures within the documentation.
210
+
211
+ .. code-block:: pycon
212
+
213
+ >>> help(example)
214
+
215
+ ....
216
+
217
+ FUNCTIONS
218
+ add(...)
219
+ Signature : (i: int, j: int) -> int
220
+
221
+ A function which adds two numbers
222
+
223
+ A shorter notation for named arguments is also available:
224
+
225
+ .. code-block:: cpp
226
+
227
+ // regular notation
228
+ m.def("add1", &add, py::arg("i"), py::arg("j"));
229
+ // shorthand
230
+ using namespace pybind11::literals;
231
+ m.def("add2", &add, "i"_a, "j"_a);
232
+
233
+ The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
234
+ Note that the literal operator must first be made visible with the directive
235
+ ``using namespace pybind11::literals``. This does not bring in anything else
236
+ from the ``pybind11`` namespace except for literals.
237
+
238
+ .. _default_args:
239
+
240
+ Default arguments
241
+ =================
242
+
243
+ Suppose now that the function to be bound has default arguments, e.g.:
244
+
245
+ .. code-block:: cpp
246
+
247
+ int add(int i = 1, int j = 2) {
248
+ return i + j;
249
+ }
250
+
251
+ Unfortunately, pybind11 cannot automatically extract these parameters, since they
252
+ are not part of the function's type information. However, they are simple to specify
253
+ using an extension of :class:`arg`:
254
+
255
+ .. code-block:: cpp
256
+
257
+ m.def("add", &add, "A function which adds two numbers",
258
+ py::arg("i") = 1, py::arg("j") = 2);
259
+
260
+ The default values also appear within the documentation.
261
+
262
+ .. code-block:: pycon
263
+
264
+ >>> help(example)
265
+
266
+ ....
267
+
268
+ FUNCTIONS
269
+ add(...)
270
+ Signature : (i: int = 1, j: int = 2) -> int
271
+
272
+ A function which adds two numbers
273
+
274
+ The shorthand notation is also available for default arguments:
275
+
276
+ .. code-block:: cpp
277
+
278
+ // regular notation
279
+ m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
280
+ // shorthand
281
+ m.def("add2", &add, "i"_a=1, "j"_a=2);
282
+
283
+ Exporting variables
284
+ ===================
285
+
286
+ To expose a value from C++, use the ``attr`` function to register it in a
287
+ module as shown below. Built-in types and general objects (more on that later)
288
+ are automatically converted when assigned as attributes, and can be explicitly
289
+ converted using the function ``py::cast``.
290
+
291
+ .. code-block:: cpp
292
+
293
+ PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {
294
+ m.attr("the_answer") = 42;
295
+ py::object world = py::cast("World");
296
+ m.attr("what") = world;
297
+ }
298
+
299
+ These are then accessible from Python:
300
+
301
+ .. code-block:: pycon
302
+
303
+ >>> import example
304
+ >>> example.the_answer
305
+ 42
306
+ >>> example.what
307
+ 'World'
308
+
309
+ .. _supported_types:
310
+
311
+ Supported data types
312
+ ====================
313
+
314
+ A large number of data types are supported out of the box and can be used
315
+ seamlessly as functions arguments, return values or with ``py::cast`` in general.
316
+ For a full overview, see the :doc:`advanced/cast/index` section.
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/benchmark.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import datetime as dt
4
+ import os
5
+ import random
6
+
7
+ nfns = 4 # Functions per class
8
+ nargs = 4 # Arguments per function
9
+
10
+
11
+ def generate_dummy_code_pybind11(nclasses=10):
12
+ decl = ""
13
+ bindings = ""
14
+
15
+ for cl in range(nclasses):
16
+ decl += f"class cl{cl:03};\n"
17
+ decl += "\n"
18
+
19
+ for cl in range(nclasses):
20
+ decl += f"class {cl:03} {{\n"
21
+ decl += "public:\n"
22
+ bindings += f' py::class_<cl{cl:03}>(m, "cl{cl:03}")\n'
23
+ for fn in range(nfns):
24
+ ret = random.randint(0, nclasses - 1)
25
+ params = [random.randint(0, nclasses - 1) for i in range(nargs)]
26
+ decl += f" cl{ret:03} *fn_{fn:03}("
27
+ decl += ", ".join(f"cl{p:03} *" for p in params)
28
+ decl += ");\n"
29
+ bindings += f' .def("fn_{fn:03}", &cl{cl:03}::fn_{fn:03})\n'
30
+ decl += "};\n\n"
31
+ bindings += " ;\n"
32
+
33
+ result = "#include <pybind11/pybind11.h>\n\n"
34
+ result += "namespace py = pybind11;\n\n"
35
+ result += decl + "\n"
36
+ result += "PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n"
37
+ result += bindings
38
+ result += "}"
39
+ return result
40
+
41
+
42
+ def generate_dummy_code_boost(nclasses=10):
43
+ decl = ""
44
+ bindings = ""
45
+
46
+ for cl in range(nclasses):
47
+ decl += f"class cl{cl:03};\n"
48
+ decl += "\n"
49
+
50
+ for cl in range(nclasses):
51
+ decl += f"class cl{cl:03} {{\n"
52
+ decl += "public:\n"
53
+ bindings += f' py::class_<cl{cl:03}>("cl{cl:03}")\n'
54
+ for fn in range(nfns):
55
+ ret = random.randint(0, nclasses - 1)
56
+ params = [random.randint(0, nclasses - 1) for i in range(nargs)]
57
+ decl += f" cl{ret:03} *fn_{fn:03}("
58
+ decl += ", ".join(f"cl{p:03} *" for p in params)
59
+ decl += ");\n"
60
+ bindings += f' .def("fn_{fn:03}", &cl{cl:03}::fn_{fn:03}, py::return_value_policy<py::manage_new_object>())\n'
61
+ decl += "};\n\n"
62
+ bindings += " ;\n"
63
+
64
+ result = "#include <boost/python.hpp>\n\n"
65
+ result += "namespace py = boost::python;\n\n"
66
+ result += decl + "\n"
67
+ result += "BOOST_PYTHON_MODULE(example) {\n"
68
+ result += bindings
69
+ result += "}"
70
+ return result
71
+
72
+
73
+ for codegen in [generate_dummy_code_pybind11, generate_dummy_code_boost]:
74
+ print("{")
75
+ for i in range(10):
76
+ nclasses = 2**i
77
+ with open("test.cpp", "w") as f:
78
+ f.write(codegen(nclasses))
79
+ n1 = dt.datetime.now()
80
+ os.system(
81
+ "g++ -Os -shared -rdynamic -undefined dynamic_lookup "
82
+ "-fvisibility=hidden -std=c++14 test.cpp -I include "
83
+ "-I /System/Library/Frameworks/Python.framework/Headers -o test.so"
84
+ )
85
+ n2 = dt.datetime.now()
86
+ elapsed = (n2 - n1).total_seconds()
87
+ size = os.stat("test.so").st_size
88
+ print(f" {{{nclasses * nfns}, {elapsed:.6f}, {size}}},")
89
+ print("}")
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/docs/benchmark.rst ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Benchmark
2
+ =========
3
+
4
+ The following is the result of a synthetic benchmark comparing both compilation
5
+ time and module size of pybind11 against Boost.Python. A detailed report about a
6
+ Boost.Python to pybind11 conversion of a real project is available here: [#f1]_.
7
+
8
+ .. [#f1] http://graylab.jhu.edu/RosettaCon2016/PyRosetta-4.pdf
9
+
10
+ Setup
11
+ -----
12
+
13
+ A python script (see the ``docs/benchmark.py`` file) was used to generate a set
14
+ of files with dummy classes whose count increases for each successive benchmark
15
+ (between 1 and 2048 classes in powers of two). Each class has four methods with
16
+ a randomly generated signature with a return value and four arguments. (There
17
+ was no particular reason for this setup other than the desire to generate many
18
+ unique function signatures whose count could be controlled in a simple way.)
19
+
20
+ Here is an example of the binding code for one class:
21
+
22
+ .. code-block:: cpp
23
+
24
+ ...
25
+ class cl034 {
26
+ public:
27
+ cl279 *fn_000(cl084 *, cl057 *, cl065 *, cl042 *);
28
+ cl025 *fn_001(cl098 *, cl262 *, cl414 *, cl121 *);
29
+ cl085 *fn_002(cl445 *, cl297 *, cl145 *, cl421 *);
30
+ cl470 *fn_003(cl200 *, cl323 *, cl332 *, cl492 *);
31
+ };
32
+ ...
33
+
34
+ PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {
35
+ ...
36
+ py::class_<cl034>(m, "cl034")
37
+ .def("fn_000", &cl034::fn_000)
38
+ .def("fn_001", &cl034::fn_001)
39
+ .def("fn_002", &cl034::fn_002)
40
+ .def("fn_003", &cl034::fn_003)
41
+ ...
42
+ }
43
+
44
+ The Boost.Python version looks almost identical except that a return value
45
+ policy had to be specified as an argument to ``def()``. For both libraries,
46
+ compilation was done with
47
+
48
+ .. code-block:: bash
49
+
50
+ Apple LLVM version 7.0.2 (clang-700.1.81)
51
+
52
+ and the following compilation flags
53
+
54
+ .. code-block:: bash
55
+
56
+ g++ -Os -shared -rdynamic -undefined dynamic_lookup -fvisibility=hidden -std=c++14
57
+
58
+ Compilation time
59
+ ----------------
60
+
61
+ The following log-log plot shows how the compilation time grows for an
62
+ increasing number of class and function declarations. pybind11 includes many
63
+ fewer headers, which initially leads to shorter compilation times, but the
64
+ performance is ultimately fairly similar (pybind11 is 19.8 seconds faster for
65
+ the largest largest file with 2048 classes and a total of 8192 methods -- a
66
+ modest **1.2x** speedup relative to Boost.Python, which required 116.35
67
+ seconds).
68
+
69
+ .. only:: not latex
70
+
71
+ .. image:: pybind11_vs_boost_python1.svg
72
+
73
+ .. only:: latex
74
+
75
+ .. image:: pybind11_vs_boost_python1.png
76
+
77
+ Module size
78
+ -----------
79
+
80
+ Differences between the two libraries become much more pronounced when
81
+ considering the file size of the generated Python plugin: for the largest file,
82
+ the binary generated by Boost.Python required 16.8 MiB, which was **2.17
83
+ times** / **9.1 megabytes** larger than the output generated by pybind11. For
84
+ very small inputs, Boost.Python has an edge in the plot below -- however, note
85
+ that it stores many definitions in an external library, whose size was not
86
+ included here, hence the comparison is slightly shifted in Boost.Python's
87
+ favor.
88
+
89
+ .. only:: not latex
90
+
91
+ .. image:: pybind11_vs_boost_python2.svg
92
+
93
+ .. only:: latex
94
+
95
+ .. image:: pybind11_vs_boost_python2.png