c-api
c-api
3.12.1
19, 2023
1 3
1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.6 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2 C API 13
2.1 C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2.1 C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2.2 ABI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2.3 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2.4 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3 API 39
4 43
5 47
5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.6 Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.8 Unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
6 61
6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
i
6.3 . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.4 . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.5 marshal .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.6 .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.6.1 . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.6.2 . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.7 . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6.8 . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.9 . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.9.1 Codec API . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
6.9.2 Unicode API . . . . . . . . . . . . . . . . . . . . . 79
6.10 Perf Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
7 83
7.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.2.1 tp_call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.2.2 Vectorcall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
7.2.3 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.2.4 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
7.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
7.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
7.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
7.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
7.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
7.7.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
7.7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
7.7.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
7.7.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
7.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
8 107
8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
8.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
8.1.2 None . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
8.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
8.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
8.2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
8.2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
8.2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
8.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
8.3.1 bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
8.3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
8.3.3 Unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
8.3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
8.3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
8.3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
8.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
8.4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
8.4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
8.5 Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
8.5.1 Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
8.5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
8.5.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
8.5.4 Cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
8.5.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
8.5.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
8.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
ii
8.6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
8.6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
8.6.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
8.6.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
8.6.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
8.6.6 MemoryView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
8.6.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
8.6.8 Capsule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
8.6.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
8.6.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
8.6.11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
8.6.12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
8.6.13 DateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
8.6.14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
9 177
9.1 Python . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
9.2 . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
9.3 . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
9.4 . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
9.5 . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
9.5.1 GIL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
9.5.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
9.5.3 Cautions about fork() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
9.5.4 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
9.5.5 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
9.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
9.6.1 A Per-Interpreter GIL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
9.6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
9.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
9.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
9.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
9.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
9.10.1 Thread Specific Storage (TSS) API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
9.10.2 Thread Local Storage (TLS) API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
10 Python 201
10.1 . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
10.2 PyWideStringList . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
10.3 PyStatus . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
10.4 PyPreConfig . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
10.5 PyPreConfig Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
10.6 PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
10.7 PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
10.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
10.9 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
10.10 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
10.11 Py_RunMain() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
10.12 Py_GetArgcArgv() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
10.13 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
11 223
11.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
11.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
11.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
11.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
11.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
11.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
11.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
iii
11.8 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
11.9 pymalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
11.9.1 pymalloc Arena . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
11.10 tracemalloc C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
11.11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
12 233
12.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
12.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
12.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
12.2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
12.2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
12.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
12.3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
12.3.2 PyTypeObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
12.3.3 PyObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
12.3.4 PyVarObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
12.3.5 PyTypeObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
12.3.6 Static Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
12.3.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
12.4 Number Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
12.5 Mapping Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
12.6 Sequence Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
12.7 Buffer Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
12.8 Async Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
12.9 Slot Type typedefs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
12.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
12.11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
12.11.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
12.11.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
A 281
B 293
B.1 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
C 295
C.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
C.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . 296
C.2.1 PYTHON 3.12.1 PSF . . . . . . . . . . . . . . . . . . . . . . . . . 296
C.2.2 PYTHON 2.0 BEOPEN.COM . . . . . . . . . . . . . . . . . . . . . 297
C.2.3 PYTHON 1.6.1 CNRI . . . . . . . . . . . . . . . . . . . . . . . . . 298
C.2.4 PYTHON 0.9.0 1.2 CWI . . . . . . . . . . . . . . . . . . . . . . 299
C.2.5 ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3.12.1 DOCUMEN-
TATION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
C.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
C.3.1 Mersenne Twister . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
C.3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
C.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
C.3.4 Cookie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
C.3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
C.3.6 UUencode UUdecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
C.3.7 XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
C.3.8 test_epoll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
C.3.9 Select kqueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
C.3.10 SipHash24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
C.3.11 strtod dtoa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
iv
C.3.12 OpenSSL . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
C.3.13 expat . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
C.3.14 libffi . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
C.3.15 zlib . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
C.3.16 cfuhash . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
C.3.17 libmpdec . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
C.3.18 W3C C14N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
C.3.19 audioop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
D 313
315
v
vi
The Python/C API, 3.12.1
Contents 1
The Python/C API, 3.12.1
2 Contents
CHAPTER 1
Python Python
1.1
CPython C PEP 7
Python
Python
1.2
Python/C API
#define PY_SSIZE_T_CLEAN
#include <Python.h>
: Python
Python.h
3
The Python/C API, 3.12.1
Python.h PY_SSIZE_T_CLEAN
Python.h Py _Py
_Py Python
: Py _Py
Python
#include <pythonX.Y/Python.h>
prefix exec_prefix
C++ API C extern "C"
API C++ API
1.3
Python Py_RETURN_NONE
PyMODINIT_FUNC
PyInit PyObject*
C++ extern "C"
PyInit_name name
static :
PyMODINIT_FUNC
PyInit_spam(void)
{
return PyModule_Create(&spam_module);
}
Py_ABS(x)
x
3.3 .
Py_ALWAYS_INLINE
Python
MSC
Py_ALWAYS_INLINE
/
4 Chapter 1.
The Python/C API, 3.12.1
3.11 .
Py_CHARMASK(c)
[-128, 127] [0, 255] c unsigned
char
Py_DEPRECATED(version)
3.8 : MSVC
Py_GETENV(s)
getenv(s) -E NULL ( PyConfig.
use_environment)
Py_MAX(x, y)
x y
3.3 .
Py_MEMBER_SIZE(type, member)
(type) member
3.6 .
Py_MIN(x, y)
x y
3.3 .
Py_NO_INLINE
C LTO+PGO (
bpo-33720)
3.11 .
Py_STRINGIFY(x)
x C Py_STRINGIFY(123) "123"
3.4 .
Py_UNREACHABLE()
switch
case default:
assert(0) abort()
release GCC
release __builtin_unreachable()
Py_UNREACHABLE() _Py_NO_RETURN
1.3. 5
The Python/C API, 3.12.1
Py_FatalError()
3.7 .
Py_UNUSED(arg)
int func(int a, int
Py_UNUSED(b)) { return a; }
3.4 .
PyDoc_STRVAR(name, str)
name Python
PyDoc_STR(str)
1.4
6 Chapter 1.
The Python/C API, 3.12.1
1.4.1
strong reference C
C strong reference
Py_INCREF()
Py_DECREF() Py_DECREF()
incref
( sizeof(Py_ssize_t) >=
sizeof(void*))
strong reference ( )
strong reference ( )
C Python
Python Py_DECREF()
Python/C API
Py_DECREF
Py_DECREF() Py_XDECREF() ---
borrowed reference
PyList_SetItem() PyTuple_SetItem()
(1, 2, "three")
:
PyObject *t;
t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));
PyLong_FromLong() PyTuple_SetItem()
Py_INCREF()
1.4. 7
The Python/C API, 3.12.1
PyTuple_SetItem() PySequence_SetItem()
PyObject_SetItem()
PyTuple_SetItem()
PyList_New() PyList_SetItem()
Py_BuildValue() C
:
PyObject_SetItem()
int
set_all(PyObject *target, PyObject *item)
{
Py_ssize_t i, n;
n = PyObject_Length(target);
if (n < 0)
return -1;
for (i = 0; i < n; i++) {
PyObject *index = PyLong_FromSsize_t(i);
if (!index)
return -1;
if (PyObject_SetItem(target, index, item) < 0) {
Py_DECREF(index);
return -1;
}
Py_DECREF(index);
}
return 0;
}
PyObject_GetItem()
PySequence_GetItem()
--- (
) PyList_GetItem()
--- PySequence_GetItem() ( )
PyList_GetItem() PySequence_GetItem()
long
sum_list(PyObject *list)
{
Py_ssize_t i, n;
long total = 0, value;
PyObject *item;
( )
8 Chapter 1.
The Python/C API, 3.12.1
( )
n = PyList_Size(list);
if (n < 0)
return -1; /* Not a list */
for (i = 0; i < n; i++) {
item = PyList_GetItem(list, i); /* Can't fail */
if (!PyLong_Check(item)) continue; /* Skip non-integers */
value = PyLong_AsLong(item);
if (value == -1 && PyErr_Occurred())
/* Integer too big to fit in a C long, bail out */
return -1;
total += value;
}
return total;
}
long
sum_sequence(PyObject *sequence)
{
Py_ssize_t i, n;
long total = 0, value;
PyObject *item;
n = PySequence_Length(sequence);
if (n < 0)
return -1; /* Has no length */
for (i = 0; i < n; i++) {
item = PySequence_GetItem(sequence, i);
if (item == NULL)
return -1; /* Not a sequence, or other failure */
if (PyLong_Check(item)) {
value = PyLong_AsLong(item);
Py_DECREF(item);
if (value == -1 && PyErr_Occurred())
/* Integer too big to fit in a C long, bail out */
return -1;
total += value;
}
else {
Py_DECREF(item); /* Discard reference ownership */
}
}
return total;
}
1.4.2
type Py_ssize_t
ABI. sizeof(Py_ssize_t) == sizeof(size_t)
C99 size_t PEP 353
PY_SSIZE_T_MAX Py_ssize_t
1.4. 9
The Python/C API, 3.12.1
1.5
Python
C Python/C API
NULL -1
/
PyErr_Occurred()
PyErr_Occurred()
NULL
: PyErr_SetString()
PyErr_Clear()
( NULL):
Python sys.exc_info() Python
Python try ... except C C
Python
sys.exc_info()
Python 1.5 Python sys.
exc_info() Python
---
sum_sequence()
Python Python :
def incr_item(dict, key):
try:
item = dict[key]
except KeyError:
item = 0
dict[key] = item + 1
C
int
incr_item(PyObject *dict, PyObject *key)
{
/* Objects all initialized to NULL for Py_XDECREF */
PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
int rv = -1; /* Return value initialized to -1 (failure) */
10 Chapter 1.
The Python/C API, 3.12.1
( )
item = PyLong_FromLong(0L);
if (item == NULL)
goto error;
}
const_one = PyLong_FromLong(1L);
if (const_one == NULL)
goto error;
error:
/* Cleanup code, shared by success and failure path */
C goto
PyErr_ExceptionMatches() PyErr_Clear()
Py_XDECREF() NULL 'X' Py_DECREF()
NULL NULL
-1 ( )
1.6 Python
Python
Py_Initialize() builtins,
__main__ sys (sys.path)
Py_Initialize() ” ” (sys.argv) Python
PyConfig.argv PyConfig.parse_argv: Python
Unix Windows Py_Initialize()
Python Python Python
shell ( PATH)
python lib/pythonX.Y
Python /usr/local/bin/python /usr/local/
lib/pythonX.Y PATH
python PYTHONHOME PYTHONPATH
Py_Initialize() Py_SetProgramName(file)
PYTHONHOME PYTHONPATH
Py_GetPath(), Py_GetPrefix(),
Py_GetExecPrefix() Py_GetProgramFullPath() Modules/getpath.c
1.6. Python 11
The Python/C API, 3.12.1
Python (
Py_Initialize()) Python Python
Py_FinalizeEx() Python Py_IsInitialized()
Py_FinalizeEx()
Python
1.7
Python
Python Misc/SpecialBuilds.txt
Python Misc/SpecialBuilds.txt
12 Chapter 1.
CHAPTER 2
C API
CPython ABI
Python 3.10.0 3.10.8 3.9.x 3.10.x
C API
• API PyUnstable
• API Py_LIMITED_API
Python.h
_Py_InternalState
API API CPython
API
2.1 C API
API CPython
13
The Python/C API, 3.12.1
2.2
2.2.1 C API
2.2.2 ABI
2.2.3 API
API C API
PyList_GetItem() PyList_GET_ITEM()
Py_LIMITED_API C API
Py_LIMITED_API Python
Py_LIMITED_API ABI API
Python Py_LIMITED_API
Python
14 Chapter 2. C API
The Python/C API, 3.12.1
2.2.4 API
Python
API API
Py_LIMITED_API
2.3
2.4 API
API :
• PY_VECTORCALL_ARGUMENTS_OFFSET
• PyAIter_Check()
• PyArg_Parse()
• PyArg_ParseTuple()
• PyArg_ParseTupleAndKeywords()
• PyArg_UnpackTuple()
• PyArg_VaParse()
• PyArg_VaParseTupleAndKeywords()
• PyArg_ValidateKeywordArguments()
• PyBaseObject_Type
• PyBool_FromLong()
• PyBool_Type
• PyBuffer_FillContiguousStrides()
• PyBuffer_FillInfo()
2.3. 15
The Python/C API, 3.12.1
• PyBuffer_FromContiguous()
• PyBuffer_GetPointer()
• PyBuffer_IsContiguous()
• PyBuffer_Release()
• PyBuffer_SizeFromFormat()
• PyBuffer_ToContiguous()
• PyByteArrayIter_Type
• PyByteArray_AsString()
• PyByteArray_Concat()
• PyByteArray_FromObject()
• PyByteArray_FromStringAndSize()
• PyByteArray_Resize()
• PyByteArray_Size()
• PyByteArray_Type
• PyBytesIter_Type
• PyBytes_AsString()
• PyBytes_AsStringAndSize()
• PyBytes_Concat()
• PyBytes_ConcatAndDel()
• PyBytes_DecodeEscape()
• PyBytes_FromFormat()
• PyBytes_FromFormatV()
• PyBytes_FromObject()
• PyBytes_FromString()
• PyBytes_FromStringAndSize()
• PyBytes_Repr()
• PyBytes_Size()
• PyBytes_Type
• PyCFunction
• PyCFunctionWithKeywords
• PyCFunction_Call()
• PyCFunction_GetFlags()
• PyCFunction_GetFunction()
• PyCFunction_GetSelf()
• PyCFunction_New()
• PyCFunction_NewEx()
• PyCFunction_Type
• PyCMethod_New()
• PyCallIter_New()
16 Chapter 2. C API
The Python/C API, 3.12.1
• PyCallIter_Type
• PyCallable_Check()
• PyCapsule_Destructor
• PyCapsule_GetContext()
• PyCapsule_GetDestructor()
• PyCapsule_GetName()
• PyCapsule_GetPointer()
• PyCapsule_Import()
• PyCapsule_IsValid()
• PyCapsule_New()
• PyCapsule_SetContext()
• PyCapsule_SetDestructor()
• PyCapsule_SetName()
• PyCapsule_SetPointer()
• PyCapsule_Type
• PyClassMethodDescr_Type
• PyCodec_BackslashReplaceErrors()
• PyCodec_Decode()
• PyCodec_Decoder()
• PyCodec_Encode()
• PyCodec_Encoder()
• PyCodec_IgnoreErrors()
• PyCodec_IncrementalDecoder()
• PyCodec_IncrementalEncoder()
• PyCodec_KnownEncoding()
• PyCodec_LookupError()
• PyCodec_NameReplaceErrors()
• PyCodec_Register()
• PyCodec_RegisterError()
• PyCodec_ReplaceErrors()
• PyCodec_StreamReader()
• PyCodec_StreamWriter()
• PyCodec_StrictErrors()
• PyCodec_Unregister()
• PyCodec_XMLCharRefReplaceErrors()
• PyComplex_FromDoubles()
• PyComplex_ImagAsDouble()
• PyComplex_RealAsDouble()
• PyComplex_Type
2.4. API 17
The Python/C API, 3.12.1
• PyDescr_NewClassMethod()
• PyDescr_NewGetSet()
• PyDescr_NewMember()
• PyDescr_NewMethod()
• PyDictItems_Type
• PyDictIterItem_Type
• PyDictIterKey_Type
• PyDictIterValue_Type
• PyDictKeys_Type
• PyDictProxy_New()
• PyDictProxy_Type
• PyDictRevIterItem_Type
• PyDictRevIterKey_Type
• PyDictRevIterValue_Type
• PyDictValues_Type
• PyDict_Clear()
• PyDict_Contains()
• PyDict_Copy()
• PyDict_DelItem()
• PyDict_DelItemString()
• PyDict_GetItem()
• PyDict_GetItemString()
• PyDict_GetItemWithError()
• PyDict_Items()
• PyDict_Keys()
• PyDict_Merge()
• PyDict_MergeFromSeq2()
• PyDict_New()
• PyDict_Next()
• PyDict_SetItem()
• PyDict_SetItemString()
• PyDict_Size()
• PyDict_Type
• PyDict_Update()
• PyDict_Values()
• PyEllipsis_Type
• PyEnum_Type
• PyErr_BadArgument()
• PyErr_BadInternalCall()
18 Chapter 2. C API
The Python/C API, 3.12.1
• PyErr_CheckSignals()
• PyErr_Clear()
• PyErr_Display()
• PyErr_DisplayException()
• PyErr_ExceptionMatches()
• PyErr_Fetch()
• PyErr_Format()
• PyErr_FormatV()
• PyErr_GetExcInfo()
• PyErr_GetHandledException()
• PyErr_GetRaisedException()
• PyErr_GivenExceptionMatches()
• PyErr_NewException()
• PyErr_NewExceptionWithDoc()
• PyErr_NoMemory()
• PyErr_NormalizeException()
• PyErr_Occurred()
• PyErr_Print()
• PyErr_PrintEx()
• PyErr_ProgramText()
• PyErr_ResourceWarning()
• PyErr_Restore()
• PyErr_SetExcFromWindowsErr()
• PyErr_SetExcFromWindowsErrWithFilename()
• PyErr_SetExcFromWindowsErrWithFilenameObject()
• PyErr_SetExcFromWindowsErrWithFilenameObjects()
• PyErr_SetExcInfo()
• PyErr_SetFromErrno()
• PyErr_SetFromErrnoWithFilename()
• PyErr_SetFromErrnoWithFilenameObject()
• PyErr_SetFromErrnoWithFilenameObjects()
• PyErr_SetFromWindowsErr()
• PyErr_SetFromWindowsErrWithFilename()
• PyErr_SetHandledException()
• PyErr_SetImportError()
• PyErr_SetImportErrorSubclass()
• PyErr_SetInterrupt()
• PyErr_SetInterruptEx()
• PyErr_SetNone()
2.4. API 19
The Python/C API, 3.12.1
• PyErr_SetObject()
• PyErr_SetRaisedException()
• PyErr_SetString()
• PyErr_SyntaxLocation()
• PyErr_SyntaxLocationEx()
• PyErr_WarnEx()
• PyErr_WarnExplicit()
• PyErr_WarnFormat()
• PyErr_WriteUnraisable()
• PyEval_AcquireLock()
• PyEval_AcquireThread()
• PyEval_CallFunction()
• PyEval_CallMethod()
• PyEval_CallObjectWithKeywords()
• PyEval_EvalCode()
• PyEval_EvalCodeEx()
• PyEval_EvalFrame()
• PyEval_EvalFrameEx()
• PyEval_GetBuiltins()
• PyEval_GetFrame()
• PyEval_GetFuncDesc()
• PyEval_GetFuncName()
• PyEval_GetGlobals()
• PyEval_GetLocals()
• PyEval_InitThreads()
• PyEval_ReleaseLock()
• PyEval_ReleaseThread()
• PyEval_RestoreThread()
• PyEval_SaveThread()
• PyEval_ThreadsInitialized()
• PyExc_ArithmeticError
• PyExc_AssertionError
• PyExc_AttributeError
• PyExc_BaseException
• PyExc_BaseExceptionGroup
• PyExc_BlockingIOError
• PyExc_BrokenPipeError
• PyExc_BufferError
• PyExc_BytesWarning
20 Chapter 2. C API
The Python/C API, 3.12.1
• PyExc_ChildProcessError
• PyExc_ConnectionAbortedError
• PyExc_ConnectionError
• PyExc_ConnectionRefusedError
• PyExc_ConnectionResetError
• PyExc_DeprecationWarning
• PyExc_EOFError
• PyExc_EncodingWarning
• PyExc_EnvironmentError
• PyExc_Exception
• PyExc_FileExistsError
• PyExc_FileNotFoundError
• PyExc_FloatingPointError
• PyExc_FutureWarning
• PyExc_GeneratorExit
• PyExc_IOError
• PyExc_ImportError
• PyExc_ImportWarning
• PyExc_IndentationError
• PyExc_IndexError
• PyExc_InterruptedError
• PyExc_IsADirectoryError
• PyExc_KeyError
• PyExc_KeyboardInterrupt
• PyExc_LookupError
• PyExc_MemoryError
• PyExc_ModuleNotFoundError
• PyExc_NameError
• PyExc_NotADirectoryError
• PyExc_NotImplementedError
• PyExc_OSError
• PyExc_OverflowError
• PyExc_PendingDeprecationWarning
• PyExc_PermissionError
• PyExc_ProcessLookupError
• PyExc_RecursionError
• PyExc_ReferenceError
• PyExc_ResourceWarning
• PyExc_RuntimeError
2.4. API 21
The Python/C API, 3.12.1
• PyExc_RuntimeWarning
• PyExc_StopAsyncIteration
• PyExc_StopIteration
• PyExc_SyntaxError
• PyExc_SyntaxWarning
• PyExc_SystemError
• PyExc_SystemExit
• PyExc_TabError
• PyExc_TimeoutError
• PyExc_TypeError
• PyExc_UnboundLocalError
• PyExc_UnicodeDecodeError
• PyExc_UnicodeEncodeError
• PyExc_UnicodeError
• PyExc_UnicodeTranslateError
• PyExc_UnicodeWarning
• PyExc_UserWarning
• PyExc_ValueError
• PyExc_Warning
• PyExc_WindowsError
• PyExc_ZeroDivisionError
• PyExceptionClass_Name()
• PyException_GetArgs()
• PyException_GetCause()
• PyException_GetContext()
• PyException_GetTraceback()
• PyException_SetArgs()
• PyException_SetCause()
• PyException_SetContext()
• PyException_SetTraceback()
• PyFile_FromFd()
• PyFile_GetLine()
• PyFile_WriteObject()
• PyFile_WriteString()
• PyFilter_Type
• PyFloat_AsDouble()
• PyFloat_FromDouble()
• PyFloat_FromString()
• PyFloat_GetInfo()
22 Chapter 2. C API
The Python/C API, 3.12.1
• PyFloat_GetMax()
• PyFloat_GetMin()
• PyFloat_Type
• PyFrameObject
• PyFrame_GetCode()
• PyFrame_GetLineNumber()
• PyFrozenSet_New()
• PyFrozenSet_Type
• PyGC_Collect()
• PyGC_Disable()
• PyGC_Enable()
• PyGC_IsEnabled()
• PyGILState_Ensure()
• PyGILState_GetThisThreadState()
• PyGILState_Release()
• PyGILState_STATE
• PyGetSetDef
• PyGetSetDescr_Type
• PyImport_AddModule()
• PyImport_AddModuleObject()
• PyImport_AppendInittab()
• PyImport_ExecCodeModule()
• PyImport_ExecCodeModuleEx()
• PyImport_ExecCodeModuleObject()
• PyImport_ExecCodeModuleWithPathnames()
• PyImport_GetImporter()
• PyImport_GetMagicNumber()
• PyImport_GetMagicTag()
• PyImport_GetModule()
• PyImport_GetModuleDict()
• PyImport_Import()
• PyImport_ImportFrozenModule()
• PyImport_ImportFrozenModuleObject()
• PyImport_ImportModule()
• PyImport_ImportModuleLevel()
• PyImport_ImportModuleLevelObject()
• PyImport_ImportModuleNoBlock()
• PyImport_ReloadModule()
• PyIndex_Check()
2.4. API 23
The Python/C API, 3.12.1
• PyInterpreterState
• PyInterpreterState_Clear()
• PyInterpreterState_Delete()
• PyInterpreterState_Get()
• PyInterpreterState_GetDict()
• PyInterpreterState_GetID()
• PyInterpreterState_New()
• PyIter_Check()
• PyIter_Next()
• PyIter_Send()
• PyListIter_Type
• PyListRevIter_Type
• PyList_Append()
• PyList_AsTuple()
• PyList_GetItem()
• PyList_GetSlice()
• PyList_Insert()
• PyList_New()
• PyList_Reverse()
• PyList_SetItem()
• PyList_SetSlice()
• PyList_Size()
• PyList_Sort()
• PyList_Type
• PyLongObject
• PyLongRangeIter_Type
• PyLong_AsDouble()
• PyLong_AsLong()
• PyLong_AsLongAndOverflow()
• PyLong_AsLongLong()
• PyLong_AsLongLongAndOverflow()
• PyLong_AsSize_t()
• PyLong_AsSsize_t()
• PyLong_AsUnsignedLong()
• PyLong_AsUnsignedLongLong()
• PyLong_AsUnsignedLongLongMask()
• PyLong_AsUnsignedLongMask()
• PyLong_AsVoidPtr()
• PyLong_FromDouble()
24 Chapter 2. C API
The Python/C API, 3.12.1
• PyLong_FromLong()
• PyLong_FromLongLong()
• PyLong_FromSize_t()
• PyLong_FromSsize_t()
• PyLong_FromString()
• PyLong_FromUnsignedLong()
• PyLong_FromUnsignedLongLong()
• PyLong_FromVoidPtr()
• PyLong_GetInfo()
• PyLong_Type
• PyMap_Type
• PyMapping_Check()
• PyMapping_GetItemString()
• PyMapping_HasKey()
• PyMapping_HasKeyString()
• PyMapping_Items()
• PyMapping_Keys()
• PyMapping_Length()
• PyMapping_SetItemString()
• PyMapping_Size()
• PyMapping_Values()
• PyMem_Calloc()
• PyMem_Free()
• PyMem_Malloc()
• PyMem_Realloc()
• PyMemberDef
• PyMemberDescr_Type
• PyMember_GetOne()
• PyMember_SetOne()
• PyMemoryView_FromBuffer()
• PyMemoryView_FromMemory()
• PyMemoryView_FromObject()
• PyMemoryView_GetContiguous()
• PyMemoryView_Type
• PyMethodDef
• PyMethodDescr_Type
• PyModuleDef
• PyModuleDef_Base
• PyModuleDef_Init()
2.4. API 25
The Python/C API, 3.12.1
• PyModuleDef_Type
• PyModule_AddFunctions()
• PyModule_AddIntConstant()
• PyModule_AddObject()
• PyModule_AddObjectRef()
• PyModule_AddStringConstant()
• PyModule_AddType()
• PyModule_Create2()
• PyModule_ExecDef()
• PyModule_FromDefAndSpec2()
• PyModule_GetDef()
• PyModule_GetDict()
• PyModule_GetFilename()
• PyModule_GetFilenameObject()
• PyModule_GetName()
• PyModule_GetNameObject()
• PyModule_GetState()
• PyModule_New()
• PyModule_NewObject()
• PyModule_SetDocString()
• PyModule_Type
• PyNumber_Absolute()
• PyNumber_Add()
• PyNumber_And()
• PyNumber_AsSsize_t()
• PyNumber_Check()
• PyNumber_Divmod()
• PyNumber_Float()
• PyNumber_FloorDivide()
• PyNumber_InPlaceAdd()
• PyNumber_InPlaceAnd()
• PyNumber_InPlaceFloorDivide()
• PyNumber_InPlaceLshift()
• PyNumber_InPlaceMatrixMultiply()
• PyNumber_InPlaceMultiply()
• PyNumber_InPlaceOr()
• PyNumber_InPlacePower()
• PyNumber_InPlaceRemainder()
• PyNumber_InPlaceRshift()
26 Chapter 2. C API
The Python/C API, 3.12.1
• PyNumber_InPlaceSubtract()
• PyNumber_InPlaceTrueDivide()
• PyNumber_InPlaceXor()
• PyNumber_Index()
• PyNumber_Invert()
• PyNumber_Long()
• PyNumber_Lshift()
• PyNumber_MatrixMultiply()
• PyNumber_Multiply()
• PyNumber_Negative()
• PyNumber_Or()
• PyNumber_Positive()
• PyNumber_Power()
• PyNumber_Remainder()
• PyNumber_Rshift()
• PyNumber_Subtract()
• PyNumber_ToBase()
• PyNumber_TrueDivide()
• PyNumber_Xor()
• PyOS_AfterFork()
• PyOS_AfterFork_Child()
• PyOS_AfterFork_Parent()
• PyOS_BeforeFork()
• PyOS_CheckStack()
• PyOS_FSPath()
• PyOS_InputHook
• PyOS_InterruptOccurred()
• PyOS_double_to_string()
• PyOS_getsig()
• PyOS_mystricmp()
• PyOS_mystrnicmp()
• PyOS_setsig()
• PyOS_sighandler_t
• PyOS_snprintf()
• PyOS_string_to_double()
• PyOS_strtol()
• PyOS_strtoul()
• PyOS_vsnprintf()
• PyObject
2.4. API 27
The Python/C API, 3.12.1
• PyObject.ob_refcnt
• PyObject.ob_type
• PyObject_ASCII()
• PyObject_AsCharBuffer()
• PyObject_AsFileDescriptor()
• PyObject_AsReadBuffer()
• PyObject_AsWriteBuffer()
• PyObject_Bytes()
• PyObject_Call()
• PyObject_CallFunction()
• PyObject_CallFunctionObjArgs()
• PyObject_CallMethod()
• PyObject_CallMethodObjArgs()
• PyObject_CallNoArgs()
• PyObject_CallObject()
• PyObject_Calloc()
• PyObject_CheckBuffer()
• PyObject_CheckReadBuffer()
• PyObject_ClearWeakRefs()
• PyObject_CopyData()
• PyObject_DelItem()
• PyObject_DelItemString()
• PyObject_Dir()
• PyObject_Format()
• PyObject_Free()
• PyObject_GC_Del()
• PyObject_GC_IsFinalized()
• PyObject_GC_IsTracked()
• PyObject_GC_Track()
• PyObject_GC_UnTrack()
• PyObject_GenericGetAttr()
• PyObject_GenericGetDict()
• PyObject_GenericSetAttr()
• PyObject_GenericSetDict()
• PyObject_GetAIter()
• PyObject_GetAttr()
• PyObject_GetAttrString()
• PyObject_GetBuffer()
• PyObject_GetItem()
28 Chapter 2. C API
The Python/C API, 3.12.1
• PyObject_GetIter()
• PyObject_GetTypeData()
• PyObject_HasAttr()
• PyObject_HasAttrString()
• PyObject_Hash()
• PyObject_HashNotImplemented()
• PyObject_Init()
• PyObject_InitVar()
• PyObject_IsInstance()
• PyObject_IsSubclass()
• PyObject_IsTrue()
• PyObject_Length()
• PyObject_Malloc()
• PyObject_Not()
• PyObject_Realloc()
• PyObject_Repr()
• PyObject_RichCompare()
• PyObject_RichCompareBool()
• PyObject_SelfIter()
• PyObject_SetAttr()
• PyObject_SetAttrString()
• PyObject_SetItem()
• PyObject_Size()
• PyObject_Str()
• PyObject_Type()
• PyObject_Vectorcall()
• PyObject_VectorcallMethod()
• PyProperty_Type
• PyRangeIter_Type
• PyRange_Type
• PyReversed_Type
• PySeqIter_New()
• PySeqIter_Type
• PySequence_Check()
• PySequence_Concat()
• PySequence_Contains()
• PySequence_Count()
• PySequence_DelItem()
• PySequence_DelSlice()
2.4. API 29
The Python/C API, 3.12.1
• PySequence_Fast()
• PySequence_GetItem()
• PySequence_GetSlice()
• PySequence_In()
• PySequence_InPlaceConcat()
• PySequence_InPlaceRepeat()
• PySequence_Index()
• PySequence_Length()
• PySequence_List()
• PySequence_Repeat()
• PySequence_SetItem()
• PySequence_SetSlice()
• PySequence_Size()
• PySequence_Tuple()
• PySetIter_Type
• PySet_Add()
• PySet_Clear()
• PySet_Contains()
• PySet_Discard()
• PySet_New()
• PySet_Pop()
• PySet_Size()
• PySet_Type
• PySlice_AdjustIndices()
• PySlice_GetIndices()
• PySlice_GetIndicesEx()
• PySlice_New()
• PySlice_Type
• PySlice_Unpack()
• PyState_AddModule()
• PyState_FindModule()
• PyState_RemoveModule()
• PyStructSequence_Desc
• PyStructSequence_Field
• PyStructSequence_GetItem()
• PyStructSequence_New()
• PyStructSequence_NewType()
• PyStructSequence_SetItem()
• PyStructSequence_UnnamedField
30 Chapter 2. C API
The Python/C API, 3.12.1
• PySuper_Type
• PySys_AddWarnOption()
• PySys_AddWarnOptionUnicode()
• PySys_AddXOption()
• PySys_FormatStderr()
• PySys_FormatStdout()
• PySys_GetObject()
• PySys_GetXOptions()
• PySys_HasWarnOptions()
• PySys_ResetWarnOptions()
• PySys_SetArgv()
• PySys_SetArgvEx()
• PySys_SetObject()
• PySys_SetPath()
• PySys_WriteStderr()
• PySys_WriteStdout()
• PyThreadState
• PyThreadState_Clear()
• PyThreadState_Delete()
• PyThreadState_Get()
• PyThreadState_GetDict()
• PyThreadState_GetFrame()
• PyThreadState_GetID()
• PyThreadState_GetInterpreter()
• PyThreadState_New()
• PyThreadState_SetAsyncExc()
• PyThreadState_Swap()
• PyThread_GetInfo()
• PyThread_ReInitTLS()
• PyThread_acquire_lock()
• PyThread_acquire_lock_timed()
• PyThread_allocate_lock()
• PyThread_create_key()
• PyThread_delete_key()
• PyThread_delete_key_value()
• PyThread_exit_thread()
• PyThread_free_lock()
• PyThread_get_key_value()
• PyThread_get_stacksize()
2.4. API 31
The Python/C API, 3.12.1
• PyThread_get_thread_ident()
• PyThread_get_thread_native_id()
• PyThread_init_thread()
• PyThread_release_lock()
• PyThread_set_key_value()
• PyThread_set_stacksize()
• PyThread_start_new_thread()
• PyThread_tss_alloc()
• PyThread_tss_create()
• PyThread_tss_delete()
• PyThread_tss_free()
• PyThread_tss_get()
• PyThread_tss_is_created()
• PyThread_tss_set()
• PyTraceBack_Here()
• PyTraceBack_Print()
• PyTraceBack_Type
• PyTupleIter_Type
• PyTuple_GetItem()
• PyTuple_GetSlice()
• PyTuple_New()
• PyTuple_Pack()
• PyTuple_SetItem()
• PyTuple_Size()
• PyTuple_Type
• PyTypeObject
• PyType_ClearCache()
• PyType_FromMetaclass()
• PyType_FromModuleAndSpec()
• PyType_FromSpec()
• PyType_FromSpecWithBases()
• PyType_GenericAlloc()
• PyType_GenericNew()
• PyType_GetFlags()
• PyType_GetModule()
• PyType_GetModuleState()
• PyType_GetName()
• PyType_GetQualName()
• PyType_GetSlot()
32 Chapter 2. C API
The Python/C API, 3.12.1
• PyType_GetTypeDataSize()
• PyType_IsSubtype()
• PyType_Modified()
• PyType_Ready()
• PyType_Slot
• PyType_Spec
• PyType_Type
• PyUnicodeDecodeError_Create()
• PyUnicodeDecodeError_GetEncoding()
• PyUnicodeDecodeError_GetEnd()
• PyUnicodeDecodeError_GetObject()
• PyUnicodeDecodeError_GetReason()
• PyUnicodeDecodeError_GetStart()
• PyUnicodeDecodeError_SetEnd()
• PyUnicodeDecodeError_SetReason()
• PyUnicodeDecodeError_SetStart()
• PyUnicodeEncodeError_GetEncoding()
• PyUnicodeEncodeError_GetEnd()
• PyUnicodeEncodeError_GetObject()
• PyUnicodeEncodeError_GetReason()
• PyUnicodeEncodeError_GetStart()
• PyUnicodeEncodeError_SetEnd()
• PyUnicodeEncodeError_SetReason()
• PyUnicodeEncodeError_SetStart()
• PyUnicodeIter_Type
• PyUnicodeTranslateError_GetEnd()
• PyUnicodeTranslateError_GetObject()
• PyUnicodeTranslateError_GetReason()
• PyUnicodeTranslateError_GetStart()
• PyUnicodeTranslateError_SetEnd()
• PyUnicodeTranslateError_SetReason()
• PyUnicodeTranslateError_SetStart()
• PyUnicode_Append()
• PyUnicode_AppendAndDel()
• PyUnicode_AsASCIIString()
• PyUnicode_AsCharmapString()
• PyUnicode_AsDecodedObject()
• PyUnicode_AsDecodedUnicode()
• PyUnicode_AsEncodedObject()
2.4. API 33
The Python/C API, 3.12.1
• PyUnicode_AsEncodedString()
• PyUnicode_AsEncodedUnicode()
• PyUnicode_AsLatin1String()
• PyUnicode_AsMBCSString()
• PyUnicode_AsRawUnicodeEscapeString()
• PyUnicode_AsUCS4()
• PyUnicode_AsUCS4Copy()
• PyUnicode_AsUTF16String()
• PyUnicode_AsUTF32String()
• PyUnicode_AsUTF8AndSize()
• PyUnicode_AsUTF8String()
• PyUnicode_AsUnicodeEscapeString()
• PyUnicode_AsWideChar()
• PyUnicode_AsWideCharString()
• PyUnicode_BuildEncodingMap()
• PyUnicode_Compare()
• PyUnicode_CompareWithASCIIString()
• PyUnicode_Concat()
• PyUnicode_Contains()
• PyUnicode_Count()
• PyUnicode_Decode()
• PyUnicode_DecodeASCII()
• PyUnicode_DecodeCharmap()
• PyUnicode_DecodeCodePageStateful()
• PyUnicode_DecodeFSDefault()
• PyUnicode_DecodeFSDefaultAndSize()
• PyUnicode_DecodeLatin1()
• PyUnicode_DecodeLocale()
• PyUnicode_DecodeLocaleAndSize()
• PyUnicode_DecodeMBCS()
• PyUnicode_DecodeMBCSStateful()
• PyUnicode_DecodeRawUnicodeEscape()
• PyUnicode_DecodeUTF16()
• PyUnicode_DecodeUTF16Stateful()
• PyUnicode_DecodeUTF32()
• PyUnicode_DecodeUTF32Stateful()
• PyUnicode_DecodeUTF7()
• PyUnicode_DecodeUTF7Stateful()
• PyUnicode_DecodeUTF8()
34 Chapter 2. C API
The Python/C API, 3.12.1
• PyUnicode_DecodeUTF8Stateful()
• PyUnicode_DecodeUnicodeEscape()
• PyUnicode_EncodeCodePage()
• PyUnicode_EncodeFSDefault()
• PyUnicode_EncodeLocale()
• PyUnicode_FSConverter()
• PyUnicode_FSDecoder()
• PyUnicode_Find()
• PyUnicode_FindChar()
• PyUnicode_Format()
• PyUnicode_FromEncodedObject()
• PyUnicode_FromFormat()
• PyUnicode_FromFormatV()
• PyUnicode_FromObject()
• PyUnicode_FromOrdinal()
• PyUnicode_FromString()
• PyUnicode_FromStringAndSize()
• PyUnicode_FromWideChar()
• PyUnicode_GetDefaultEncoding()
• PyUnicode_GetLength()
• PyUnicode_InternFromString()
• PyUnicode_InternInPlace()
• PyUnicode_IsIdentifier()
• PyUnicode_Join()
• PyUnicode_Partition()
• PyUnicode_RPartition()
• PyUnicode_RSplit()
• PyUnicode_ReadChar()
• PyUnicode_Replace()
• PyUnicode_Resize()
• PyUnicode_RichCompare()
• PyUnicode_Split()
• PyUnicode_Splitlines()
• PyUnicode_Substring()
• PyUnicode_Tailmatch()
• PyUnicode_Translate()
• PyUnicode_Type
• PyUnicode_WriteChar()
• PyVarObject
2.4. API 35
The Python/C API, 3.12.1
• PyVarObject.ob_base
• PyVarObject.ob_size
• PyVectorcall_Call()
• PyVectorcall_NARGS()
• PyWeakReference
• PyWeakref_GetObject()
• PyWeakref_NewProxy()
• PyWeakref_NewRef()
• PyWrapperDescr_Type
• PyWrapper_New()
• PyZip_Type
• Py_AddPendingCall()
• Py_AtExit()
• Py_BEGIN_ALLOW_THREADS
• Py_BLOCK_THREADS
• Py_BuildValue()
• Py_BytesMain()
• Py_CompileString()
• Py_DecRef()
• Py_DecodeLocale()
• Py_END_ALLOW_THREADS
• Py_EncodeLocale()
• Py_EndInterpreter()
• Py_EnterRecursiveCall()
• Py_Exit()
• Py_FatalError()
• Py_FileSystemDefaultEncodeErrors
• Py_FileSystemDefaultEncoding
• Py_Finalize()
• Py_FinalizeEx()
• Py_GenericAlias()
• Py_GenericAliasType
• Py_GetBuildInfo()
• Py_GetCompiler()
• Py_GetCopyright()
• Py_GetExecPrefix()
• Py_GetPath()
• Py_GetPlatform()
• Py_GetPrefix()
36 Chapter 2. C API
The Python/C API, 3.12.1
• Py_GetProgramFullPath()
• Py_GetProgramName()
• Py_GetPythonHome()
• Py_GetRecursionLimit()
• Py_GetVersion()
• Py_HasFileSystemDefaultEncoding
• Py_IncRef()
• Py_Initialize()
• Py_InitializeEx()
• Py_Is()
• Py_IsFalse()
• Py_IsInitialized()
• Py_IsNone()
• Py_IsTrue()
• Py_LeaveRecursiveCall()
• Py_Main()
• Py_MakePendingCalls()
• Py_NewInterpreter()
• Py_NewRef()
• Py_ReprEnter()
• Py_ReprLeave()
• Py_SetPath()
• Py_SetProgramName()
• Py_SetPythonHome()
• Py_SetRecursionLimit()
• Py_UCS4
• Py_UNBLOCK_THREADS
• Py_UTF8Mode
• Py_VaBuildValue()
• Py_Version
• Py_XNewRef()
• Py_buffer
• Py_intptr_t
• Py_ssize_t
• Py_uintptr_t
• allocfunc
• binaryfunc
• descrgetfunc
• descrsetfunc
2.4. API 37
The Python/C API, 3.12.1
• destructor
• getattrfunc
• getattrofunc
• getbufferproc
• getiterfunc
• getter
• hashfunc
• initproc
• inquiry
• iternextfunc
• lenfunc
• newfunc
• objobjargproc
• objobjproc
• releasebufferproc
• reprfunc
• richcmpfunc
• setattrfunc
• setattrofunc
• setter
• ssizeargfunc
• ssizeobjargproc
• ssizessizeargfunc
• ssizessizeobjargproc
• symtable
• ternaryfunc
• traverseproc
• unaryfunc
• vectorcallfunc
• visitproc
38 Chapter 2. C API
CHAPTER 3
API
Python
Py_eval_input,
Py_file_input Py_single_input
FILE* C
FILE Windows
Python
FILE*
int Py_Main(int argc, wchar_t **argv)
ABI. Python argc
argv C main()
0 1
Python 2
SystemExit 1
PyConfig.inspect
int Py_BytesMain(int argc, char **argv)
ABI 3.8 . Py_Main() argv
3.8 .
int PyRun_AnyFile(FILE *fp, const char *filename)
PyRun_AnyFileExFlags() closeit 0 flags NULL
int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
PyRun_AnyFileExFlags() closeit 0
int PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
PyRun_AnyFileExFlags() flags NULL
int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)
fp Unix
PyRun_InteractiveLoop() PyRun_SimpleFile() filename
(sys.getfilesystemencoding()) filename NULL
39
The Python/C API, 3.12.1
SystemExit -1
PyConfig.inspect
int PyRun_SimpleFile(FILE *fp, const char *filename)
PyRun_SimpleFileExFlags() closeit 0 flags
NULL
int PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
PyRun_SimpleFileExFlags() flags NULL
int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)
PyRun_SimpleStringFlags() Python fp
filename filesystem encoding and error handler closeit
PyRun_SimpleFileExFlags()
int (*PyOS_InputHook)(void)
ABI. int func(void) Python
Python Modules/_tkinter.c
3.12 :
char *(*PyOS_ReadlineFunctionPointer)(FILE*, FILE*, const char*)
char *func(FILE *stdin, FILE *stdout, char *prompt)
prompt
NULL
readline tab
40 Chapter 3. API
The Python/C API, 3.12.1
PyMem_RawMalloc() PyMem_RawRealloc()
NULL
3.4 : PyMem_RawMalloc() PyMem_RawRealloc()
PyMem_Malloc() PyMem_Realloc()
3.12 :
PyObject *PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
PyRun_StringFlags() flags NULL
PyObject *PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
PyCompilerFlags *flags)
globals locals str Python
flags globals locals
start
Python NULL
PyObject *PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals)
PyRun_FileExFlags() closeit 0
flags NULL
PyObject *PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int
closeit)
PyRun_FileExFlags() flags NULL
PyObject *PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
PyCompilerFlags *flags)
PyRun_FileExFlags() closeit 0
PyObject *PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
int closeit, PyCompilerFlags *flags)
PyRun_StringFlags() Python fp
filename filesystem encoding and error handler
closeit PyRun_FileExFlags()
PyObject *Py_CompileString(const char *str, const char *filename, int start)
ABI. Py_CompileStringFlags()
flags NULL
PyObject *Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags)
Py_CompileStringExFlags() optimize
-1
PyObject *Py_CompileStringObject(const char *str, PyObject *filename, int start, PyCompilerFlags *flags,
int optimize)
str Python
start Py_eval_input, Py_file_input
Py_single_input filename
SyntaxError NULL
optimize -1 -O
0( __debug__ ) 1( __debug__ ) 2(
)
3.4 .
PyObject *Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompilerFlags
*flags, int optimize)
Py_CompileStringObject() filename filesystem encoding
and error handler
3.2 .
41
The Python/C API, 3.12.1
int Py_eval_input
Python Py_CompileString()
int Py_file_input
Python Py_CompileString()
Python
int Py_single_input
Python Py_CompileString()
struct PyCompilerFlags
int flags
PyCompilerFlags *flags from
__future__ import flags
PyCompilerFlags *flags NULL cf_flags 0 from
__future__ import
int cf_flags
int cf_feature_version
cf_feature_version Python PY_MINOR_VERSION
cf_flags PyCF_ONLY_AST
3.8 : cf_feature_version
int CO_FUTURE_DIVISION
flags / PEP 238
42 Chapter 3. API
CHAPTER 4
Python
Py_ssize_t Py_REFCNT(PyObject *o)
Python o
refcount 0 1
Py_SET_REFCNT()
3.11 : const PyObject*
3.10 : Py_REFCNT()
void Py_SET_REFCNT(PyObject *o, Py_ssize_t refcnt)
o refcnt
3.9 .
3.12 :
void Py_INCREF(PyObject *o)
o strong reference
borrowed reference strong reference Py_NewRef()
strong reference
Py_DECREF()
NULL NULL Py_XINCREF()
o
3.12 :
void Py_XINCREF(PyObject *o)
Py_INCREF() o NULL
Py_XNewRef()
43
The Python/C API, 3.12.1
Py_INCREF(obj);
self->attr = obj;
self->attr = Py_NewRef(obj);
Py_INCREF()
3.10 .
PyObject *Py_XNewRef(PyObject *o)
ABI 3.10 . Py_NewRef() o NULL
o NULL NULL
3.10 .
void Py_DECREF(PyObject *o)
o strong reference
strong reference ( 0)
deallocation ( NULL)
strong reference
NULL NULL Py_XDECREF()
o
: Python __del__()
Python Py_DECREF()
Py_DECREF()
3.12 :
void Py_XDECREF(PyObject *o)
Py_DECREF() o NULL
Py_DECREF()
void Py_CLEAR(PyObject *o)
o strong reference NULL
Py_DECREF() NULL Py_DECREF()
NULL
3.12 :
44 Chapter 4.
The Python/C API, 3.12.1
Py_DECREF(dst);
dst = src;
Py_SETREF(dst, src);
45
The Python/C API, 3.12.1
46 Chapter 4.
CHAPTER 5
Python Python
POSIX errno :( ) C API
C API
NULL -1 ( : PyArg_* 1
0 )
NULL NULL
NULL
Python/C API
: sys.exc_info()
5.1
void PyErr_Clear()
ABI.
void PyErr_PrintEx(int set_sys_last_vars)
ABI. sys.stderr SystemExit
Python SystemExit
set_sys_last_vars sys.last_exc
sys.last_type, sys.last_value sys.last_traceback
,
3.12 : sys.last_exc
47
The Python/C API, 3.12.1
void PyErr_Print()
ABI. PyErr_PrintEx(1)
void PyErr_WriteUnraisable(PyObject *obj)
ABI. obj sys.unraisablehook()
sys.stderr
__del__()
obj obj
obj NULL
5.2
NULL
return
void PyErr_SetString(PyObject *type, const char *message)
ABI.
PyExc_RuntimeError strong reference ( Py_INCREF())
'utf-8'
void PyErr_SetObject(PyObject *type, PyObject *value)
ABI. PyErr_SetString()
Python
PyObject *PyErr_Format(PyObject *exception, const char *format, ...)
NULL ABI. NULL excep-
tion Python format
PyUnicode_FromFormat() format ASCII
PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
NULL ABI 3.5 . PyErr_Format()
va_list
3.5 .
void PyErr_SetNone(PyObject *type)
ABI. PyErr_SetObject(type, Py_None)
int PyErr_BadArgument()
ABI. PyErr_SetString(PyExc_TypeError, message) message
PyObject *PyErr_NoMemory()
NULL ABI. PyErr_SetNone(PyExc_MemoryError)
NULL return PyErr_NoMemory();
48 Chapter 5.
The Python/C API, 3.12.1
: Windows
5.2. 49
The Python/C API, 3.12.1
3.4 .
PyObject *PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char
*filename)
NULL ABI on Windows 3.7 .
PyErr_SetFromWindowsErrWithFilename()
: Windows
PyObject *PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
NULL ABI 3.7 . ImportError msg
name path NULL ImportError
name path
3.3 .
PyObject *PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name,
PyObject *path)
NULL ABI 3.6 . PyErr_SetImportError()
ImportError
3.6 .
void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
SyntaxError
SyntaxError
3.4 .
void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
ABI 3.7 . PyErr_SyntaxLocationObject() filename
filesystem encoding and error handler
3.2 .
void PyErr_SyntaxLocation(const char *filename, int lineno)
ABI. PyErr_SyntaxLocationEx() col_offset parameter
void PyErr_BadInternalCall()
ABI. PyErr_SetString(PyExc_SystemError, message) mes-
sage Python/C API
5.3
C Python warnings
sys.stderr
0
-1
Py_DECREF()
50 Chapter 5.
The Python/C API, 3.12.1
warnings -W
C API
int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno,
PyObject *module, PyObject *registry)
Python warnings.
warn_explicit() module registry
NULL
3.4 .
int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const
char *module, PyObject *registry)
ABI. PyErr_WarnExplicitObject() message module UTF-8
filename filesystem encoding and error handler
int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
ABI. PyErr_WarnEx() PyUnicode_FromFormat()
format ASCII
3.2 .
int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
ABI 3.6 . PyErr_WarnFormat() category
ResourceWarning source warnings.WarningMessage()
3.6 .
5.4
PyObject *PyErr_Occurred()
ABI. type (
PyErr_Set* PyErr_Restore() )
NULL Py_DECREF()
GIL
: PyErr_ExceptionMatches()
PyObject *PyErr_GetRaisedException(void)
ABI 3.12 .
5.4. 51
The Python/C API, 3.12.1
{
PyObject *exc = PyErr_GetRaisedException();
PyErr_SetRaisedException(exc);
}
:
PyErr_GetHandledException()
3.12 .
void PyErr_SetRaisedException(PyObject *exc)
ABI 3.12 . exc
: exc
3.12 .
void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
ABI. 3.12 : PyErr_GetRaisedException()
NULL
NULL
{
PyObject *type, *value, *traceback;
PyErr_Fetch(&type, &value, &traceback);
: PyErr_Fetch()
52 Chapter 5.
The Python/C API, 3.12.1
PyErr_Fetch() *exc
*val
: __traceback__
:
if (tb != NULL) {
PyException_SetTraceback(val, tb);
}
PyObject *PyErr_GetHandledException(void)
ABI 3.11 . sys.exception()
NULL
Does not modify the interpreter’s exception state.
:
PyErr_SetHandledException()
3.11 .
void PyErr_SetHandledException(PyObject *exc)
ABI 3.11 . sys.exception()
NULL
:
PyErr_GetHandledException()
3.11 .
void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
ABI 3.7 . sys.exc_info()
NULL
PyErr_GetHandledException()
:
PyErr_SetExcInfo()
3.3 .
void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
ABI 3.7 . sys.exc_info()
NULL
PyErr_SetHandledException()
:
PyErr_GetExcInfo()
3.3 .
3.11 : type traceback NULL
value
5.4. 53
The Python/C API, 3.12.1
5.5
int PyErr_CheckSignals()
ABI. Python
Python
signal Python
0 Python
-1 (
PyErr_CheckSignals() )
Python 0
( Ctrl-C) C
void PyErr_SetInterrupt()
ABI. SIGINT
PyErr_SetInterruptEx(SIGINT)
: GIL C
signum -1 0
: GIL C
3.10 .
int PySignal_SetWakeupFd(int fd)
fd
-1 Python signal.set_wakeup_fd()
fd
3.5 : Windows
54 Chapter 5.
The Python/C API, 3.12.1
5.6 Exception
5.7
API
5.6. Exception 55
The Python/C API, 3.12.1
orig orig
ExceptionGroup None
3.12 .
5.8 Unicode
C Unicode
PyObject *PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length,
Py_ssize_t start, Py_ssize_t end, const char *reason)
ABI. UnicodeDecodeError encoding, object,
length, start, end reason encoding reason UTF-8
PyObject *PyUnicodeDecodeError_GetEncoding(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetEncoding(PyObject *exc)
ABI. encoding
PyObject *PyUnicodeDecodeError_GetObject(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetObject(PyObject *exc)
PyObject *PyUnicodeTranslateError_GetObject(PyObject *exc)
ABI. object
int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
ABI. start *start start NULL
0 -1
int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
ABI. start start 0 -1
int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
ABI. end *end end NULL 0
-1
int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
ABI. end end 0 -1
PyObject *PyUnicodeDecodeError_GetReason(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetReason(PyObject *exc)
PyObject *PyUnicodeTranslateError_GetReason(PyObject *exc)
ABI. reason
int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
ABI. reason reason 0 -1
56 Chapter 5.
The Python/C API, 3.12.1
5.9
C
Python
tp_call
int Py_EnterRecursiveCall(const char *where)
ABI 3.9 . C
USE_STACKCHECK PyOS_CheckStack() OS
MemoryError
RecursionError
5.10
C Python
1
PyExc_BaseException BaseException
Page 58, 1
PyExc_Exception Exception
Page 58, 1
PyExc_ArithmeticError ArithmeticError
PyExc_AssertionError AssertionError
PyExc_AttributeError AttributeError
PyExc_BlockingIOError BlockingIOError
PyExc_BrokenPipeError BrokenPipeError
PyExc_BufferError BufferError
PyExc_ChildProcessError ChildProcessError
5.9. 57
The Python/C API, 3.12.1
1–
C Python
PyExc_ConnectionAbortedError
ConnectionAbortedError
PyExc_ConnectionError ConnectionError
PyExc_ConnectionRefusedError
ConnectionRefusedError
PyExc_ConnectionResetError
ConnectionResetError
PyExc_EOFError EOFError
PyExc_FileExistsError FileExistsError
PyExc_FileNotFoundError FileNotFoundError
PyExc_FloatingPointError FloatingPointError
PyExc_GeneratorExit GeneratorExit
PyExc_ImportError ImportError
PyExc_IndentationError IndentationError
PyExc_IndexError IndexError
PyExc_InterruptedError InterruptedError
PyExc_IsADirectoryError IsADirectoryError
PyExc_KeyError KeyError
PyExc_KeyboardInterrupt KeyboardInterrupt
Page 58, 1
PyExc_LookupError LookupError
PyExc_MemoryError MemoryError
PyExc_ModuleNotFoundErrorModuleNotFoundError
PyExc_NameError NameError
PyExc_NotADirectoryError NotADirectoryError
PyExc_NotImplementedErrorNotImplementedError
Page 58, 1
PyExc_OSError OSError
PyExc_OverflowError OverflowError
PyExc_PermissionError PermissionError
PyExc_ProcessLookupError ProcessLookupError
PyExc_RecursionError RecursionError
PyExc_ReferenceError ReferenceError
PyExc_RuntimeError RuntimeError
PyExc_StopAsyncIteration StopAsyncIteration
PyExc_StopIteration StopIteration
PyExc_SyntaxError SyntaxError
PyExc_SystemError SystemError
PyExc_SystemExit SystemExit
PyExc_TabError TabError
PyExc_TimeoutError TimeoutError
PyExc_TypeError TypeError
PyExc_UnboundLocalError UnboundLocalError
PyExc_UnicodeDecodeError UnicodeDecodeError
PyExc_UnicodeEncodeError UnicodeEncodeError
PyExc_UnicodeError UnicodeError
PyExc_UnicodeTranslateError
UnicodeTranslateError
PyExc_ValueError ValueError
PyExc_ZeroDivisionError ZeroDivisionError
58 Chapter 5.
The Python/C API, 3.12.1
3.6 : PyExc_ModuleNotFoundError.
PyExc_OSError:
C
PyExc_EnvironmentError
PyExc_IOError
2
PyExc_WindowsError
3.3 :
5.11
C Python
3
PyExc_Warning Warning
PyExc_BytesWarning BytesWarning
PyExc_DeprecationWarning DeprecationWarning
PyExc_FutureWarning FutureWarning
PyExc_ImportWarning ImportWarning
PyExc_PendingDeprecationWarning PendingDeprecationWarning
PyExc_ResourceWarning ResourceWarning
PyExc_RuntimeWarning RuntimeWarning
PyExc_SyntaxWarning SyntaxWarning
PyExc_UnicodeWarning UnicodeWarning
PyExc_UserWarning UserWarning
3.2 : PyExc_ResourceWarning.
2 Windows MS_WINDOWS
3
5.11. 59
The Python/C API, 3.12.1
60 Chapter 5.
CHAPTER 6
C C Python
C Python
6.1
3.7 .
void PyOS_AfterFork_Parent()
ABI on platforms with fork() 3.7 .
fork()
fork()
61
The Python/C API, 3.12.1
3.7 .
void PyOS_AfterFork_Child()
ABI on platforms with fork() 3.7 .
fork()
Python fork()
3.7 .
:
os.register_at_fork() PyOS_BeforeFork(),
PyOS_AfterFork_Parent() PyOS_AfterFork_Child() Python
void PyOS_AfterFork()
ABI on platforms with fork().
Python
3.7 : PyOS_AfterFork_Child()
int PyOS_CheckStack()
ABI on platforms with USE_STACKCHECK 3.7 .
USE_STACKCHECK Microsoft Visual
C++ Windows USE_STACKCHECK
will be defined automatically; you should never change the definition in your own code.
PyOS_sighandler_t PyOS_getsig(int i)
ABI. i sigaction() signal()
PyOS_sighandler_t void (*)(int)
62 Chapter 6.
The Python/C API, 3.12.1
PyMem_RawFree()
size NULL null *size
NULL size NULL *size
(size_t)-1 (size_t)-2
filesystem encoding and error handler PyConfig_Read() : PyConfig
filesystem_encoding filesystem_errors
C
Py_EncodeLocale()
:
PyUnicode_DecodeFSDefaultAndSize() PyUnicode_DecodeLocaleAndSize()
3.5 .
3.7 : Python UTF-8 UTF-8
3.8 : Windows PyPreConfig.legacy_windows_fs_encoding
UTF-8
char *Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
ABI 3.7 . filesystem encoding and error
handler surrogateescape U+DC80..U+DCFF
0x80..0xFF
PyMem_Free()
NULL
error_pos NULL *error_pos (size_t)-1
:
PyUnicode_EncodeFSDefault() PyUnicode_EncodeLocale()
3.5 .
3.7 : Python UTF-8 UTF-8
3.8 : Windows PyPreConfig.legacy_windows_fs_encoding
UTF-8
6.1. 63
The Python/C API, 3.12.1
6.2
sys C sys
3.11 .
void PySys_AddWarnOptionUnicode(PyObject *unicode)
ABI. API PyConfig.warnoptions
Python
unicode sys.warnoptions
CPython Py_Initialize()
warnings Unicode
3.11 .
void PySys_SetPath(const wchar_t *path)
ABI. API PyConfig.
module_search_paths PyConfig.module_search_paths_set Python
sys.path path
( Unix : Windows ;)
3.11 .
void PySys_WriteStdout(const char *format, ...)
ABI. format sys.stdout
64 Chapter 6.
The Python/C API, 3.12.1
3.2 .
void PySys_FormatStderr(const char *format, ...)
ABI. PySys_FormatStdout() sys.stderr stderr
3.2 .
void PySys_AddXOption(const wchar_t *s)
ABI 3.7 . API PyConfig.
xoptions Python
s -X PySys_GetXOptions()
Py_Initialize()
3.2 .
3.11 .
PyObject *PySys_GetXOptions()
ABI 3.7 . -X sys.
_xoptions NULL
3.2 .
int PySys_Audit(const char *event, const char *format, ...)
format N
Py_BuildValue()
N
# Py_ssize_t PY_SSIZE_T_CLEAN
sys.audit() Python
3.8 .
3.8.2 : Py_ssize_t #
int PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
hook
API
userData
Python
Py_Initialize()
Exception
6.2. 65
The Python/C API, 3.12.1
sys.addaudithook
Exception
3.8 .
6.3
6.4
NULL
__import__()
fromlist
PyImport_ImportModule()
66 Chapter 6.
The Python/C API, 3.12.1
:
PyImport_ImportModule() name
3.3 .
PyObject *PyImport_AddModule(const char *name)
ABI. PyImport_AddModuleObject() UTF-8
Unicode object.
PyObject *PyImport_ExecCodeModule(const char *name, PyObject *co)
ABI. package.module
Python compile()
NULL name
sys.modules name PyImport_ExecCodeModule()
sys.modules sys.modules
name package.module
6.4. 67
The Python/C API, 3.12.1
PyImport_ExecCodeModuleEx() PyImport_ExecCodeModuleWithPathnames()
3.12 : __cached__ __loader__ ModuleSpec
PyObject *PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
ABI. PyImport_ExecCodeModule() pathname
NULL __file__
PyImport_ExecCodeModuleWithPathnames()
PyObject *PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
PyObject *cpathname)
ABI 3.7 . PyImport_ExecCodeModuleEx()
cpathname NULL __cached__
3.3 .
3.12 : __cached__ ModuleSpec
PyObject *PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, const char
*pathname, const char *cpathname)
ABI. PyImport_ExecCodeModuleObject() name,
pathname cpathname UTF-8 pathname NULL
cpathname
3.2 .
3.3 : imp.source_from_cache()
3.12 : imp
long PyImport_GetMagicNumber()
ABI. Python .pyc
-1
3.3 : -1
const char *PyImport_GetMagicTag()
ABI. PEP 3147 Python sys.
implementation.cache_tag
3.2 .
PyObject *PyImport_GetModuleDict()
ABI. ( sys.modules)
68 Chapter 6.
The Python/C API, 3.12.1
PyImport_ImportModule() ---
3.3 .
3.4 : __file__
int PyImport_ImportFrozenModule(const char *name)
ABI. PyImport_ImportFrozenModuleObject() UTF-8
Unicode
struct _frozen
freeze ( Python
Tools/freeze/) Include/import.h :
struct _frozen {
const char *name;
const unsigned char *code;
int size;
bool is_package;
};
6.5 marshal
C marshal
marshal
0 1 marshal
2 Py_MARSHAL_VERSION
2
6.5. marshal 69
The Python/C API, 3.12.1
marshal
long PyMarshal_ReadLongFromFile(FILE *file)
FILE* C long 32
long
(EOFError) -1
int PyMarshal_ReadShortFromFile(FILE *file)
FILE* C short 16
short
(EOFError) -1
PyObject *PyMarshal_ReadObjectFromFile(FILE *file)
FILE* Python
(EOFError, ValueError TypeError) NULL
PyObject *PyMarshal_ReadLastObjectFromFile(FILE *file)
FILE* Python
PyMarshal_ReadObjectFromFile()
6.6
extending-index
PyArg_ParseTuple() PyArg_ParseTupleAndKeywords()
PyArg_Parse()
70 Chapter 6.
The Python/C API, 3.12.1
6.6.1
0 Python
()
Python [] C ( )
unicode
C :
• y* s* Py_buffer
Py_BEGIN_ALLOW_THREADS
PyBuffer_Release()
• es, es#, et et#
PyMem_Free()
• str bytes-like object bytes const char
* Python
PyBufferProcs.bf_releasebuffer
NULL bytearray bytes memoryview
bf_releasebuffer
: # s# y# PY_SSIZE_T_CLEAN Python.h
Python 3.9 PY_SSIZE_T_CLEAN Py_ssize_t
int
: bytes-like objects C
O& PyUnicode_FSConverter()
6.6. 71
The Python/C API, 3.12.1
PyArg_ParseTuple()
*buffer PyMem_Free()
*buffer NULL
*buffer PyMem_Free()
*buffer NULL PyArg_ParseTuple()
*buffer_length
ValueError
*buffer_length NUL
et# (str, bytes bytearray) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]
es#
72 Chapter 6.
The Python/C API, 3.12.1
3.1 : Py_CLEANUP_SUPPORTED
p (bool) [int] ( ) C true/false
1 0 Python truth Python
3.3 .
6.6. 73
The Python/C API, 3.12.1
| Python C
PyArg_ParseTuple() C ( )
$ PyArg_ParseTupleAndKeywords() only Python
| $
3.3 .
: (PyArg_ParseTuple()
)
; : ;
Python
arg PyArg_Parse*
PyArg_Parse*
API
int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[],
...)
ABI. keywords
NULL positional-only parameters true;
false
3.6 : positional-only parameters
int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char
*keywords[], va_list vargs)
ABI. PyArg_ParseTupleAndKeywords() va_list
int PyArg_ValidateKeywordArguments(PyObject*)
ABI.
PyArg_ParseTupleAndKeywords()
3.2 .
74 Chapter 6.
The Python/C API, 3.12.1
int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
ABI.
METH_VARARGS
args min max min max
PyObject*
args args
args
_weakref :
static PyObject *
weakref_ref(PyObject *self, PyObject *args)
{
PyObject *object;
PyObject *callback = NULL;
PyObject *result = NULL;
PyArg_UnpackTuple() PyArg_ParseTuple():
PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
6.6.2
Py_BuildValue()
None
0 1
s s#
Py_BuildValue()
malloc() Py_BuildValue()
Py_BuildValue() free()
() Python
[] C ( )
( s#)
6.6. 75
The Python/C API, 3.12.1
SystemError NULL
76 Chapter 6.
The Python/C API, 3.12.1
6.7
6.7. 77
The Python/C API, 3.12.1
6.8
PyObject *PyEval_GetBuiltins(void)
ABI.
PyObject *PyEval_GetLocals(void)
ABI.
NULL
PyObject *PyEval_GetGlobals(void)
ABI.
NULL
PyFrameObject *PyEval_GetFrame(void)
ABI. NULL
PyThreadState_GetFrame()
const char *PyEval_GetFuncName(PyObject *func)
ABI. func func
const char *PyEval_GetFuncDesc(PyObject *func)
ABI. func ”()”, ” constructor”, ”
instance” ” object” PyEval_GetFuncName() func
6.9
78 Chapter 6.
The Python/C API, 3.12.1
encoding
KeyError NULL
PyObject *PyCodec_Encoder(const char *encoding)
ABI. encoding
PyObject *PyCodec_Decoder(const char *encoding)
ABI. encoding
PyObject *PyCodec_IncrementalEncoder(const char *encoding, const char *errors)
ABI. encoding IncrementalEncoder
PyObject *PyCodec_IncrementalDecoder(const char *encoding, const char *errors)
ABI. encoding IncrementalDecoder
PyObject *PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors)
ABI. encoding StreamReader
PyObject *PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors)
ABI. encoding StreamWriter
UnicodeEncodeError, UnicodeDecodeError
UnicodeTranslateError
Unicode
/
0 -1
6.9. 79
The Python/C API, 3.12.1
API
/tmp/perf-$pid.map
PyUnstable_WritePerfMapEntry()
PyUnstable_WritePerfMapEntry()
API
/tmp/perf-$pid.map
:
# address size name
7f3529fcf759 b py::bar:/run/t.py
80 Chapter 6.
The Python/C API, 3.12.1
void PyUnstable_PerfMapState_Fini(void)
API
82 Chapter 6.
CHAPTER 7
Python
Python
PyList_New()
NULL
7.1
PyObject *Py_NotImplemented
NotImplemented
Py_RETURN_NOTIMPLEMENTED
C Py_NotImplemented NotImplemented
strong reference
int PyObject_Print(PyObject *o, FILE *fp, int flags)
o fp -1 flags
Py_PRINT_RAW str() repr()
int PyObject_HasAttr(PyObject *o, PyObject *attr_name)
ABI. o attr_name 1 0 Python
hasattr(o, attr_name)
: __getattr__() __getattribute__()
PyObject_GetAttr()
83
The Python/C API, 3.12.1
NULL
3.3 .
int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)
ABI 3.7 . __dict__
3.3 .
PyObject **_PyObject_GetDictPtr(PyObject *obj)
obj __dict__ __dict__ NULL
PyObject_GetAttr()
84 Chapter 7.
The Python/C API, 3.12.1
: o1 o2 PyObject_RichCompareBool() Py_EQ 1
Py_NE 0
type __bases__
7.1. 85
The Python/C API, 3.12.1
inst __class__
cls __bases__
86 Chapter 7.
The Python/C API, 3.12.1
NULL
3.12 .
Py_ssize_t PyType_GetTypeDataSize(PyTypeObject *cls)
ABI 3.12 . cls PyObject_GetTypeData()
-PyType_Spec.basicsize (
memset())
cls PyType_Spec.basicsize Python
3.12 .
void *PyObject_GetItemData(PyObject *o)
Py_TPFLAGS_ITEMS_AT_END
NULL o Py_TPFLAGS_ITEMS_AT_END
TypeError
3.12 .
7.2
CPython tp_call
7.2.1 tp_call
tp_call :
dict Python
callable(*args, **kwargs) args*
*kwargs* *NULL
*tp_call* tp_new tp_init
PyObject_Call() API
7.2. 87
The Python/C API, 3.12.1
7.2.2 Vectorcall
3.9 .
vectorcall PEP 590
vectorcall CPython
tp_call ( PyObject_Call())
vectorcall tp_call
tp_call PyVectorcall_Call() :
: Vectorcall tp_call
PY_VECTORCALL_ARGUMENTS_OFFSET
self
3.8 .
vectorcall call API
PyObject_Vectorcall()
88 Chapter 7.
The Python/C API, 3.12.1
Vectorcall API
PyVectorcall_NARGS
3.8 .
vectorcallfunc PyVectorcall_Function(PyObject *op)
*op* vectorcall
*NULL* *op* vectorcall
op vectorcall PyVectorcall_Function(op) !=
NULL
3.9 .
PyObject *PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict)
ABI 3.12 . * * vectorcallfunc
dict
tp_call tp_call
Py_TPFLAGS_HAVE_VECTORCALL tp_call
3.8 .
7.2.3 API
Python
tp_call vectorcall
7.2. 89
The Python/C API, 3.12.1
NULL
Python callable(*args)
PyObject* PyObject_CallFunctionObjArgs()
3.4 : The types of name and format were changed from char *.
PyObject *PyObject_CallFunctionObjArgs(PyObject *callable, ...)
ABI. Python callable PyObject*
NULL
NULL
Python callable(arg1, arg2, ...)
90 Chapter 7.
The Python/C API, 3.12.1
NULL
PyObject *PyObject_CallMethodNoArgs(PyObject *obj, PyObject *name)
Python obj name Python
NULL
3.9 .
PyObject *PyObject_CallMethodOneArg(PyObject *obj, PyObject *name, PyObject *arg)
Python obj arg name Python
NULL
3.9 .
PyObject *PyObject_Vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
ABI 3.12 . Python callable
vectorcallfunc callable vectorcall callable vec-
torcall
NULL
3.9 .
PyObject *PyObject_VectorcallDict(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwdict)
callable vectorcall kwdict
args
3.9 .
PyObject *PyObject_VectorcallMethod(PyObject *name, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
ABI 3.12 . vectorcall Python
name args[0] args args[1]
nargsf args[0]
args[0] PY_VECTORCALL_ARGUMENTS_OFFSET
PyObject_Vectorcall()
Py_TPFLAGS_METHOD_DESCRIPTOR
args vector
NULL
3.9 .
7.2. 91
The Python/C API, 3.12.1
7.2.4 API
7.3
92 Chapter 7.
The Python/C API, 3.12.1
7.3. 93
The Python/C API, 3.12.1
94 Chapter 7.
The Python/C API, 3.12.1
7.4
7.4. 95
The Python/C API, 3.12.1
7.5
96 Chapter 7.
The Python/C API, 3.12.1
: __getitem__()
PyObject_GetItem()
: __getitem__() str
PyMapping_GetItemString()
7.6
7.6. 97
The Python/C API, 3.12.1
if (iterator == NULL) {
/* propagate error */
}
Py_DECREF(iterator);
if (PyErr_Occurred()) {
/* propagate error */
}
else {
/* continue doing useful work */
}
type PySendResult
PyIter_Send()
3.10 .
PySendResult PyIter_Send(PyObject *iter, PyObject *arg, PyObject **presult)
ABI 3.10 . arg iter :
• PYGEN_RETURN presult
• PYGEN_NEXT presult
• PYGEN_ERROR presult NULL
3.10 .
7.7
Python bytes
bytearray array.array
Python C :
•
Buffer Object Structures
•
98 Chapter 7.
The Python/C API, 3.12.1
bytes bytearray
array.array
write()
write() readinto()
• PyObject_GetBuffer()
• PyArg_ParseTuple() ( ) y*, w* or s*
PyBuffer_Release()
7.7.1
( buffers ) Python
Python
C
Python PyObject C
PyObject_GetBuffer()
type Py_buffer
ABI ( ) 3.11 .
void *buf
strides
contiguous
PyObject *obj
PyBuffer_Release()
NULL C-API
PyMemoryView_FromBuffer() PyBuffer_FillInfo()
temporary NULL
Py_ssize_t len
product(shape) * itemsize
((char *)buf)[0] up to
((char *)buf)[len-1] PyBUF_SIMPLE
PyBUF_WRITABLE
int readonly
PyBUF_WRITABLE
Py_ssize_t itemsize
struct.calcsize() NULL format
7.7. 99
The Python/C API, 3.12.1
Py_ssize_t *shape
Py_ssize_t ndim n shape[0] *
... * shape[ndim-1] * itemsize len
Shape shape[n] >= 0 shape[n] == 0
complex arrays
shape
Py_ssize_t *strides
Py_ssize_t ndim
Stride
strides[n] <= 0 complex arrays
strides
Py_ssize_t *suboffsets
ndim Py_ssize_t suboffsets[n] >= 0 n
suboffset suboffset
NULL
Python Imaging Library (PIL) complex arrays
suboffsets
void *internal
PyBUF_MAX_NDIM 64
7.7.2
PyObject_GetBuffer()
flags
Py_buffer
100 Chapter 7.
The Python/C API, 3.12.1
PyBUF_WRITABLE
readonly
PyBUF_FORMAT
format
NULL
PyBUF_WRITABLE PyBUF_SIMPLE 0
PyBUF_WRITABLE
PyBUF_FORMAT PyBUF_SIMPLE B(
)
PyBUF_INDIRECT
NULL
PyBUF_STRIDES
NULL NULL
PyBUF_ND
C Fortran C-
NULL C
PyBUF_C_CONTIGUOUS
NULL F
PyBUF_F_CONTIGUOUS
NULL C F
PyBUF_ANY_CONTIGUOUS
7.7. 101
The Python/C API, 3.12.1
U PyBuffer_IsContiguous()
format
U 0
PyBUF_FULL
U 1 0
PyBUF_FULL_RO
NULL U 0
PyBUF_RECORDS
NULL U 1 0
PyBUF_RECORDS_RO
NULL U 0 NULL
PyBUF_STRIDED
NULL U 1 0 NULL
PyBUF_STRIDED_RO
7.7.3
NumPy-
buf
102 Chapter 7.
The Python/C API, 3.12.1
( )
return False
if offset < 0 or offset+itemsize > memlen:
return False
if any(v % itemsize for v in strides):
return False
if ndim <= 0:
return ndim == 0 and not shape and not strides
if 0 in shape:
return True
PIL-
PIL
C char v[2][2][3] 2 2 char
(*v[2])[2][3] buf
char x[2][3]
n N-D NULL
void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
Py_ssize_t *suboffsets, Py_ssize_t *indices) {
char *pointer = (char*)buf;
int i;
for (i = 0; i < ndim; i++) {
pointer += strides[i] * indices[i];
if (suboffsets[i] >=0 ) {
pointer = *((char**)pointer) + suboffsets[i];
}
}
return (void*)pointer;
}
7.7.4
7.7. 103
The Python/C API, 3.12.1
PyObject_GetBuffer()
Py_ssize_t PyBuffer_SizeFromFormat(const char *format)
ABI 3.11 . format itemsize -1
3.9 .
int PyBuffer_IsContiguous(const Py_buffer *view, char order)
ABI 3.11 . view C order 'C' Fortran order
'F' contiguous order 'A' 1 0
void *PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices)
ABI 3.11 . view indices indices
view->ndim
int PyBuffer_FromContiguous(const Py_buffer *view, const void *buf, Py_ssize_t len, char fort)
ABI 3.11 . buf len view fort 'C' 'F'
C Fortran 0 -1
int PyBuffer_ToContiguous(void *buf, const Py_buffer *src, Py_ssize_t len, char order)
ABI 3.11 . src len buf order
'C' 'F' 'A' C Fortran 0
-1
len != src->len
int PyObject_CopyData(PyObject *dest, PyObject *src)
ABI 3.11 . src dest C Fortran
0 -1
void PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize,
char order)
ABI 3.11 . contiguous ( order 'C' C
order 'F' Fortran ) strides
int PyBuffer_FillInfo(Py_buffer *view, PyObject *exporter, void *buf, Py_ssize_t len, int readonly, int
flags)
ABI 3.11 . len buf
readonly bug
flags flag view buf
flag PyBUF_WRITABLE
view->obj exporter 0 BufferError
view->obj NULL -1
getbufferproc exporter
flags exporter NULL
7.8
3.0 .
Python 2 API Python 3
2.x
PyObject_GetBuffer() ( PyArg_ParseTuple() y* w*
) PyBuffer_Release()
104 Chapter 7.
The Python/C API, 3.12.1
PyObject_GetBuffer()
int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len)
ABI. obj 0
buffer buffer_len -1 TypeError
7.8. 105
The Python/C API, 3.12.1
106 Chapter 7.
CHAPTER 8
Python
Python
PyDict_Check() Python
:
NULL NULL
8.1
Python None
8.1.1
type PyTypeObject
API ( ). C built-in
PyTypeObject PyType_Type
ABI. type type object Python type
int PyType_Check(PyObject *o)
o
0
int PyType_CheckExact(PyObject *o)
o
0
unsigned int PyType_ClearCache()
ABI.
107
The Python/C API, 3.12.1
3.2 .
3.4 : unsigned long long
PyObject *PyType_GetDict(PyTypeObject *type)
(cls.__dict__)
tp_dict
PyObject_GetAttr()
tp_dict
3.12 .
void PyType_Modified(PyTypeObject *type)
ABI.
3.12 .
int PyType_HasFeature(PyTypeObject *o, int feature)
o feature
int PyType_IS_GC(PyTypeObject *o)
Py_TPFLAGS_HAVE_GC
108 Chapter 8.
The Python/C API, 3.12.1
: GC Py_TPFLAGS_HAVE_GC
GC
Py_TPFLAGS_HAVE_GC GC tp_traverse
3.11 .
PyObject *PyType_GetQualName(PyTypeObject *type)
ABI 3.11 .
__qualname__
3.11 .
void *PyType_GetSlot(PyTypeObject *type, int slot)
ABI 3.4 . NULL
NULL
PyType_Slot.slot slot
3.4 .
3.10 : PyType_GetSlot()
PyObject *PyType_GetModule(PyTypeObject *type)
ABI 3.10 . PyType_FromModuleAndSpec()
TypeError NULL
PyType_GetModule(Py_TYPE(self)) Py_TYPE(self)
PyCMethod
PyType_GetModuleByDef()
PyCMethod
3.9 .
8.1. 109
The Python/C API, 3.12.1
API
1
0
3.12 .
PyType_Ready()
type() class
type ( ) PyType_From* :
• __new__() ( type.__new__)
• __init__()
• __init_subclass__()
• __set_name__()
110 Chapter 8.
The Python/C API, 3.12.1
3.12 .
PyObject *PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)
ABI 3.10 . PyType_FromMetaclass(NULL,
module, spec, bases)
3.9 .
3.10 : bases NULL tp_doc
3.12 :
type
tp_new tp_new
Python 3.14+
PyObject *PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
ABI 3.3 . PyType_FromMetaclass(NULL, NULL,
spec, bases)
3.3 .
3.12 :
type
tp_new tp_new
Python 3.14+
PyObject *PyType_FromSpec(PyType_Spec *spec)
ABI. PyType_FromMetaclass(NULL, NULL, spec,
NULL)
3.12 : Py_tp_base[s]
type
tp_new tp_new
Python 3.14+
type PyType_Spec
ABI ( ).
const char *name
PyTypeObject.tp_name
int basicsize
PyTypeObject.tp_basicsize
tp_basicsize
PyObject_GetTypeData()
3.12 :
int itemsize
PyTypeObject.tp_itemsize
tp_itemsize
tp_itemsize
itemsize:
• ( tp_itemsize)
• PyType_Spec.basicsize
• PyType_Spec.basicsize
8.1. 111
The Python/C API, 3.12.1
• Py_TPFLAGS_ITEMS_AT_END
unsigned int flags
PyTypeObject.tp_flags
Py_TPFLAGS_HEAPTYPE PyType_FromSpecWithBases()
PyType_Slot *slots
PyType_Slot {0, NULL}
ID
type PyType_Slot
ABI ( ). ID
int slot
ID
ID PyTypeObject, PyNumberMethods,
PySequenceMethods, PyMappingMethods PyAsyncMethods
Py_ :
• Py_tp_dealloc PyTypeObject.tp_dealloc
• Py_nb_add PyNumberMethods.nb_add
• Py_sq_length PySequenceMethods.sq_length
offset PyType_Slot :
• tp_weaklistoffset ( Py_TPFLAGS_MANAGED_WEAKREF)
• tp_dictoffset ( Py_TPFLAGS_MANAGED_DICT)
• tp_vectorcall_offset ( PyMemberDef
"__vectorcalloffset__")
MANAGED ( vectorcall Python
3.12 ) Py_tp_members offset PyMemberDef
documentation
:
• tp_vectorcall ( tp_new / tp_init)
• : tp_dict, tp_mro, tp_cache, tp_subclasses tp_weaklist
Py_tp_bases Py_tp_base
PyType_FromSpecWithBases() bases
3.9 : PyBufferProcs API
3.11 : bf_getbuffer bf_releasebuffer API
void *pfunc
Py_tp_doc NULL
112 Chapter 8.
The Python/C API, 3.12.1
8.1.2 None
8.2
8.2.1
PyObject *PyLong_FromLong(long v)
ABI. v PyLongObject NULL
-5 256
int
PyObject *PyLong_FromUnsignedLong(unsigned long v)
ABI. C unsigned long PyLongObject
NULL
PyObject *PyLong_FromSsize_t(Py_ssize_t v)
ABI. C Py_ssize_t PyLongObject
NULL
PyObject *PyLong_FromSize_t(size_t v)
ABI. C size_t PyLongObject
NULL
PyObject *PyLong_FromLongLong(long long v)
ABI. C long long PyLongObject
NULL
8.2. 113
The Python/C API, 3.12.1
114 Chapter 8.
The Python/C API, 3.12.1
8.2. 115
The Python/C API, 3.12.1
API
op 1 0
PyUnstable_Long_CompactValue() PyLong_As*
int.to_bytes()
API
op PyUnstable_Long_IsCompact()
8.2.2
PyTypeObject PyBool_Type
ABI. PyTypeObject Python Python bool
116 Chapter 8.
The Python/C API, 3.12.1
Py_RETURN_TRUE
Py_True
PyObject *PyBool_FromLong(long v)
ABI. Py_True Py_False v
8.2.3
type PyFloatObject
C PyObject Python
PyTypeObject PyFloat_Type
ABI. C PyTypeObject Python Python
float
int PyFloat_Check(PyObject *p)
PyFloatObject PyFloatObject
8.2. 117
The Python/C API, 3.12.1
Pack C double
Unpack C double (2, 4 or 8)
IEEE 754 2
IEEE 754 binary16 4 (32 ) IEEE 754 binary32 8
IEEE 754 INF NaN ( )
IEEE INF NaN
IEEE 754 IEEE
IEEE
3.11 .
2, 4 8 p le int (
p+1, p+3 p+6 p+7) (
p) PY_BIG_ENDIAN 1
0
: 0 -1 ( OverflowError)
IEEE :
• x NaN
• -0.0 +0.0
int PyFloat_Pack2(double x, unsigned char *p, int le)
C double IEEE 754 binary16
int PyFloat_Pack4(double x, unsigned char *p, int le)
C double IEEE 754 binary32
int PyFloat_Pack8(double x, unsigned char *p, int le)
C double IEEE 754 binary64
2, 4 8 p le int (
p+1, p+3 p+6 p+7) (
p) PY_BIG_ENDIAN 1
0
: double -1.0 PyErr_Occurred() (
OverflowError)
IEEE NaN
double PyFloat_Unpack2(const unsigned char *p, int le)
IEEE 754 binary16 C double
double PyFloat_Unpack4(const unsigned char *p, int le)
IEEE 754 binary32 C double
double PyFloat_Unpack8(const unsigned char *p, int le)
IEEE 754 binary64 C double
118 Chapter 8.
The Python/C API, 3.12.1
8.2.4
API
type Py_complex
Python C
typedef struct {
double real;
double imag;
} Py_complex;
Python
type PyComplexObject
C PyObject Python
PyTypeObject PyComplex_Type
ABI. PyTypeObject Python Python
complex
int PyComplex_Check(PyObject *p)
PyComplexObject PyComplexObject
PyObject *PyComplex_FromCComplex(Py_complex v)
C Py_complex Python
8.2. 119
The Python/C API, 3.12.1
8.3
; Python
8.3.1 bytes
TypeError
type PyBytesObject
PyObject Python
PyTypeObject PyBytes_Type
ABI. PyTypeObject Python Python bytes
120 Chapter 8.
The Python/C API, 3.12.1
%% %
%c int C
%d int printf("%d").1
%u unsigned int printf("%u").Page 121, 1
%ld printf("%ld").Page 121, 1
%lu unsigned long printf("%lu").Page 121, 1
%zd Py_ssize_t printf("%zd").Page 121, 1
%zu size_t printf("%zu").Page 121, 1
%i int printf("%i").Page 121, 1
%x int printf("%x").Page 121, 1
%s const char* null C
%p const void* C printf("%p")
0x printf
PyBytes_FromStringAndSize(NULL, size)
o PyBytes_AsString() NULL
TypeError
char *PyBytes_AS_STRING(PyObject *string)
PyBytes_AsString()
int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)
ABI. buffer length null obj
length NULL -1
ValueError
obj length
PyBytes_FromStringAndSize(NULL, size)
obj PyBytes_AsStringAndSize()
-1 TypeError
3.5 : TypeError
void PyBytes_Concat(PyObject **bytes, PyObject *newpart)
ABI. *bytes bytes newpart
bytes bytes
*bytes NULL
1 d u ld lu zd zu i x 0
8.3. 121
The Python/C API, 3.12.1
lvalue
*bytes 0 *bytes
*bytes *bytes NULL
MemoryError -1
8.3.2
type PyByteArrayObject
PyObject Python
PyTypeObject PyByteArray_Type
ABI. Python bytearray PyTypeObject Python bytearray
API
122 Chapter 8.
The Python/C API, 3.12.1
8.3.3 Unicode
Unicode
Unicode
API C Unicode
int PyUnicode_Check(PyObject *obj)
obj Unicode Unicode
8.3. 123
The Python/C API, 3.12.1
3.3 .
Py_UCS1 *PyUnicode_1BYTE_DATA(PyObject *unicode)
Py_UCS2 *PyUnicode_2BYTE_DATA(PyObject *unicode)
Py_UCS4 *PyUnicode_4BYTE_DATA(PyObject *unicode)
UCS1 UCS2 UCS4
PyUnicode_KIND()
3.3 .
PyUnicode_1BYTE_KIND
PyUnicode_2BYTE_KIND
PyUnicode_4BYTE_KIND
PyUnicode_KIND()
3.3 .
3.12 : PyUnicode_WCHAR_KIND
int PyUnicode_KIND(PyObject *unicode)
PyUnicode see above) that indicate how many bytes per character
this Unicode unicode Unicode
3.3 .
void *PyUnicode_DATA(PyObject *unicode)
Unicode unicode Unicode
3.3 .
void PyUnicode_WRITE(int kind, void *data, Py_ssize_t index, Py_UCS4 value)
data ( PyUnicode_DATA() )
kind data index
( 0 ) value
3.3 .
Py_UCS4 PyUnicode_READ(int kind, void *data, Py_ssize_t index)
data ( PyUnicode_DATA() )
3.3 .
Py_UCS4 PyUnicode_READ_CHAR(PyObject *unicode, Py_ssize_t index)
Unicode unicode
PyUnicode_READ()
3.3 .
124 Chapter 8.
The Python/C API, 3.12.1
3.3 .
int PyUnicode_IsIdentifier(PyObject *unicode)
ABI. 1 identifiers
0
3.9 : Py_FatalError()
Unicode
Unicode Python
C
int Py_UNICODE_ISSPACE(Py_UCS4 ch)
ch 1 0
int Py_UNICODE_ISLOWER(Py_UCS4 ch)
ch 1 0
int Py_UNICODE_ISUPPER(Py_UCS4 ch)
ch 1 0
int Py_UNICODE_ISTITLE(Py_UCS4 ch)
ch 1 0
int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)
ch 1 0
int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)
ch 1 0
int Py_UNICODE_ISDIGIT(Py_UCS4 ch)
ch 1 0
int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)
ch 1 0
int Py_UNICODE_ISALPHA(Py_UCS4 ch)
ch 1 0
int Py_UNICODE_ISALNUM(Py_UCS4 ch)
ch 1 0
int Py_UNICODE_ISPRINTABLE(Py_UCS4 ch)
ch 1 “0“ Unicode
”Other” ”Separator” ASCII (0x20) (
repr()
sys.stdout sys.stderr )
API
Py_UCS4 Py_UNICODE_TOLOWER(Py_UCS4 ch)
ch
3.3 :
8.3. 125
The Python/C API, 3.12.1
Unicode
Unicode API
PyObject *PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
Unicode maxchar
127, 255, 65535, 1114111
Unicode
3.3 .
PyObject *PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
kind Unicode
PyUnicode_1BYTE_KIND PyUnicode_KIND() buffer
1, 2 4 size
buffer buffer UCS4
(PyUnicode_4BYTE_KIND) UCS1 UCS1
(PyUnicode_1BYTE_KIND)
3.3 .
PyObject *PyUnicode_FromStringAndSize(const char *str, Py_ssize_t size)
ABI. str Unicode UTF-8
SystemError:
126 Chapter 8.
The Python/C API, 3.12.1
• size < 0,
• str NULL size > 0
3.12 : str == NULL size > 0
PyObject *PyUnicode_FromString(const char *str)
ABI. UTF-8 str Unicode
1. '%'
2.
3. '*' ( )
int
4. '.' ( ) '*' ( )
int
5.
6.
0
- 0
(d, i, o, u, x, or X) ( int):
s V l const wchar_t*
:
8.3. 127
The Python/C API, 3.12.1
% %
d, i C
u C
o C
x C
X C
c int
s const char* null C
const wchar_t*
p const void* C
printf("%p") 0x
printf
A PyObject* ascii()
U PyObject* Unicode
V PyObject*, const Unicode ( NULL) C
char* const NULL
wchar_t*
S PyObject* PyObject_Str()
R PyObject* PyObject_Repr()
: "%s" "%V" (
PyObject* NULL) wchar_t ( l) "%A",
"%U", "%S", "%R" "%V" ( PyObject* NULL)
: C printf() 0 (d, i, u, o, x, or X)
128 Chapter 8.
The Python/C API, 3.12.1
Unicode TypeError
API NULL
Py_ssize_t PyUnicode_GetLength(PyObject *unicode)
ABI 3.7 . Unicode
3.3 .
Py_ssize_t PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t
from_start, Py_ssize_t how_many)
Unicode
memcpy() -1
3.3 .
Py_ssize_t PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char)
fill_char unicode[start:start+length]
fill_char 1
-1
3.3 .
int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 character)
ABI 3.7 . PyUnicode_New()
Unicode
unicode Unicode
3.3 .
Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
ABI 3.7 . unicode Unicode
PyUnicode_READ_CHAR()
3.3 .
PyObject *PyUnicode_Substring(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
ABI 3.7 . unicode start ( )
end ( )
3.3 .
Py_UCS4 *PyUnicode_AsUCS4(PyObject *unicode, Py_UCS4 *buffer, Py_ssize_t buflen, int copy_null)
ABI 3.7 . unicode UCS4
copy_null NULL buflen unicode
SystemError buffer
3.3 .
Py_UCS4 *PyUnicode_AsUCS4Copy(PyObject *unicode)
ABI 3.7 . unicode PyMem_Malloc() UCS4
NULL MemoryError
3.3 .
8.3. 129
The Python/C API, 3.12.1
Python UTF-8
:
The Py_DecodeLocale()
3.3 .
3.7 : surrogateescape
Android Py_DecodeLocale() surrogateescape
strict
PyObject *PyUnicode_DecodeLocale(const char *str, const char *errors)
ABI 3.7 . PyUnicode_DecodeLocaleAndSize()
strlen()
3.3 .
PyObject *PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
ABI 3.7 . Unicode Android VxWorks
UTF-8 "strict"
"surrogateescape" (PEP 383) errors NULL "strict"
bytes unicode
PyUnicode_EncodeFSDefault() filesystem encoding and error handler
Python UTF-8
:
Py_EncodeLocale()
3.3 .
3.7 : surrogateescape
Android Py_EncodeLocale() surrogateescape
strict
130 Chapter 8.
The Python/C API, 3.12.1
PyUnicode_DecodeLocaleAndSize()
:
The Py_DecodeLocale()
3.6 :
PyObject *PyUnicode_DecodeFSDefault(const char *str)
ABI. filesystem encoding and error handler
PyUnicode_DecodeFSDefaultAndSize()
3.6 :
PyObject *PyUnicode_EncodeFSDefault(PyObject *unicode)
ABI. filesystem encoding and error handler Unicode
bytes bytes
PyUnicode_EncodeLocale()
:
Py_EncodeLocale()
3.2 .
3.6 :
wchar_t
wchar_t:
PyObject *PyUnicode_FromWideChar(const wchar_t *wstr, Py_ssize_t size)
ABI. size wchar_t wstr Unicode
-1 size wcslen() NULL
Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *wstr, Py_ssize_t size)
ABI. Unicode wchar_t wstr size wchar_t
wchar_t
-1 wchar_t*
wchar_t* wchar_t*
C
wchar_t *PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size)
ABI 3.7 . Unicode
size NULL *size
8.3. 131
The Python/C API, 3.12.1
wchar_t C size
NULL wchar_t* ValueError
PyMem_New PyMem_Free()
NULL *size MemoryError
3.2 .
3.7 : size NULL wchar_t* ValueError
Python C
API:
PyObject *PyUnicode_Decode(const char *str, Py_ssize_t size, const char *encoding, const char *errors)
ABI. str size Unicode
encoding errors str() Python
NULL
PyObject *PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors)
ABI. Unicode Python
encoding errors Unicode encode()
Python NULL
UTF-8
UTF-8 API:
PyObject *PyUnicode_DecodeUTF8(const char *str, Py_ssize_t size, const char *errors)
ABI. UTF-8 str size
Unicode NULL
PyObject *PyUnicode_DecodeUTF8Stateful(const char *str, Py_ssize_t size, const char *errors,
Py_ssize_t *consumed)
ABI. consumed NULL
PyUnicode_DecodeUTF8() consumed NULL UTF-8
consumed
PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
ABI. UTF-8 Unicode Python
”strict” NULL
132 Chapter 8.
The Python/C API, 3.12.1
NULL size
Unicode UTF-8
Unicode
3.3 .
3.7 : const char * char *
3.10 : API
const char *PyUnicode_AsUTF8(PyObject *unicode)
PyUnicode_AsUTF8AndSize()
3.3 .
3.7 : const char * char *
UTF-32
UTF-32 API:
PyObject *PyUnicode_DecodeUTF32(const char *str, Py_ssize_t size, const char *errors, int *byteorder)
ABI. UTF-32 size
Unicode errors ( NULL) ”strict”
byteorder NULL :
*byteorder (BOM)
BOM Unicode *byteorder -1 1
*byteorder
byteorder NULL
NULL
PyObject *PyUnicode_DecodeUTF32Stateful(const char *str, Py_ssize_t size, const char *errors, int
*byteorder, Py_ssize_t *consumed)
ABI. consumed NULL
PyUnicode_DecodeUTF32() consumed NULL
PyUnicode_DecodeUTF32Stateful() UTF-32
consumed
8.3. 133
The Python/C API, 3.12.1
UTF-16
UTF-16 API:
PyObject *PyUnicode_DecodeUTF16(const char *str, Py_ssize_t size, const char *errors, int *byteorder)
ABI. UTF-16 size
Unicode errors ( NULL) ”strict”
byteorder NULL :
*byteorder (BOM)
BOM Unicode *byteorder -1 1
( \ufeff \ufffe )
*byteorder
byteorder NULL
NULL
PyObject *PyUnicode_DecodeUTF16Stateful(const char *str, Py_ssize_t size, const char *errors, int
*byteorder, Py_ssize_t *consumed)
ABI. consumed NULL
PyUnicode_DecodeUTF16() consumed NULL
PyUnicode_DecodeUTF16Stateful() UTF-16
consumed
PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
ABI. UTF-16 Python
BOM ”strict” NULL
UTF-7
UTF-7 API:
PyObject *PyUnicode_DecodeUTF7(const char *str, Py_ssize_t size, const char *errors)
ABI. UTF-7 str size Unicode
NULL
PyObject *PyUnicode_DecodeUTF7Stateful(const char *str, Py_ssize_t size, const char *errors,
Py_ssize_t *consumed)
ABI. consumed NULL
PyUnicode_DecodeUTF7() consumed NULL UTF-7 base-
64 consumed
134 Chapter 8.
The Python/C API, 3.12.1
Unicode-Escape
Raw-Unicode-Escape
Latin-1
ASCII
8.3. 135
The Python/C API, 3.12.1
encodings
__getitem__()
API:
PyObject *PyUnicode_DecodeCharmap(const char *str, Py_ssize_t length, PyObject *mapping, const char
*errors)
ABI. mapping str size
Unicode NULL
mapping NULL Latin-1 mapping 0 255
Unicode Unicode None
-- LookupError None 0xFFFE '\ufffe'
Windows MBCS
136 Chapter 8.
The Python/C API, 3.12.1
NULL -1
PyObject *PyUnicode_Concat(PyObject *left, PyObject *right)
ABI. Unicode
PyObject *PyUnicode_Split(PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
ABI. Unicode sep
NULL
maxsplit
PyObject *PyUnicode_Splitlines(PyObject *unicode, int keepends)
ABI. Unicode Unicode
CRLF keepends 0
PyObject *PyUnicode_Join(PyObject *separator, PyObject *seq)
ABI. separator Unicode
Py_ssize_t PyUnicode_Tailmatch(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int
direction)
ABI. substr (direction == -1 , direction == 1 )
unicode[start:end] 1 0 -1
Py_ssize_t PyUnicode_Find(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int
direction)
ABI. direction (direction == 1 direction == -1 )
substr unicode[start:end] -1
-2
Py_ssize_t PyUnicode_FindChar(PyObject *unicode, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int
direction)
ABI 3.7 . direction (direction == 1 direction == -1
) ch unicode[start:end]
-1 -2
3.3 .
3.7 : start end unicode[start:end]
Py_ssize_t PyUnicode_Count(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
ABI. substr unicode[start:end]
-1
PyObject *PyUnicode_Replace(PyObject *unicode, PyObject *substr, PyObject *replstr, Py_ssize_t
maxcount)
ABI. unicode substr replstr maxcount
Unicode maxcount == -1
8.3. 137
The Python/C API, 3.12.1
)
PyObject *PyUnicode_InternFromString(const char *str)
ABI. PyUnicode_FromString()
PyUnicode_InternInPlace() Unicode
8.3.4
type PyTupleObject
PyObject Python
PyTypeObject PyTuple_Type
ABI. PyTypeObject Python Python tuple
138 Chapter 8.
The Python/C API, 3.12.1
: o
: o PyTuple_SetItem()
pos
0 *p *p
*p -1 *p NULL MemoryError
SystemError
8.3.5
namedtuple() C
8.3. 139
The Python/C API, 3.12.1
: o
: o
140 Chapter 8.
The Python/C API, 3.12.1
8.3.6
type PyListObject
C PyObject Python
PyTypeObject PyList_Type
ABI. PyTypeObject Python Python
list
int PyList_Check(PyObject *p)
p list list
int PyList_CheckExact(PyObject *p)
p list list
PyObject *PyList_New(Py_ssize_t len)
ABI. len NULL
: len NULL C
PySequence_SetItem() API C PyList_SetItem()
Python
: item
: item PyList_SetItem()
list i
8.3. 141
The Python/C API, 3.12.1
8.4
8.4.1
type PyDictObject
PyObject Python
PyTypeObject PyDict_Type
ABI. Python PyTypeObject Python dict
142 Chapter 8.
The Python/C API, 3.12.1
: __hash__() __eq__()
PyDict_GetItemWithError()
8.4. 143
The Python/C API, 3.12.1
p
:
144 Chapter 8.
The Python/C API, 3.12.1
dict dict
-1
PyErr_WriteUnraisable() 0
0
API
3.12 .
8.4.2
8.4. 145
The Python/C API, 3.12.1
API
PyTypeObject PySet_Type
ABI. PyTypeObject Python set
PyTypeObject PyFrozenSet_Type
ABI. PyTypeObject Python frozenset
Python
Python
int PySet_Check(PyObject *p)
p set
int PyFrozenSet_Check(PyObject *p)
p frozenset
int PyAnySet_Check(PyObject *p)
p set frozenset
146 Chapter 8.
The Python/C API, 3.12.1
0 -1 key TypeError
MemoryError set set SystemError
set frozenset
int PySet_Discard(PyObject *set, PyObject *key)
ABI. 1 0
-1 KeyError key TypeError
Python discard() set
set SystemError
PyObject *PySet_Pop(PyObject *set)
ABI. set set
NULL KeyError set set
SystemError
int PySet_Clear(PyObject *set)
ABI. 0 set set
-1 SystemError
8.5 Function
8.5.1 Function
Python
type PyFunctionObject
C
PyTypeObject PyFunction_Type
PyTypeObject Python types.FunctionType Python
__module__ globals
defaults, annotations closure NULL __qualname__ co_qualname
148 Chapter 8.
The Python/C API, 3.12.1
Python
event PyFunction_EVENT_DESTROY
-1
PyErr_WriteUnraisable() 0
0
API
3.12 .
8.5.2
PyCFunction PyCFunction
PyMethod_New(func, NULL, class)
PyTypeObject PyInstanceMethod_Type
PyTypeObject Python Python
int PyInstanceMethod_Check(PyObject *o)
o ( PyInstanceMethod_Type)
NULL
PyObject *PyInstanceMethod_New(PyObject *func)
func func
8.5.3
PyTypeObject PyMethod_Type
PyTypeObject Python types.MethodType Python
8.5.4 Cell
Cell Cell
Cell
Cell Cell
Cell
type PyCellObject
Cell C
PyTypeObject PyCell_Type
Cell
int PyCell_Check(PyObject *ob)
ob cell ob NULL
PyObject *PyCell_New(PyObject *ob)
ob cell NULL
PyObject *PyCell_Get(PyObject *cell)
cell cell
PyObject *PyCell_GET(PyObject *cell)
cell cell cell NULL cell
150 Chapter 8.
The Python/C API, 3.12.1
8.5.5
CPython
type PyCodeObject
C
PyTypeObject PyCode_Type
PyTypeObject Python code
int PyCode_Check(PyObject *co)
co code
int PyCode_GetNumFree(PyCodeObject *co)
co
PyCodeObject *PyUnstable_Code_New(int argcount, int kwonlyargcount, int nlocals, int stacksize, int flags,
PyObject *code, PyObject *consts, PyObject *names, PyObject
*varnames, PyObject *freevars, PyObject *cellvars, PyObject
*filename, PyObject *name, PyObject *qualname, int firstlineno,
PyObject *linetable, PyObject *exceptiontable)
API
PyCode_NewEmpty()
PyUnstable_Code_New() Python
VM
3.11 : qualname exceptiontable
3.12 : PyCode_New C API
API
PyUnstable_Code_New() ”posonlyargcount”
PyUnstable_Code_New
3.8 : PyCode_NewWithPosOnlyArgs
3.11 : qualname exceptiontable
3.12 : PyUnstable_Code_NewWithPosOnlyArgs
Exception
3.11 .
PyObject *PyCode_GetVarnames(PyCodeObject *co)
Python getattr(co, 'co_varnames')
PyTupleObject NULL
3.11 .
PyObject *PyCode_GetCellvars(PyCodeObject *co)
Python getattr(co, 'co_cellvars')
PyTupleObject NULL
3.11 .
PyObject *PyCode_GetFreevars(PyCodeObject *co)
Python getattr(co, 'co_freevars')
PyTupleObject NULL
3.11 .
int PyCode_AddWatcher(PyCode_WatchCallback callback)
callback PyCode_ClearWatcher()
ID ID -1
3.12 .
int PyCode_ClearWatcher(int watcher_id)
PyCode_AddWatcher() watcher_id
0 watcher_id -1
3.12 .
type PyCodeEvent
: - PY_CODE_EVENT_CREATE -
PY_CODE_EVENT_DESTROY
3.12 .
typedef int (*PyCode_WatchCallback)(PyCodeEvent event, PyCodeObject *co)
event PY_CODE_EVENT_CREATE co
co co
152 Chapter 8.
The Python/C API, 3.12.1
event PY_CODE_EVENT_DESTROY
API
Python
-1
PyErr_WriteUnraisable() 0
0
API
3.12 .
8.5.6
API
PyCode_GetExtra
PyCode_SetExtra
free NULL: free NULL
PyObject Py_DecRef()
3.6 : _PyEval_RequestCodeExtraIndex
3.12 : PyUnstable_Eval_RequestCodeExtraIndex
API
int PyUnstable_Code_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
API
extra 0 -1
extra NULL 0
3.6 : _PyCode_GetExtra
3.12 : PyUnstable_Code_GetExtra API
API
extra 0 -1
3.6 : _PyCode_SetExtra
8.6
8.6.1
: Python OS
3.2 : name
int PyObject_AsFileDescriptor(PyObject *p)
ABI. p int
fileno()
-1
PyObject *PyFile_GetLine(PyObject *p, int n)
ABI. p.readline([n]) p p
readline() n 0
n 0 n
n 0
EOFError
int PyFile_SetOpenCodeHook(Py_OpenCodeHookFunction handler)
io.open_code()
PyObject *(*)(PyObject *path, void *userData)
path PyUnicodeObject
userData
Python
sys.modules
PyFile_SetOpenCodeHook()
-1
Py_Initialize()
setopencodehook
3.8 .
154 Chapter 8.
The Python/C API, 3.12.1
8.6.2
PyTypeObject PyModule_Type
ABI. C PyTypeObject Python Python
types.ModuleType
int PyModule_Check(PyObject *p)
p
int PyModule_CheckExact(PyObject *p)
p PyModule_Type
8.6. 155
The Python/C API, 3.12.1
PyModule_Create()
type PyModuleDef
ABI ( ).
PyModuleDef_Base m_base
PyModuleDef_HEAD_INIT
const char *m_name
m_size m_free
m_size -1
m_size
PEP 3121
PyMethodDef *m_methods
PyMethodDef NULL
PyModuleDef_Slot *m_slots
{0, NULL}
m_slots NULL
3.5 : 3.5 NULL :
inquiry m_reload
traverseproc m_traverse
NULL
Py_mod_exec m_size 0
PyModule_GetState() NULL
3.9 :
156 Chapter 8.
The Python/C API, 3.12.1
inquiry m_clear
NULL
Py_mod_exec m_size 0
PyModule_GetState() NULL
PyTypeObject.tp_clear
m_free
3.9 :
freefunc m_free
NULL
Py_mod_exec m_size 0
PyModule_GetState() NULL
3.9 :
: PyModule_Create()
PyModule_AddObjectRef()
Python
__new__() __init__()
sys.modules
Python
( PyModule_GetState() ) (
__dict__ PyType_FromSpec() )
(PyInit_modulename) m_slots
PyModuleDef PyModuleDef
8.6. 157
The Python/C API, 3.12.1
int slot
ID
void *value
ID
3.5 .
m_slots id 0
:
Py_mod_create
value :
PyObject *create_module(PyObject *spec, PyModuleDef *def)
Py_mod_create
Py_mod_create PyModule_New()
spec
PyModule_Type
PyModuleDef NULL m_traverse, m_clear, m_free
m_size Py_mod_create PyModule_Type
Py_mod_exec
Python
:
int exec_module(PyObject *module)
Py_mod_exec *m_slots*
Py_mod_multiple_interpreters
:
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED
Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED
GIL isolating-extensions-
howto
Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
GIL isolating-extensions-howto
158 Chapter 8.
The Python/C API, 3.12.1
Py_mod_multiple_interpreters
Py_mod_multiple_interpreters
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED
3.12 .
PEP:489
PyModule_FromDefAndSpec PyModule_ExecDef
PyObject *PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec)
def ModuleSpec spec
PyModule_FromDefAndSpec2() module_api_version PYTHON_API_VERSION
3.5 .
PyObject *PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version)
ABI 3.7 . def spec
API module_api_version
RuntimeWarning
: PyModule_FromDefAndSpec()
3.5 .
int PyModule_ExecDef(PyObject *module, PyModuleDef *def)
ABI 3.7 . *def* Py_mod_exec
3.5 .
int PyModule_SetDocString(PyObject *module, const char *docstring)
ABI 3.7 . *module* *docstring*
PyModule_Create PyModule_FromDefAndSpec PyModuleDef
3.5 .
int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions)
ABI 3.7 . NULL *functions* *module*
PyMethodDef C
Python
PyModule_Create PyModule_FromDefAndSpec PyModuleDef
3.5 .
8.6. 159
The Python/C API, 3.12.1
0 -1
*value* NULL NULL
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (obj == NULL) {
return -1;
}
int res = PyModule_AddObjectRef(module, "spam", obj);
Py_DECREF(obj);
return res;
}
obj NULL:
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
int res = PyModule_AddObjectRef(module, "spam", obj);
Py_XDECREF(obj);
return res;
}
: PyModule_AddObject() value
*value* Py_DECREF()
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (obj == NULL) {
return -1;
}
( )
160 Chapter 8.
The Python/C API, 3.12.1
( )
if (PyModule_AddObject(module, "spam", obj) < 0) {
Py_DECREF(obj);
return -1;
}
// PyModule_AddObject() stole a reference to obj:
// Py_DECREF(obj) is not needed here
return 0;
}
obj NULL:
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (PyModule_AddObject(module, "spam", obj) < 0) {
Py_XDECREF(obj);
return -1;
}
// PyModule_AddObject() stole a reference to obj:
// Py_DECREF(obj) is not needed here
return 0;
}
8.6. 161
The Python/C API, 3.12.1
Python PyState_AddModule
PyState_FindModule
GIL
0 -1
3.3 .
int PyState_RemoveModule(PyModuleDef *def)
ABI 3.3 . def 0
-1
GIL
3.3 .
8.6.3
Python __getitem__()
PyTypeObject PySeqIter_Type
ABI. PySeqIter_New() iter()
162 Chapter 8.
The Python/C API, 3.12.1
8.6.4
PyTypeObject PyProperty_Type
ABI.
PyObject *PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)
ABI.
PyObject *PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)
ABI.
PyObject *PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)
ABI.
PyObject *PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)
8.6.5
PyTypeObject PySlice_Type
ABI. Python slice
int PySlice_Check(PyObject *ob)
ob slice ob NULL
PyObject *PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
ABI. start, stop step
slice NULL
None NULL
int PySlice_GetIndices(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t
*step)
ABI. slice start, stop step length length
0 -1 None
-1
8.6. 163
The Python/C API, 3.12.1
0 -1
: PySlice_Unpack()
PySlice_AdjustIndices()
// return error
}
Python
3.6.1 .
164 Chapter 8.
The Python/C API, 3.12.1
Ellipsis
PyObject *Py_Ellipsis
Python Ellipsis Py_None immortal
3.12 : Py_Ellipsis
8.6.6 MemoryView
memoryview C Python
PyObject *PyMemoryView_FromObject(PyObject *obj)
ABI. memoryview obj
memoryview /
/
PyObject *PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags)
ABI 3.7 . mem memoryview
flags PyBUF_READ PyBUF_WRITE .
3.3 .
PyObject *PyMemoryView_FromBuffer(const Py_buffer *view)
ABI 3.11 . view memoryview
PyMemoryView_FromMemory()
PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)
ABI. memoryview contiguous
’C’ ’F’ortran order memoryview
memoryview bytes
int PyMemoryView_Check(PyObject *obj)
obj memoryview memoryview
8.6.7
Python
8.6. 165
The Python/C API, 3.12.1
: borrowed reference
Py_INCREF()
8.6.8 Capsule
using-capsules
3.1 .
type PyCapsule
PyObject void* Python
C C C
C API
type PyCapsule_Destructor
ABI. Capsule
PyCapsule_New() PyCapsule_Destructor
int PyCapsule_CheckExact(PyObject *p)
PyCapsule
PyObject *PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor)
ABI. pointer PyCapsule pointer
NULL
NULL
name NULL C NULL
capsule destructor
166 Chapter 8.
The Python/C API, 3.12.1
0
int PyCapsule_SetContext(PyObject *capsule, void *context)
ABI. capsule context
0
int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor)
ABI. capsule destructor
0
int PyCapsule_SetName(PyObject *capsule, const char *name)
ABI. capsule name NULL capsule
capsule name NULL
0
int PyCapsule_SetPointer(PyObject *capsule, void *pointer)
ABI. capsule pointer NULL
0
8.6. 167
The Python/C API, 3.12.1
8.6.9
type PyFrameObject
API ( ). C
168 Chapter 8.
The Python/C API, 3.12.1
:pep:523
struct _PyInterpreterFrame
3.11 .
PyObject *PyUnstable_InterpreterFrame_GetCode(struct _PyInterpreterFrame *frame);
API
strong reference
3.12 .
int PyUnstable_InterpreterFrame_GetLasti(struct _PyInterpreterFrame *frame);
API
3.12 .
int PyUnstable_InterpreterFrame_GetLine(struct _PyInterpreterFrame *frame);
API
-1
3.12 .
8.6. 169
The Python/C API, 3.12.1
8.6.10
Python
PyGen_New() PyGen_NewWithQualName()
type PyGenObject
C
PyTypeObject PyGen_Type
8.6.11
3.5 .
async
type PyCoroObject
C
PyTypeObject PyCoro_Type
8.6.12
3.7.1 :
// in 3.7.0:
PyContext *PyContext_New(void);
// in 3.7.1+:
PyObject *PyContext_New(void);
170 Chapter 8.
The Python/C API, 3.12.1
bpo-34762
3.7 .
contextvars C API
type PyContext
contextvars.Context C
type PyContextVar
contextvars.ContextVar C
type PyContextToken
contextvars.Token C
PyTypeObject PyContext_Type
context
PyTypeObject PyContextVar_Type
context variable
PyTypeObject PyContextToken_Type
context variable token
8.6. 171
The Python/C API, 3.12.1
• default_value NULL;
• var NULL
• NULL
NULL
PyObject *PyContextVar_Set(PyObject *var, PyObject *value)
var value
NULL
int PyContextVar_Reset(PyObject *var, PyObject *token)
var token PyContextVar_Set()
0 -1
8.6.13 DateTime
datetime
datetime.h ( Python.h ) PyDateTime_IMPORT
C
PyDateTimeAPI
type PyDateTime_Date
PyObject Python
type PyDateTime_DateTime
PyObject Python
type PyDateTime_Time
PyObject Python
type PyDateTime_Delta
PyObject
PyTypeObject PyDateTime_DateType
PyTypeObject Python Python datetime.date
PyTypeObject PyDateTime_DateTimeType
PyTypeObject Python Python datetime.datetime
PyTypeObject PyDateTime_TimeType
PyTypeObject Python Python datetime.time
PyTypeObject PyDateTime_DeltaType
PyTypeObject Python Python
datetime.timedelta
PyTypeObject PyDateTime_TZInfoType
PyTypeObject Python Python datetime.tzinfo
UTC :
PyObject *PyDateTime_TimeZone_UTC
UTC datetime.timezone.utc
3.7 .
172 Chapter 8.
The Python/C API, 3.12.1
PyObject *PyTime_FromTimeAndFold(int hour, int minute, int second, int usecond, int fold)
hour, minute, second, microsecond fold datetime.time
3.6 .
8.6. 173
The Python/C API, 3.12.1
3.7 .
PyObject *PyTimeZone_FromOffsetAndName(PyObject *offset, PyObject *name)
datetime.timezone offset
name
3.7 .
PyDateTime_Date
( PyDateTime_DateTime) NULL :
int PyDateTime_GET_YEAR(PyDateTime_Date *o)
174 Chapter 8.
The Python/C API, 3.12.1
8.6.14
...
static PyMethodDef my_obj_methods[] = {
// Other methods.
...
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"}
...
}
8.6. 175
The Python/C API, 3.12.1
:
__class_getitem__()
3.9 .
PyTypeObject Py_GenericAliasType
ABI 3.9 . Py_GenericAlias() C Python
types.GenericAlias
3.9 .
176 Chapter 8.
CHAPTER 9
Python
9.1 Python
Python
•
– PyImport_AppendInittab()
– PyImport_ExtendInittab()
– PyInitFrozenExtensions()
– PyMem_SetAllocator()
– PyMem_SetupDebugHooks()
– PyObject_SetArenaAllocator()
– Py_SetPath()
– Py_SetProgramName()
– Py_SetPythonHome()
– Py_SetStandardStreamEncoding()
– PySys_AddWarnOption()
– PySys_AddXOption()
– PySys_ResetWarnOptions()
•
– Py_IsInitialized()
– PyMem_GetAllocator()
– PyObject_GetArenaAllocator()
177
The Python/C API, 3.12.1
– Py_GetBuildInfo()
– Py_GetCompiler()
– Py_GetCopyright()
– Py_GetPlatform()
– Py_GetVersion()
•
– Py_DecodeLocale()
•
– PyMem_RawMalloc()
– PyMem_RawRealloc()
– PyMem_RawCalloc()
– PyMem_RawFree()
: Py_Initialize(): Py_EncodeLocale(),
Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), Py_GetProgramFullPath(),
Py_GetPythonHome(), Py_GetProgramName() PyEval_InitThreads()
9.2
Python
-b Py_BytesWarningFlag
1 -bb Py_BytesWarningFlag 2.
int Py_BytesWarningFlag
API PyConfig.bytes_warning Python
-b
3.12 .
int Py_DebugFlag
API PyConfig.parser_debug Python
-d PYTHONDEBUG
3.12 .
int Py_DontWriteBytecodeFlag
API PyConfig.write_bytecode Python
, Python .pyc
-B PYTHONDONTWRITEBYTECODE
3.12 .
178 Chapter 9.
The Python/C API, 3.12.1
int Py_FrozenFlag
API PyConfig.pathconfig_warnings Python
Py_GetPath()
_freeze_importlib frozenmain
3.12 .
int Py_HashRandomizationFlag
API PyConfig.hash_seed PyConfig.
use_hash_seed Python
PYTHONHASHSEED 1
PYTHONHASHSEED
3.12 .
int Py_IgnoreEnvironmentFlag
API PyConfig.use_environment Python
-i
3.12 .
int Py_IsolatedFlag
API PyConfig.isolated Python
Python. sys.path site-packages
-I
3.4 .
3.12 .
int Py_LegacyWindowsFSEncodingFlag
API PyPreConfig.legacy_windows_fs_encoding
Python
mbcs “replace“ UTF-8
surrogatepass filesystem encoding and error handler
PYTHONLEGACYWINDOWSFSENCODING 1
PEP 529
9.2. 179
The Python/C API, 3.12.1
: Windows
3.12 .
int Py_LegacyWindowsStdioFlag
API PyConfig.legacy_windows_stdio Python
site-packages sys.path
-s -I PYTHONNOUSERSITE
3.12 .
int Py_OptimizeFlag
API PyConfig.optimization_level Python
-O PYTHONOPTIMIZE
3.12 .
int Py_QuietFlag
API PyConfig.quiet Python
-q
3.2 .
3.12 .
int Py_UnbufferedStdioFlag
API PyConfig.buffered_stdio Python
stdout stderr
-u PYTHONUNBUFFERED
3.12 .
180 Chapter 9.
The Python/C API, 3.12.1
int Py_VerboseFlag
API PyConfig.verbose Python
2
-v PYTHONVERBOSE
3.12 .
9.3
void Py_Initialize()
ABI. Python Python Python/C
API Python
(sys.modules) builtins __main__
sys (sys.path) sys.argv
PySys_SetArgvEx() ( Py_FinalizeEx() )
Py_InitializeFromConfig() Python
Py_Initialize()
Py_FinalizeEx()
cpython._PySys_ClearAuditHooks
3.6 .
void Py_Finalize()
ABI. Py_FinalizeEx()
9.3. 181
The Python/C API, 3.12.1
9.4
Py_FinalizeEx() Py_Initialize()
0
3.4 .
3.11 .
void Py_SetProgramName(const wchar_t *name)
ABI. API PyConfig.program_name Python
Py_Initialize()
main() argv[0] Py_GetPath()
Python 'python'
Python
Py_DecodeLocale() wchar_t*
3.11 .
wchar_t *Py_GetProgramName()
ABI. Py_SetProgramName()
Py_Initialize() NULL
3.10 : Py_Initialize() NULL
wchar_t *Py_GetPrefix()
ABI. Return the prefix for installed platform-independent files. This is derived through a number of
complicated rules from the program name set with Py_SetProgramName() and some environment vari-
ables; for example, if the program name is '/usr/local/bin/python', the prefix is '/usr/local'.
The returned string points into static storage; the caller should not modify its value. This corresponds to the
prefix variable in the top-level Makefile and the --prefix argument to the configure script at
build time. The value is available to Python code as sys.prefix. It is only useful on Unix. See also the
next function.
Py_Initialize() NULL
3.10 : Py_Initialize() NULL
wchar_t *Py_GetExecPrefix()
ABI. Return the exec-prefix for installed platform-dependent files. This is derived through a number
of complicated rules from the program name set with Py_SetProgramName() and some environment
variables; for example, if the program name is '/usr/local/bin/python', the exec-prefix is '/usr/
local'. The returned string points into static storage; the caller should not modify its value. This corresponds
182 Chapter 9.
The Python/C API, 3.12.1
to the exec_prefix variable in the top-level Makefile and the --exec-prefix argument to the
configure script at build time. The value is available to Python code as sys.exec_prefix. It is only
useful on Unix.
Background: The exec-prefix differs from the prefix when platform dependent files (such as executables and
shared libraries) are installed in a different directory tree. In a typical installation, platform dependent files
may be installed in the /usr/local/plat subtree while platform independent may be installed in /usr/
local.
Generally speaking, a platform is a combination of hardware and software families, e.g. Sparc machines run-
ning the Solaris 2.x operating system are considered the same platform, but Intel machines running Solaris 2.x
are another platform, and Intel machines running Linux are yet another platform. Different major revisions of
the same operating system generally also form different platforms. Non-Unix operating systems are a different
story; the installation strategies on those systems are so different that the prefix and exec-prefix are meaning-
less, and set to the empty string. Note that compiled Python bytecode files are platform independent (but not
independent from the Python version by which they were compiled!).
System administrators will know how to configure the mount or automount programs to share /usr/
local between platforms while having /usr/local/plat be a different filesystem for each platform.
Py_Initialize() NULL
3.10 : Py_Initialize() NULL
wchar_t *Py_GetProgramFullPath()
ABI. Return the full program name of the Python executable; this is computed as a side-effect of
deriving the default module search path from the program name (set by Py_SetProgramName() above).
The returned string points into static storage; the caller should not modify its value. The value is available to
Python code as sys.executable.
Py_Initialize() NULL
3.10 : Py_Initialize() NULL
wchar_t *Py_GetPath()
ABI. Return the default module search path; this is computed from the program name (set by
Py_SetProgramName() above) and some environment variables. The returned string consists of a series
of directory names separated by a platform dependent delimiter character. The delimiter character is ':'
on Unix and macOS, ';' on Windows. The returned string points into static storage; the caller should not
modify its value. The list sys.path is initialized with this value on interpreter startup; it can be (and usually
is) modified later to change the search path for loading modules.
Py_Initialize() NULL
3.10 : Py_Initialize() NULL
void Py_SetPath(const wchar_t*)
ABI 3.7 . API PyConfig.
module_search_paths PyConfig.module_search_paths_set Python
Set the default module search path. If this function is called before Py_Initialize(), then
Py_GetPath() won’t attempt to compute a default search path but uses the one provided instead. This
is useful if Python is embedded by an application that has full knowledge of the location of all modules. The
path components should be separated by the platform dependent delimiter character, which is ':' on Unix
and macOS, ';' on Windows.
This also causes sys.executable to be set to the program full path (see
Py_GetProgramFullPath()) and for sys.prefix and sys.exec_prefix to be empty. It
is up to the caller to modify these if required after calling Py_Initialize().
Use Py_DecodeLocale() to decode a bytes string to get a wchar_* string.
The path argument is copied internally, so the caller may free it after the call completes.
3.8 : The program full path is now used for sys.executable, instead of the program name.
3.11 .
9.4. 183
The Python/C API, 3.12.1
The first word (up to the first space character) is the current Python version; the first characters are the major
and minor version separated by a period. The returned string points into static storage; the caller should not
modify its value. The value is available to Python code as sys.version.
See also the Py_Version constant.
const char *Py_GetPlatform()
ABI. Return the platform identifier for the current platform. On Unix, this is formed from the
”official” name of the operating system, converted to lower case, followed by the major revision number; e.g.,
for Solaris 2.x, which is also known as SunOS 5.x, the value is 'sunos5'. On macOS, it is 'darwin'. On
Windows, it is 'win'. The returned string points into static storage; the caller should not modify its value.
The value is available to Python code as sys.platform.
const char *Py_GetCopyright()
ABI. Return the official copyright string for the current Python version, for example
'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'
Python sys.copyright
"[GCC 2.7.2.2]"
Python sys.version
Python sys.version
184 Chapter 9.
The Python/C API, 3.12.1
See also PyConfig.orig_argv and PyConfig.argv members of the Python Initialization Configura-
tion.
: It is recommended that applications embedding the Python interpreter for purposes other than executing
a single script pass 0 as updatepath, and update sys.path themselves if desired. See CVE-2008-5983.
On versions before 3.1.3, you can achieve the same effect by manually popping the first sys.path element
after having called PySys_SetArgv(), for example using:
3.1.3 .
3.11 .
void PySys_SetArgv(int argc, wchar_t **argv)
ABI. This API is kept for backward compatibility: setting PyConfig.argv and PyConfig.
parse_argv should be used instead, see Python Initialization Configuration.
This function works like PySys_SetArgvEx() with updatepath set to 1 unless the python interpreter
was started with the -I.
Use Py_DecodeLocale() to decode a bytes string to get a wchar_* string.
See also PyConfig.orig_argv and PyConfig.argv members of the Python Initialization Configura-
tion.
3.4 : The updatepath value depends on -I.
3.11 .
void Py_SetPythonHome(const wchar_t *home)
ABI. This API is kept for backward compatibility: setting PyConfig.home should be used
instead, see Python Initialization Configuration.
Set the default ”home” directory, that is, the location of the standard Python libraries. See PYTHONHOME for
the meaning of the argument string.
The argument should point to a zero-terminated character string in static storage whose contents will not change
for the duration of the program’s execution. No code in the Python interpreter will change the contents of this
storage.
Use Py_DecodeLocale() to decode a bytes string to get a wchar_* string.
3.11 .
wchar_t *Py_GetPythonHome()
ABI. Return the default ”home”, that is, the value set by a previous call to
Py_SetPythonHome(), or the value of the PYTHONHOME environment variable if it is set.
Py_Initialize() NULL
3.10 : Py_Initialize() NULL
9.4. 185
The Python/C API, 3.12.1
9.5
The Python interpreter is not fully thread-safe. In order to support multi-threaded Python programs, there’s a global
lock, called the global interpreter lock or GIL, that must be held by the current thread before it can safely access
Python objects. Without the lock, even the simplest operations could cause problems in a multi-threaded program:
for example, when two threads simultaneously increment the reference count of the same object, the reference count
could end up being incremented only once instead of twice.
Therefore, the rule exists that only the thread that has acquired the GIL may operate on Python objects or call Python/C
API functions. In order to emulate concurrency of execution, the interpreter regularly tries to switch threads (see
sys.setswitchinterval()). The lock is also released around potentially blocking I/O operations like reading
or writing a file, so that other Python threads can run in the meantime.
The Python interpreter keeps some thread-specific bookkeeping information inside a data structure called
PyThreadState. There’s also one global variable pointing to the current PyThreadState: it can be retrieved
using PyThreadState_Get().
9.5.1 GIL
GIL
Py_BEGIN_ALLOW_THREADS
... Do some blocking I/O operation ...
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
Py_END_ALLOW_THREADS
:
PyThreadState *_save;
_save = PyEval_SaveThread();
... Do some blocking I/O operation ...
PyEval_RestoreThread(_save);
Here is how these functions work: the global interpreter lock is used to protect the pointer to the current thread state.
When releasing the lock and saving the thread state, the current thread state pointer must be retrieved before the
lock is released (since another thread could immediately acquire the lock and store its own thread state in the global
variable). Conversely, when acquiring the lock and restoring the thread state, the lock must be acquired before storing
the thread state pointer.
: Calling system I/O functions is the most common use case for releasing the GIL, but it can also be useful before
calling long-running computations which don’t need access to Python objects, such as compression or cryptographic
functions operating over memory buffers. For example, the standard zlib and hashlib modules release the GIL
when compressing or hashing data.
186 Chapter 9.
The Python/C API, 3.12.1
9.5.2 Python
When threads are created using the dedicated Python APIs (such as the threading module), a thread state is
automatically associated to them and the code showed above is therefore correct. However, when threads are created
from C (for example by a third-party library with its own thread management), they don’t hold the GIL, nor is there
a thread state structure for them.
If you need to call Python code from these threads (often this will be part of a callback API provided by the afore-
mentioned third-party library), you must first register these threads with the interpreter by creating a thread state
data structure, then acquiring the GIL, and finally storing their thread state pointer, before you can start using the
Python/C API. When you are done, you should reset the thread state pointer, release the GIL, and finally free the
thread state data structure.
The PyGILState_Ensure() and PyGILState_Release() functions do all of the above automatically.
The typical idiom for calling into Python from a C thread is:
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
Note that the PyGILState_* functions assume there is only one global interpreter (created auto-
matically by Py_Initialize()). Python supports the creation of additional interpreters (using
Py_NewInterpreter()), but mixing multiple interpreters and the PyGILState_* API is unsupported.
Another important thing to note about threads is their behaviour in the face of the C fork() call. On most systems
with fork(), after a process forks only the thread that issued the fork will exist. This has a concrete impact both
on how locks must be handled and on all stored state in CPython’s runtime.
The fact that only the ”current” thread remains means any locks held by other threads will never be released. Python
solves this for os.fork() by acquiring the locks it uses internally before the fork, and releasing them afterwards.
In addition, it resets any lock-objects in the child. When extending or embedding Python, there is no way to inform
Python of additional (non-Python) locks that need to be acquired before or reset after a fork. OS facilities such
as pthread_atfork() would need to be used to accomplish the same thing. Additionally, when extending
or embedding Python, calling fork() directly rather than through os.fork() (and returning to or calling into
Python) may result in a deadlock by one of Python’s internal locks being held by a thread that is defunct after the
fork. PyOS_AfterFork_Child() tries to reset the necessary locks, but is not always able to.
The fact that all other threads go away also means that CPython’s runtime state there must be cleaned up properly,
which os.fork() does. This means finalizing all other PyThreadState objects belonging to the current inter-
preter and all other PyInterpreterState objects. Due to this and the special nature of the ”main” interpreter,
fork() should only be called in that interpreter’s ”main” thread, where the CPython global runtime was originally
initialized. The only exception is if exec() will be called immediately after.
9.5. 187
The Python/C API, 3.12.1
9.5.4 API
These are the most commonly used types and functions when writing C extension code, or when embedding the
Python interpreter:
type PyInterpreterState
API ( ). This data structure represents the state shared by a number of
cooperating threads. Threads belonging to the same interpreter share their module administration and a few
other internal items. There are no public members in this structure.
Threads belonging to different interpreters initially share nothing, except process state like available memory,
open file descriptors and such. The global interpreter lock is also shared by all threads, regardless of to which
interpreter they belong.
type PyThreadState
API ( ). This data structure represents the state of a single thread. The only
public data member is:
PyInterpreterState *interp
void PyEval_InitThreads()
ABI.
Python 3.6 GIL
3.9 :
3.7 : Py_Initialize()
3.2 : This function cannot be called before Py_Initialize() anymore.
3.9 .
int PyEval_ThreadsInitialized()
ABI. Returns a non-zero value if PyEval_InitThreads() has been called. This function can
be called without holding the GIL, and therefore can be used to avoid calls to the locking API when running
single-threaded.
3.7 : The GIL is now initialized by Py_Initialize().
3.9 .
PyThreadState *PyEval_SaveThread()
ABI. Release the global interpreter lock (if it has been created) and reset the thread state to NULL,
returning the previous thread state (which is not NULL). If the lock has been created, the current thread must
have acquired it.
void PyEval_RestoreThread(PyThreadState *tstate)
ABI. Acquire the global interpreter lock (if it has been created) and set the thread state to tstate,
which must not be NULL. If the lock has been created, the current thread must not have acquired it, otherwise
deadlock ensues.
: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing()
to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termi-
nation.
PyThreadState *PyThreadState_Get()
ABI. Return the current thread state. The global interpreter lock must be held. When the current
thread state is NULL, this issues a fatal error (so that the caller needn’t check for NULL).
188 Chapter 9.
The Python/C API, 3.12.1
: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing()
to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termi-
nation.
void PyGILState_Release(PyGILState_STATE)
ABI. Release any resources previously acquired. After this call, Python’s state will be the same as
it was prior to the corresponding PyGILState_Ensure() call (but generally this state will be unknown to
the caller, hence the use of the GILState API).
Every call to PyGILState_Ensure() must be matched by a call to PyGILState_Release() on the
same thread.
PyThreadState *PyGILState_GetThisThreadState()
ABI. Get the current thread state for this thread. May return NULL if no GILState API has been used
on the current thread. Note that the main thread always has such a thread-state, even if no auto-thread-state
call has been made on the main thread. This is mainly a helper/diagnostic function.
int PyGILState_Check()
Return 1 if the current thread is holding the GIL and 0 otherwise. This function can be called from any thread
at any time. Only if it has had its Python thread state initialized and currently is holding the GIL will it return
1. This is mainly a helper/diagnostic function. It can be useful for example in callback contexts or memory
allocation functions when knowing that the GIL is locked can allow the caller to perform sensitive actions or
otherwise behave differently.
3.4 .
The following macros are normally used without a trailing semicolon; look for example usage in the Python source
distribution.
Py_BEGIN_ALLOW_THREADS
ABI. This macro expands to { PyThreadState *_save; _save =
PyEval_SaveThread();. Note that it contains an opening brace; it must be matched with a fol-
lowing Py_END_ALLOW_THREADS macro. See above for further discussion of this macro.
Py_END_ALLOW_THREADS
ABI. PyEval_RestoreThread(_save); }
Py_BEGIN_ALLOW_THREADS
9.5. 189
The Python/C API, 3.12.1
Py_BLOCK_THREADS
ABI. PyEval_RestoreThread(_save);:
Py_END_ALLOW_THREADS
Py_UNBLOCK_THREADS
ABI. _save = PyEval_SaveThread();:
Py_BEGIN_ALLOW_THREADS
9.5.5 API
190 Chapter 9.
The Python/C API, 3.12.1
The throwflag parameter is used by the throw() method of generators: if non-zero, handle the current
exception.
3.9 : tstate
3.11 : The frame parameter changed from PyFrameObject* to _PyInterpreterFrame*.
_PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
Get the frame evaluation function.
See the PEP 523 ”Adding a frame evaluation API to CPython”.
3.9 .
9.5. 191
The Python/C API, 3.12.1
: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing()
to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termi-
nation.
: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing()
to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termi-
nation.
192 Chapter 9.
The Python/C API, 3.12.1
9.6
While in most uses, you will only embed a single Python interpreter, there are cases where you need to create several
independent interpreters in the same process and perhaps even in the same thread. Sub-interpreters allow you to do
that.
The ”main” interpreter is the first one created when the runtime initializes. It is usually the only Python interpreter in
a process. Unlike sub-interpreters, the main interpreter has unique process-global responsibilities like signal handling.
It is also responsible for execution during runtime initialization and is usually the active interpreter during runtime
finalization. The PyInterpreterState_Main() function returns a pointer to its state.
You can switch between sub-interpreters using the PyThreadState_Swap() function. You can create and de-
stroy them using the following functions:
type PyInterpreterConfig
Structure containing most parameters to configure a sub-interpreter. Its values are used only in
Py_NewInterpreterFromConfig() and never modified by the runtime.
3.12 .
:
int use_main_obmalloc
If this is 0 then the sub-interpreter will use its own ”object” allocator state. Otherwise it will use (share)
the main interpreter’s.
If this is 0 then check_multi_interp_extensions must be 1 (non-zero). If this is 1 then gil
must not be PyInterpreterConfig_OWN_GIL.
int allow_fork
If this is 0 then the runtime will not support forking the process in any thread where the sub-interpreter
is currently active. Otherwise fork is unrestricted.
Note that the subprocess module still works when fork is disallowed.
int allow_exec
If this is 0 then the runtime will not support replacing the current process via exec (e.g. os.execv())
in any thread where the sub-interpreter is currently active. Otherwise exec is unrestricted.
Note that the subprocess module still works when exec is disallowed.
int allow_threads
If this is 0 then the sub-interpreter’s threading module won’t create threads. Otherwise threads are
allowed.
int allow_daemon_threads
If this is 0 then the sub-interpreter’s threading module won’t create daemon threads. Otherwise
daemon threads are allowed (as long as allow_threads is non-zero).
9.6. 193
The Python/C API, 3.12.1
int check_multi_interp_extensions
If this is 0 then all extension modules may be imported, including legacy (single-phase init) modules,
in any thread where the sub-interpreter is currently active. Otherwise only multi-phase init extension
modules (see PEP 489) may be imported. (Also see Py_mod_multiple_interpreters.)
This must be 1 (non-zero) if use_main_obmalloc is 0.
int gil
This determines the operation of the GIL for the sub-interpreter. It may be one of the following:
PyInterpreterConfig_DEFAULT_GIL
Use the default selection (PyInterpreterConfig_SHARED_GIL).
PyInterpreterConfig_SHARED_GIL
Use (share) the main interpreter’s GIL.
PyInterpreterConfig_OWN_GIL
Use the sub-interpreter’s own GIL.
If this is PyInterpreterConfig_OWN_GIL then PyInterpreterConfig.
use_main_obmalloc must be 0.
PyStatus Py_NewInterpreterFromConfig(PyThreadState **tstate_p, const PyInterpreterConfig *config)
Create a new sub-interpreter. This is an (almost) totally separate environment for the execution of Python
code. In particular, the new interpreter has separate, independent versions of all imported modules, including
the fundamental modules builtins, __main__ and sys. The table of loaded modules (sys.modules)
and the module search path (sys.path) are also separate. The new environment has no sys.argv variable.
It has new standard I/O stream file objects sys.stdin, sys.stdout and sys.stderr (however these
refer to the same underlying file descriptors).
The given config controls the options with which the interpreter is initialized.
Upon success, tstate_p will be set to the first thread state created in the new sub-interpreter. This thread state
is made in the current thread state. Note that no actual thread is created; see the discussion of thread states
below. If creation of the new interpreter is unsuccessful, tstate_p is set to NULL; no exception is set since the
exception state is stored in the current thread state and there may not be a current thread state.
Like all other Python/C API functions, the global interpreter lock must be held before calling this function and
is still held when it returns. Likewise a current thread state must be set on entry. On success, the returned
thread state will be set as current. If the sub-interpreter is created with its own GIL then the GIL of the calling
interpreter will be released. When the function returns, the new interpreter’s GIL will be held by the current
thread and the previously interpreter’s GIL will remain released here.
3.12 .
Sub-interpreters are most effective when isolated from each other, with certain functionality restricted:
PyInterpreterConfig config = {
.use_main_obmalloc = 0,
.allow_fork = 0,
.allow_exec = 0,
.allow_threads = 1,
.allow_daemon_threads = 0,
.check_multi_interp_extensions = 1,
.gil = PyInterpreterConfig_OWN_GIL,
};
PyThreadState *tstate = Py_NewInterpreterFromConfig(&config);
Note that the config is used only briefly and does not get modified. During initialization the config’s values
are converted into various PyInterpreterState values. A read-only copy of the config may be stored
internally on the PyInterpreterState.
Extension modules are shared between (sub-)interpreters as follows:
194 Chapter 9.
The Python/C API, 3.12.1
Using Py_NewInterpreterFromConfig() you can create a sub-interpreter that is completely isolated from
other interpreters, including having its own GIL. The most important benefit of this isolation is that such an interpreter
can execute Python code without being blocked by other interpreters or blocking any others. Thus a single Python
process can truly take advantage of multiple CPU cores when running Python code. The isolation also encourages a
different approach to concurrency than that of just using threads. (See PEP 554.)
Using an isolated interpreter requires vigilance in preserving that isolation. That especially means not sharing any
objects or mutable state without guarantees about thread-safety. Even objects that are otherwise immutable (e.g.
None, (1, 5)) can’t normally be shared because of the refcount. One simple but less-efficient approach around
this is to use a global lock around all use of some state (or object). Alternately, effectively immutable objects (like
integers or strings) can be made safe in spite of their refcounts by making them ”immortal”. In fact, this has been
done for the builtin singletons, small integers, and a number of other builtin objects.
If you preserve isolation then you will have access to proper multi-core computing without the complications that
come with free-threading. Failure to preserve isolation will expose you to the full consequences of free-threading,
including races and hard-to-debug crashes.
Aside from that, one of the main challenges of using multiple isolated interpreters is how to communicate between
them safely (not break isolation) and efficiently. The runtime and stdlib do not provide any standard approach to
this yet. A future stdlib module would help mitigate the effort of preserving isolation and expose effective tools for
communicating (and sharing) data between interpreters.
3.12 .
9.6. 195
The Python/C API, 3.12.1
9.6.2
Because sub-interpreters (and the main interpreter) are part of the same process, the insulation between them isn’t
perfect --- for example, using low-level file operations like os.close() they can (accidentally or maliciously) affect
each other’s open files. Because of the way extensions are shared between (sub-)interpreters, some extensions may not
work properly; this is especially likely when using single-phase initialization or (static) global variables. It is possible
to insert objects created in one sub-interpreter into a namespace of another (sub-)interpreter; this should be avoided
if possible.
Special care should be taken to avoid sharing user-defined functions, methods, instances or classes between sub-
interpreters, since import operations executed by such objects may affect the wrong (sub-)interpreter’s dictionary of
loaded modules. It is equally important to avoid sharing objects from which the above are reachable.
Also note that combining this functionality with PyGILState_* APIs is delicate, because these APIs as-
sume a bijection between Python thread states and OS-level threads, an assumption broken by the presence of
sub-interpreters. It is highly recommended that you don’t switch sub-interpreters between a pair of matching
PyGILState_Ensure() and PyGILState_Release() calls. Furthermore, extensions (such as ctypes)
using these APIs to allow calling of Python code from non-Python created threads will probably be broken when
using sub-interpreters.
9.7
A mechanism is provided to make asynchronous notifications to the main interpreter thread. These notifications take
the form of a function pointer and a void pointer argument.
int Py_AddPendingCall(int (*func)(void*), void *arg)
ABI. Schedule a function to be called from the main interpreter thread. On success, 0 is returned
and func is queued for being called in the main thread. On failure, -1 is returned without setting any exception.
When successfully queued, func will be eventually called from the main interpreter thread with the argument
arg. It will be called asynchronously with respect to normally running Python code, but with both these con-
ditions met:
• on a bytecode boundary;
• with the main thread holding the global interpreter lock (func can therefore use the full C API).
func must return 0 on success, or -1 on failure with an exception set. func won’t be interrupted to perform
another asynchronous notification recursively, but it can still be interrupted to switch threads if the global
interpreter lock is released.
This function doesn’t need a current thread state to run, and it doesn’t need the global interpreter lock.
To call this function in a subinterpreter, the caller must hold the GIL. Otherwise, the function func can be
scheduled to be called from the wrong interpreter.
: This is a low-level function, only useful for very special cases. There is no guarantee that func
will be called as quick as possible. If the main thread is busy executing a system call, func won’t be called
before the system call returns. This function is generally not suitable for calling Python code from arbitrary
C threads. Instead, use the PyGILState API.
3.9 : If this function is called in a subinterpreter, the function func is now scheduled to be called
from the subinterpreter, rather than being called from the main interpreter. Each subinterpreter now has its
own list of scheduled calls.
3.1 .
196 Chapter 9.
The Python/C API, 3.12.1
9.8
The Python interpreter provides some low-level support for attaching profiling and execution tracing facilities. These
are used for profiling, debugging, and coverage analysis tools.
This C interface allows the profiling or tracing code to avoid the overhead of calling through Python-level callable
objects, making a direct C function call instead. The essential attributes of the facility have not changed; the interface
allows trace functions to be installed per-thread, and the basic events reported to the trace function are the same as
had been reported to the Python-level trace functions in previous versions.
typedef int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
The type of the trace function registered using PyEval_SetProfile() and PyEval_SetTrace().
The first parameter is the object passed to the registration function as obj, frame is the frame object to which the
event pertains, what is one of the constants PyTrace_CALL, PyTrace_EXCEPTION, PyTrace_LINE,
PyTrace_RETURN, PyTrace_C_CALL, PyTrace_C_EXCEPTION, PyTrace_C_RETURN, or
PyTrace_OPCODE, and arg depends on the value of what:
what arg
PyTrace_CALL Py_None.
PyTrace_EXCEPTION sys.exc_info()
PyTrace_LINE Py_None.
PyTrace_RETURN NULL
PyTrace_C_CALL
PyTrace_C_EXCEPTION
PyTrace_C_RETURN
PyTrace_OPCODE Py_None.
int PyTrace_CALL
The value of the what parameter to a Py_tracefunc function when a new call to a function or method is
being reported, or a new entry into a generator. Note that the creation of the iterator for a generator function
is not reported as there is no control transfer to the Python bytecode in the corresponding frame.
int PyTrace_EXCEPTION
The value of the what parameter to a Py_tracefunc function when an exception has been raised. The
callback function is called with this value for what when after any bytecode is processed after which the
exception becomes set within the frame being executed. The effect of this is that as exception propagation
causes the Python stack to unwind, the callback is called upon return to each frame as the exception propagates.
Only trace functions receives these events; they are not needed by the profiler.
int PyTrace_LINE
The value passed as the what parameter to a Py_tracefunc function (but not a profiling function) when a
line-number event is being reported. It may be disabled for a frame by setting f_trace_lines to 0 on that
frame.
int PyTrace_RETURN
The value for the what parameter to Py_tracefunc functions when a call is about to return.
int PyTrace_C_CALL
The value for the what parameter to Py_tracefunc functions when a C function is about to be called.
int PyTrace_C_EXCEPTION
The value for the what parameter to Py_tracefunc functions when a C function has raised an exception.
int PyTrace_C_RETURN
The value for the what parameter to Py_tracefunc functions when a C function has returned.
int PyTrace_OPCODE
The value for the what parameter to Py_tracefunc functions (but not profiling functions) when a new
opcode is about to be executed. This event is not emitted by default: it must be explicitly requested by setting
f_trace_opcodes to 1 on the frame.
9.8. 197
The Python/C API, 3.12.1
9.9
198 Chapter 9.
The Python/C API, 3.12.1
9.10
The Python interpreter provides low-level support for thread-local storage (TLS) which wraps the underlying native
TLS implementation to support the Python-level thread local storage API (threading.local). The CPython
C level APIs are similar to those offered by pthreads and Windows: use a thread key and functions to associate a
void* value per thread.
The GIL does not need to be held when calling these functions; they supply their own locking.
Note that Python.h does not include the declaration of the TLS APIs, you need to include pythread.h to use
thread-local storage.
: None of these API functions handle memory management on behalf of the void* values. You need to
allocate and deallocate them yourself. If the void* values happen to be PyObject*, these functions don’t do
refcount operations on them either.
TSS API is introduced to supersede the use of the existing TLS API within the CPython interpreter. This API uses
a new type Py_tss_t instead of int to represent thread keys.
3.7 .
:
”A New C-API for Thread-Local Storage in CPython” (PEP 539)
type Py_tss_t
This data structure represents the state of a thread key, the definition of which may depend on the underlying
TLS implementation, and it has an internal field representing the key’s initialization state. There are no public
members in this structure.
When Py_LIMITED_API is not defined, static allocation of this type by Py_tss_NEEDS_INIT is allowed.
Py_tss_NEEDS_INIT
This macro expands to the initializer for Py_tss_t variables. Note that this macro won’t be defined with
Py_LIMITED_API.
Dynamic Allocation
Dynamic allocation of the Py_tss_t, required in extension modules built with Py_LIMITED_API, where static
allocation of this type is not possible due to its implementation being opaque at build time.
Py_tss_t *PyThread_tss_alloc()
ABI 3.7 . Return a value which is the same state as a value initialized with
Py_tss_NEEDS_INIT, or NULL in the case of dynamic allocation failure.
void PyThread_tss_free(Py_tss_t *key)
ABI 3.7 . Free the given key allocated by PyThread_tss_alloc(), after first
calling PyThread_tss_delete() to ensure any associated thread locals have been unassigned. This is a
no-op if the key argument is NULL.
: A freed key becomes a dangling pointer. You should reset the key to NULL.
9.10. 199
The Python/C API, 3.12.1
The parameter key of these functions must not be NULL. Moreover, the behaviors of PyThread_tss_set()
and PyThread_tss_get() are undefined if the given Py_tss_t has not been initialized by
PyThread_tss_create().
int PyThread_tss_is_created(Py_tss_t *key)
ABI 3.7 . Return a non-zero value if the given Py_tss_t has been initialized by
PyThread_tss_create().
int PyThread_tss_create(Py_tss_t *key)
ABI 3.7 . Return a zero value on successful initialization of a TSS key. The behavior
is undefined if the value pointed to by the key argument is not initialized by Py_tss_NEEDS_INIT. This
function can be called repeatedly on the same key -- calling it on an already initialized key is a no-op and
immediately returns success.
void PyThread_tss_delete(Py_tss_t *key)
ABI 3.7 . Destroy a TSS key to forget the values associated with the key across all
threads, and change the key’s initialization state to uninitialized. A destroyed key is able to be initialized again
by PyThread_tss_create(). This function can be called repeatedly on the same key -- calling it on an
already destroyed key is a no-op.
int PyThread_tss_set(Py_tss_t *key, void *value)
ABI 3.7 . Return a zero value to indicate successfully associating a void* value with a
TSS key in the current thread. Each thread has a distinct mapping of the key to a void* value.
void *PyThread_tss_get(Py_tss_t *key)
ABI 3.7 . Return the void* value associated with a TSS key in the current thread. This
returns NULL if no value is associated with the key in the current thread.
: This version of the API does not support platforms where the native TLS key is defined in a way that cannot
be safely cast to int. On such platforms, PyThread_create_key() will return immediately with a failure
status, and the other TLS functions will all be no-ops on such platforms.
API
int PyThread_create_key()
ABI.
void PyThread_delete_key(int key)
ABI.
int PyThread_set_key_value(int key, void *value)
ABI.
void *PyThread_get_key_value(int key)
ABI.
void PyThread_delete_key_value(int key)
ABI.
void PyThread_ReInitTLS()
ABI.
200 Chapter 9.
CHAPTER 10
Python
3.8 .
Python Py_InitializeFromConfig() PyConfig
Py_PreInitialize() PyPreConfig
10.1
Python :
PyConfig config;
PyConfig_InitPythonConfig(&config);
config.isolated = 1;
201
The Python/C API, 3.12.1
( )
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto exception;
}
PyConfig_Clear(&config);
return Py_RunMain();
exception:
PyConfig_Clear(&config);
if (PyStatus_IsExit(status)) {
return status.exitcode;
}
/* Display the error message and exit the process with
non-zero exit code */
Py_ExitStatusException(status);
}
10.2 PyWideStringList
type PyWideStringList
wchar_t*
length items NULL NULL
10.3 PyStatus
type PyStatus
C
:
int exitcode
exit()
const char *err_msg
err_msg NULL
PyStatus PyStatus_NoMemory(void)
Py_ExitStatusException()
int PyStatus_IsError(PyStatus status)
( )
return PyStatus_Ok();
}
10.4 PyPreConfig
type PyPreConfig
Python
:
void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)
Python
void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)
:
int allocator
Python :
• PYMEM_ALLOCATOR_NOT_SET (0): ( )
• PYMEM_ALLOCATOR_DEFAULT (1):
• PYMEM_ALLOCATOR_DEBUG (2):
• PYMEM_ALLOCATOR_MALLOC (3): C malloc()
• PYMEM_ALLOCATOR_MALLOC_DEBUG (4): malloc()
• PYMEM_ALLOCATOR_PYMALLOC (5): Python pymalloc
• PYMEM_ALLOCATOR_PYMALLOC_DEBUG (6): Python pymalloc
Python --without-pymalloc PYMEM_ALLOCATOR_PYMALLOC
PYMEM_ALLOCATOR_PYMALLOC_DEBUG
Memory Management.
: PYMEM_ALLOCATOR_NOT_SET
int configure_locale
LC_CTYPE
0 coerce_c_locale coerce_c_locale_warn 0
locale encoding
: Python 1 0
int coerce_c_locale
2 C
1 LC_CTYPE
locale encoding
: Python -1 0
int coerce_c_locale_warn
C
: Python -1 0
int dev_mode
Python : PyConfig.dev_mode
: Python -1 0
int isolated
PyConfig.isolated
: Python 0 1
int legacy_windows_fs_encoding
:
• PyPreConfig.utf8_mode 0,
• PyConfig.filesystem_encoding "mbcs",
• PyConfig.filesystem_errors "replace".
PYTHONLEGACYWINDOWSFSENCODING
Windows #ifdef MS_WINDOWS Windows
: 0.
int parse_argv
Py_PreInitializeFromArgs() Py_PreInitializeFromBytesArgs()
Python argv
: Python 1 0
int use_environment
? PyConfig.use_environment
: Python 1 0
int utf8_mode
Python UTF-8
-X utf8 PYTHONUTF8 0 1
LC_CTYPE C POSIX 1
: Python -1 0
Python :
• Python (PyPreConfig.allocator)
• LC_CTYPE (locale encoding)
• Python UTF-8 (PyPreConfig.utf8_mode)
(PyPreConfig ) _PyRuntime.preconfig
Python
PyStatus Py_PreInitialize(const PyPreConfig *preconfig)
preconfig Python
preconfig NULL
PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char *const *argv)
preconfig Python
preconfig parse_argv argv
preconfig NULL
PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t *const *argv)
preconfig Python
preconfig parse_argv argv
preconfig NULL
PyStatus_Exception() Py_ExitStatusException()
PyStatus status;
PyPreConfig preconfig;
PyPreConfig_InitPythonConfig(&preconfig);
preconfig.utf8_mode = 1;
status = Py_PreInitialize(&preconfig);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
Py_Initialize();
/* ... use Python API here ... */
Py_Finalize();
10.6 PyConfig
type PyConfig
Python
PyConfig_Clear()
:
void PyConfig_InitPythonConfig(PyConfig *config)
Python
void PyConfig_InitIsolatedConfig(PyConfig *config)
Python
PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t
length, wchar_t **items)
list length items
Python
PyStatus PyConfig_Read(PyConfig *config)
Python
Python 3.11
PyConfig_Read() PyConfig.argv PyConfig.
parse_argv 2 Python PyConfig.argv
Python
Python
3.10 : PyConfig.argv PyConfig.
parse_argv 2 PyConfig.parse_argv 1
3.11 : PyConfig_Read() Python
Py_InitializeFromConfig()
void PyConfig_Clear(PyConfig *config)
• PyConfig.dev_mode
• PyConfig.isolated
• PyConfig.parse_argv
• PyConfig.use_environment
PyConfig_SetArgv() PyConfig_SetBytesArgv()
parse_argv
PyStatus_Exception() Py_ExitStatusException()
:
PyWideStringList argv
: sys.argv
parse_argv 1 Python Python argv
argv Python
argv sys.argv
: NULL.
orig_argv
int safe_path
Py_RunMain() sys.path :
• argv[0] L"-m" (python -m module)
• (python script.py)
-P PYTHONSAFEPATH 1
Python 0 1
3.11 .
wchar_t *base_exec_prefix
sys.base_exec_prefix.
: NULL.
Python
wchar_t *base_executable
Python : sys._base_executable
__PYVENV_LAUNCHER__
NULL PyConfig.executable
: NULL.
Python
wchar_t *base_prefix
sys.base_prefix.
: NULL.
Python
int buffered_stdio
0 configure_c_stdio C stdout stderr
-u PYTHONUNBUFFERED 0
stdin
: 1.
int bytes_warning
1 bytes bytearray str bytes int
2 BytesWarning
-b
: 0.
int warn_default_encoding
io.TextIOWrapper EncodingWarning
io-encoding-warning
: 0.
3.10 .
int code_debug_ranges
0
PYTHONNODEBUGRANGES -X no_debug_ranges 0
: 1.
3.11 .
wchar_t *check_hash_pycs_mode
.pyc : --check-hash-based-pycs
• L"always": ’check_source’
• L"never": pyc
• L"default": pyc ’check_source’
L"default"
PEP 552 ”Deterministic pycs”
int configure_c_stdio
C :
• Windows stdin, stdout stderr (O_BINARY)
• buffered_stdio stdin, stdout stderr
• interactive stdin stdout Windows stdout
: Python 1 0
int dev_mode
Python
-X dev PYTHONDEVMODE 1
: Python -1 0
int dump_refs
Python
PYTHONDUMPREFS 1
Py_TRACE_REFS Python configure
--with-trace-refs
: 0.
wchar_t *exec_prefix
Python : sys.exec_prefix
: NULL.
Python
wchar_t *executable
Python : sys.executable
: NULL.
Python
int faulthandler
faulthandler
faulthandler.enable()
-X faulthandler PYTHONFAULTHANDLER 1
: Python -1 0
wchar_t *filesystem_encoding
: sys.getfilesystemencoding()
macOS, Android VxWorks "utf-8"
Windows "utf-8" PyPreConfig
legacy_windows_fs_encoding "mbcs"
• PyPreConfig.utf8_mode "utf-8"
• Python nl_langinfo(CODESET) ASCII mbstowcs()
Latin1 "ascii"
• nl_langinfo(CODESET) "utf-8"
• locale encoding: nl_langinfo(CODESET)
Python Python "ANSI_X3.4-1968"
"ascii"
filesystem_errors
wchar_t *filesystem_errors
: sys.getfilesystemencodeerrors()
Windows "surrogatepass" PyPreConfig
legacy_windows_fs_encoding "replace"
"surrogateescape"
• "strict"
• "surrogateescape"
• "surrogatepass" ( UTF-8 )
filesystem_encoding
unsigned long hash_seed
int use_hash_seed
-X importtime PYTHONPROFILEIMPORTTIME 1
: 0.
int inspect
0 -c
sys.stdin
-i PYTHONINSPECT 1
: 0.
int install_signal_handlers
Python
Python 1 0
int interactive
0 REPL
-i
: 0.
int int_max_str_digits
-1
4300 (sys.int_info.default_max_str_digits) 0 0
640 (sys.int_info.str_digits_check_threshold)
-X int_max_str_digits PYTHONINTMAXSTRDIGITS
Python -1 4300 (sys.int_info.
default_max_str_digits)
3.12 .
int isolated
0
• safe_path 1: Python sys.path
• use_environment 0: PYTHON
• user_site_directory 0: sys.path
• Python REPL readline readline
-I 1
: Python 0 1
PyPreConfig.isolated
int legacy_windows_stdio
io.FileIO io._WindowsConsoleIO sys.stdin sys.
stdout sys.stderr
PYTHONLEGACYWINDOWSSTDIO 1
Windows #ifdef MS_WINDOWS Windows
: 0.
PEP 528 ( Windows UTF-8)
int malloc_stats
Python pymalloc
PYTHONMALLOCSTATS 1
Python --without-pymalloc
: 0.
wchar_t *platlibdir
: sys.platlibdir
PYTHONPLATLIBDIR
configure --with-platlibdir PLATLIBDIR ( :
"lib" Windows "DLLs")
Python
3.9 .
3.11 : Windows DLLs
wchar_t *pythonpath_env
(sys.path) DELIM (os.pathsep)
PYTHONPATH
: NULL.
Python
PyWideStringList module_search_paths
int module_search_paths_set
: sys.path
module_search_paths_set 0 Py_InitializeFromConfig()
module_search_paths module_search_paths_set 1
(module_search_paths) 0 (module_search_paths_set)
Python
int optimization_level
3.10 .
int parse_argv
int parser_debug
0
-d PYTHONDEBUG
Python ( Py_DEBUG )
: 0.
int pathconfig_warnings
stderr 0
Python 1 0
Python
3.11 : Windows
wchar_t *prefix
Python : sys.prefix
: NULL.
Python
wchar_t *program_name
executable Python
• Py_SetProgramName()
• macOS PYTHONEXECUTABLE
• WITH_NEXT_FRAMEWORK __PYVENV_LAUNCHER__
• argv argv[0]
• Windows L"python" L"python3"
: NULL.
Python
wchar_t *pycache_prefix
.pyc : sys.pycache_prefix
-X pycache_prefix=PATH PYTHONPYCACHEPREFIX
NULL sys.pycache_prefix None
: NULL.
int quiet
0 Python
-q
: 0.
wchar_t *run_command
-c
Py_RunMain()
: NULL.
wchar_t *run_filename
-c -m Py_RunMain()
-X showrefcount 1
Python ( Py_REF_DEBUG )
: 0.
int site_import
site
sys.path
site
site.main()
-S 0
sys.flags.no_site site_import
: 1.
int skip_source_first_line
PyConfig.run_filename
Unix #!cmd DOS
-x 1
: 0.
wchar_t *stdio_encoding
wchar_t *stdio_errors
sys.stdin sys.stdout sys.stderr sys.stderr
"backslashreplace"
Py_SetStandardStreamEncoding() error errors NULL
PYTHONIOENCODING
• PyPreConfig.utf8_mode "UTF-8"
• locale encoding
• Windows "surrogateescape"
• PyPreConfig.utf8_mode LC_CTYPE ”C”
”POSIX” "surrogateescape"
• "strict"
int tracemalloc
tracemalloc
tracemalloc.start()
-X tracemalloc=N PYTHONTRACEMALLOC
: Python -1 0
int perf_profiling
perf
perf trampoline perf_profiling
-X perf PYTHONPERFSUPPORT
: -1
3.12 .
int use_environment
-E 0
: Python 1 0
int user_site_directory
sys.path
-s -I 0
PYTHONNOUSERSITE 0
Python 1 0
int verbose
0
-v
PYTHONVERBOSE
: 0.
PyWideStringList warnoptions
warnings : sys.warnoptions
warnings sys.warnoptions: PyConfig.
warnoptions warnings.filters
-W warnoptions
PYTHONWARNINGS (,)
int write_bytecode
0 Python .pyc
-B PYTHONDONTWRITEBYTECODE 0
sys.dont_write_bytecode write_bytecode
: 1.
PyWideStringList xoptions
-X : sys._xoptions
10.7 PyConfig
Python
PyStatus Py_InitializeFromConfig(const PyConfig *config)
config Python
PyStatus_Exception() Py_ExitStatusException()
PyImport_FrozenModules() PyImport_AppendInittab()
PyImport_ExtendInittab() Python Python
Python Python PyImport_AppendInittab()
PyImport_ExtendInittab()
(PyConfig ) PyInterpreterState.config
:
void init_python(void)
{
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto exception;
}
PyConfig_Clear(&config);
return;
exception:
PyConfig_Clear(&config);
Py_ExitStatusException(status);
}
3.11
PyConfig config;
PyConfig_InitPythonConfig(&config);
( )
if (PyStatus_Exception(status)) {
goto done;
}
status = Py_InitializeFromConfig(&config);
done:
PyConfig_Clear(&config);
return status;
}
10.8
PyPreConfig_InitIsolatedConfig() PyConfig_InitIsolatedConfig()
Python Python
(PyConfig.argv )
C ( stdout) LC_CTYPE
PyConfig.home
10.9 Python
PyPreConfig_InitPythonConfig() PyConfig_InitPythonConfig()
Python Python
Python
LC_CTYPE PYTHONUTF8 PYTHONCOERCECLOCALE C
(PEP 538) Python UTF-8 (PEP 540)
10.10 Python
PyConfig
•
– PyConfig.home
– PyConfig.platlibdir
– PyConfig.pathconfig_warnings
– PyConfig.program_name
– PyConfig.pythonpath_env
–
– PATH ( PyConfig.program_name)
– __PYVENV_LAUNCHER__
– Windows only HKEY_CURRENT_USER HKEY_LOCAL_MACHINE
”SoftwarePythonPythonCoreX.YPythonPath” X.Y Python
•
– PyConfig.base_exec_prefix
– PyConfig.base_executable
– PyConfig.base_prefix
– PyConfig.exec_prefix
– PyConfig.executable
– PyConfig.module_search_paths_set, PyConfig.module_search_paths
– PyConfig.prefix
Python
module_search_paths_set 0 module_search_paths
module_search_paths_set 1
module_search_paths_set 1 module_search_paths
module_search_paths
pathconfig_warnings 0 Unix Windows
– run_filename sys.path
– sys.path
site_import sys.path site user_site_directory
site-package site site-package sys.path
• pyvenv.cfg
• ._pth ( : python._pth)
• pybuilddir.txt ( Unix)
._pth :
• isolated 1
• use_environment 0
• site_import 0
• safe_path 1
__PYVENV_LAUNCHER__ PyConfig.base_executable
10.11 Py_RunMain()
int Py_RunMain(void)
(PyConfig.run_command) (PyConfig.
run_filename) (PyConfig.run_module)
-i REPL
Python exit()
Python Py_RunMain() Python
10.12 Py_GetArgcArgv()
10.13 API
PyStatus _Py_InitializeMain(void)
Python
importlib :
Python Python sys.meta_path
void init_python(void)
{
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
config._init_main = 0;
status = Py_InitializeFromConfig(&config);
PyConfig_Clear(&config);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
( )
"import sys; "
"print('Run Python code before _Py_InitializeMain', "
"file=sys.stderr)");
if (res < 0) {
exit(1);
}
status = _Py_InitializeMain();
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
}
11.1
Python
Python
Python
Python Python
Python/C API
C Python
malloc(), calloc(), realloc() free() C Python
PyObject *res;
char *buf = (char *) malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
...Do some I/O operation involving buf...
res = PyBytes_FromString(buf);
free(buf); /* malloc'ed */
return res;
I/O C Python
Python Python
C Python
Python
Python
223
The Python/C API, 3.12.1
Python
C I/O
Python
:
PYTHONMALLOC Python
PYTHONMALLOCSTATS pymalloc pymalloc
11.2
PyMemAllocatorDomain
• * *
GIL
• ”Mem” Python GIL
Python
• Python Python
PyMem_Free()
PyMem_Malloc()
11.3
p NULL,
11.4
ANSI C Python
pymalloc .
: GIL
p NULL PyMem_Malloc(n) n 0
NULL
p NULL PyMem_Malloc() PyMem_Realloc()
PyMem_Calloc()
PyMem_Realloc() NULL p
void PyMem_Free(void *p)
ABI. p p PyMem_Malloc() PyMem_Realloc()
PyMem_Calloc() PyMem_Free(p)
p NULL,
TYPE C
PyMem_New(TYPE, n)
PyMem_Malloc() (n * sizeof(TYPE))
TYPE*
11.4. 225
The Python/C API, 3.12.1
PyMem_Resize(p, TYPE, n)
PyMem_Realloc() (n * sizeof(TYPE))
TYPE* p NULL
C p p
void PyMem_Del(void *p)
PyMem_Free()
Python C API
Python
• PyMem_MALLOC(size)
• PyMem_NEW(type, size)
• PyMem_REALLOC(ptr, size)
• PyMem_RESIZE(ptr, type, size)
• PyMem_FREE(ptr)
• PyMem_DEL(ptr)
11.5
ANSI C Python
:
Python
pymalloc .
: GIL
void *PyObject_Malloc(size_t n)
ABI. n void*
NULL
NULL PyObject_Malloc(1)
11.6
PyMem_RawMallocPyMem_Malloc PyOb-
ject_Malloc
"pymalloc" malloc pymalloc pymalloc
"pymalloc_debug"malloc + debug pymalloc + de- pymalloc + de-
bug bug
pymalloc "malloc" malloc malloc malloc
• PYTHONMALLOC
• malloc C C malloc() calloc() realloc() free()
• pymalloc pymalloc .
• ”+ debug”: Python .
• Python
11.7
3.4 .
type PyMemAllocatorEx
:
void *ctx
type PyMemAllocatorDomain
11.6. 227
The Python/C API, 3.12.1
PYMEM_DOMAIN_RAW
• PyMem_RawMalloc()
• PyMem_RawRealloc()
• PyMem_RawCalloc()
• PyMem_RawFree()
PYMEM_DOMAIN_MEM
• PyMem_Malloc(),
• PyMem_Realloc()
• PyMem_Calloc()
• PyMem_Free()
PYMEM_DOMAIN_OBJ
• PyObject_Malloc()
• PyObject_Realloc()
• PyObject_Calloc()
• PyObject_Free()
void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
NULL
PYMEM_DOMAIN_RAW GIL
GIL
PyMem_SetupDebugHooks()
: PyMem_SetAllocator() :
• Py_PreInitialize() Py_InitializeFromConfig()
• Python Py_InitializeFromConfig()
must
3.12 :
void PyMem_SetupDebugHooks(void)
Python
11.8 Python
p[N:N+S] PYMEM_FORBIDDENBYTE
p[N+S:N+2*S] PYMEM_DEBUG_SERIALNO
malloc realloc 1 size_t
obmalloc.c bumpserialno()
PYMEM_DEADBYTE ( )
PYMEM_CLEANBYTE ( )
11.9 pymalloc
3.4 .
type PyObjectArenaAllocator
arena
void *ctx
3.7 .
int PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr, size_t size)
tracemalloc
0 -1 ( ) tracemalloc -2
11.11
I/O Python :
PyObject *res;
char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Free(buf); /* allocated with PyMem_Malloc */
return res;
PyObject *res;
char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Del(buf); /* allocated with PyMem_New */
return res;
API
fatal
12.1
PyObject_New(TYPE, typeobj)
C TYPE Python typeobj (PyTypeObject*) Python f
Python
1 tp_basicsize
PyObject_NewVar(TYPE, typeobj, size)
C TYPE Python typeobj (PyTypeObject*) Python
Python TYPE typeobj
tp_itemsize size (Py_ssize_t)
233
The Python/C API, 3.12.1
PyObject _Py_NoneStruct
None Python Py_None
:
PyModule_Create()
12.2
Python
12.2.1
Python PyObject
PyVarObject
Python
type PyObject
API. ( ABI )
Python
PyObject
Python PyObject* Py_REFCNT
Py_TYPE
type PyVarObject
API. ( ABI ) ob_size PyObject
Python/C API
Py_REFCNT, Py_TYPE Py_SIZE
PyObject_HEAD
PyObject_HEAD :
PyObject ob_base;
PyObject
PyObject_VAR_HEAD
PyObject_VAR_HEAD
:
PyVarObject ob_base;
PyVarObject
int Py_Is(PyObject *x, PyObject *y)
ABI 3.10 . x y Python x is y
3.10 .
int Py_IsNone(PyObject *x)
ABI 3.10 . None Python x is None
3.10 .
int Py_IsTrue(PyObject *x)
ABI 3.10 . True Python x is True
3.10 .
3.10 .
PyTypeObject *Py_TYPE(PyObject *o)
Python o
borrowed reference
Py_SET_TYPE()
3.11 : Py_TYPE() const PyObject*
int Py_IS_TYPE(PyObject *o, PyTypeObject *type)
o type : Py_TYPE(o) == type
3.9 .
void Py_SET_TYPE(PyObject *o, PyTypeObject *type)
o type
3.9 .
Py_ssize_t Py_SIZE(PyVarObject *o)
Python o
Py_SET_SIZE()
3.11 : Py_SIZE() const PyVarObject*
void Py_SET_SIZE(PyVarObject *o, Py_ssize_t size)
o size
3.9 .
PyObject_HEAD_INIT(type)
PyObject :
_PyObject_EXTRA_INIT
1, type,
PyVarObject_HEAD_INIT(type, size)
PyVarObject ob_size :
_PyObject_EXTRA_INIT
1, type, size,
12.2.2
type PyCFunction
ABI. C Python
PyObject* NULL NULL
Python
:
12.2. 235
The Python/C API, 3.12.1
type PyCFunctionWithKeywords
ABI. C METH_VARARGS | METH_KEYWORDS Python
:
type _PyCFunctionFast
C METH_FASTCALL Python :
type _PyCFunctionFastWithKeywords
C METH_FASTCALL | METH_KEYWORDS Python
:
type PyCMethod
C METH_METHOD | METH_FASTCALL | METH_KEYWORDS Python
:
3.9 .
type PyMethodDef
ABI ( ). :
const char *ml_name
PyCFunction ml_meth
C
int ml_flags
ml_meth C PyObject*
PyCFunction PyCFunction
PyObject* self C
ml_flags
:
METH_VARARGS
PyCFunction PyObject*
self ( args)
PyArg_ParseTuple() PyArg_UnpackTuple()
METH_KEYWORDS
: METH_VARARGS | METH_KEYWORDS, METH_FASTCALL |
METH_KEYWORDS METH_METHOD | METH_FASTCALL | METH_KEYWORDS
METH_VARARGS | METH_KEYWORDS PyCFunctionWithKeywords
: self, args, kwargs kwargs
NULL PyArg_ParseTupleAndKeywords()
METH_FASTCALL
_PyCFunctionFast self
PyObject*
3.7 .
3.10 : METH_FASTCALL ABI
METH_FASTCALL | METH_KEYWORDS METH_FASTCALL
_PyCFunctionFastWithKeywords vectorcall
PyObject*
NULL args
3.7 .
METH_METHOD
: METH_METHOD | METH_FASTCALL | METH_KEYWORDS
METH_METHOD | METH_FASTCALL | METH_KEYWORDS METH_FASTCALL | METH_KEYWORDS
Py_TYPE(self)
PyCMethod self defining_class
METH_FASTCALL | METH_KEYWORDS
3.9 .
METH_NOARGS
METH_NOARGS
PyCFunction self
NULL
2 Py_UNUSED
METH_O
METH_O PyArg_ParseTuple()
"O" PyCFunction self PyObject*
METH_CLASS
classmethod()
METH_STATIC
NULL
staticmethod()
12.2. 237
The Python/C API, 3.12.1
METH_COEXIST
METH_COEXIST
sq_contains __contains__()
PyCFunction PyCFunction
PyCFunction
12.2.3
type PyMemberDef
ABI ( ). C
NULL tp_members
:
const char *name
NULL PyMemberDef[]
int type
C
Py_ssize_t offset
int flags
( flags 0 ) Py_READONLY
Py_T_STRING Py_READONLY Py_T_OBJECT_EX (
T_OBJECT)
PyType_FromSpec() PyMemberDef
"__vectorcalloffset__" tp_vectorcall_offset
Py_T_PYSSIZET Py_READONLY :
PyMemberDef.flags:
Py_READONLY
Py_AUDIT_READ
object.__getattr__
Py_RELATIVE_OFFSET
PyMemberDef offset PyObject
basicsize Py_tp_members
PyMemberDef.type C Python
Python Python C
TypeError ValueError
(D) del delattr()
12.2. 239
The Python/C API, 3.12.1
C Python
char int
Py_T_BYTE
short int
Py_T_SHORT
int int
Py_T_INT
long int
Py_T_LONG
Py_ssize_t int
Py_T_PYSSIZET
float float
Py_T_FLOAT
double float
Py_T_DOUBLE
char ( 0 1) bool
Py_T_BOOL
(**): 1 ASCII
(RO) Py_READONLY
(D) NULL NULL AttributeError
3.12 : #include "structmember.h"
Py_ ( T_INT)
T_OBJECT
Py_T_OBJECT_EX NULL None Python
None
T_NONE
None Py_READONLY
type PyGetSetDef
ABI ( ).
PyTypeObject.tp_getset
const char *name
getter get
C
setter set
C
const char *doc
void *closure
getter setter
get PyObject* ( ) ( closure):
NULL
set PyObject* ( ) ( closure):
NULL 0 -1
12.3
Python : PyTypeObject
PyObject_* PyType_* Python
PyTypeObject
12.3. 241
The Python/C API, 3.12.1
12.3.1
”tp_ ”
Page 243, 1
PyTypeObject Type /
Page 243, 2
O T D I
<R> tp_name const char * __name__ X X
tp_basicsize Py_ssize_t X X X
tp_itemsize Py_ssize_t X X
tp_dealloc destructor X X X
tp_vectorcall_offset Py_ssize_t X X
(tp_getattr) getattrfunc __getattribute__, __getattr__ G
(tp_setattr) setattrfunc __setattr__, __delattr__ G
tp_as_async PyAsyncMethods * %
tp_repr reprfunc __repr__ X X X
tp_as_number PyNumberMethods * %
tp_as_sequence PySequenceMethods * %
tp_as_mapping PyMappingMethods * %
tp_hash hashfunc __hash__ X G
tp_call ternaryfunc __call__ X X
tp_str reprfunc __str__ X X
tp_getattro getattrofunc __getattribute__, __getattr__ X X G
tp_setattro setattrofunc __setattr__, __delattr__ X X G
tp_as_buffer PyBufferProcs * %
tp_flags unsigned long X X ?
tp_doc const char * __doc__ X X
tp_traverse traverseproc X G
tp_clear inquiry X G
tp_richcompare richcmpfunc __lt__, __le__, __eq__, __ne__, X G
__gt__, __ge__
(tp_weaklistoffset) Py_ssize_t X ?
tp_iter getiterfunc __iter__ X
tp_iternext iternextfunc __next__ X
tp_methods PyMethodDef [] X X
tp_members PyMemberDef [] X
tp_getset PyGetSetDef [] X X
tp_base PyTypeObject * __base__ X
tp_dict PyObject * __dict__ ?
tp_descr_get descrgetfunc __get__ X
tp_descr_set descrsetfunc __set__, __delete__ X
(tp_dictoffset) Py_ssize_t X ?
tp_init initproc __init__ X X X
tp_alloc allocfunc X ? ?
tp_new newfunc __new__ X X ? ?
tp_free freefunc X X ? ?
tp_is_gc inquiry X X
<tp_bases> PyObject * __bases__ ~
<tp_mro> PyObject * __mro__ ~
[tp_cache] PyObject *
[tp_subclasses] void * __subclasses__
[tp_weaklist] PyObject *
(tp_del) destructor
[tp_version_tag] unsigned int
1–
Page 243, 1
PyTypeObject Type /
Page 243, 2
O T D I
tp_finalize destructor __del__ X
tp_vectorcall vectorcallfunc
[tp_watched] unsigned char
Type
am_await unaryfunc __await__
am_aiter unaryfunc __aiter__
am_anext unaryfunc __anext__
am_send sendfunc
<>: NULL
[]:
<R> ( ) ( NULL)
2
”O”: PyBaseObject_Type
”T”: PyType_Type
”D”: ( NULL)
12.3. 243
The Python/C API, 3.12.1
2–
Type
nb_rshift binaryfunc __rshift__
__rrshift__
nb_inplace_rshift binaryfunc __irshift__
nb_and binaryfunc __and__ __rand__
nb_inplace_and binaryfunc __iand__
nb_xor binaryfunc __xor__ __rxor__
nb_inplace_xor binaryfunc __ixor__
nb_or binaryfunc __or__ __ror__
nb_inplace_or binaryfunc __ior__
nb_int unaryfunc __int__
nb_reserved void *
nb_float unaryfunc __float__
nb_floor_divide binaryfunc __floordiv__
nb_inplace_floor_divide binaryfunc __ifloordiv__
nb_true_divide binaryfunc __truediv__
nb_inplace_true_divide binaryfunc __itruediv__
nb_index unaryfunc __index__
nb_matrix_multiply binaryfunc __matmul__
__rmatmul__
nb_inplace_matrix_multiply binaryfunc __imatmul__
bf_getbuffer getbufferproc()
bf_releasebuffer releasebufferproc()
typedef
typedef
allocfunc PyObject *
PyTypeObject *
Py_ssize_t
newfunc PyObject *
PyObject *
PyObject *
PyObject *
initproc int
PyObject *
PyObject *
PyObject *
setattrfunc int
PyObject *
const char *
PyObject *
getattrofunc PyObject *
PyObject *
PyObject *
setattrofunc int
PyObject *
PyObject *
PyObject *
descrgetfunc PyObject *
PyObject *
PyObject *
PyObject *
descrsetfunc int
PyObject *
PyObject *
12.3. PyObject * 245
12.3.2 PyTypeObject
PyTypeObject Include/object.h
:
destructor tp_dealloc;
Py_ssize_t tp_vectorcall_offset;
getattrfunc tp_getattr;
setattrfunc tp_setattr;
PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
or tp_reserved (Python 3) */
reprfunc tp_repr;
PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;
hashfunc tp_hash;
ternaryfunc tp_call;
reprfunc tp_str;
getattrofunc tp_getattro;
setattrofunc tp_setattro;
/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
( )
( )
destructor tp_finalize;
vectorcallfunc tp_vectorcall;
12.3.3 PyObject
PyTypeObject *PyObject.ob_type
ABI. PyObject_HEAD_INIT
&PyType_Type
Windows NULL
PyObject_HEAD_INIT
Foo_Type.ob_type = &PyType_Type;
12.3. 247
The Python/C API, 3.12.1
PyObject *PyObject._ob_next
PyObject *PyObject._ob_prev
Py_TRACE_REFS configure --with-trace-refs
option
PyObject_HEAD_INIT NULL
NULL
sys.getobjects()
PYTHONDUMPREFS
12.3.4 PyVarObject
Py_ssize_t PyVarObject.ob_size
ABI. 0
12.3.5 PyTypeObject
PyType_Ready() NULL
PyBaseObject_Type PyType_Type
P Q M
T tp_name "P.Q.M.T"
'__module__'
tp_name
__module__ __name__
tp_name __name__ __module__
pickle
pydoc
NULL PyTypeObject() tp_itemsize
Py_ssize_t PyTypeObject.tp_basicsize
Py_ssize_t PyTypeObject.tp_itemsize
tp_itemsize
tp_itemsize
tp_basicsize
ob_size tp_basicsize
N tp_itemsize N N ob_size
ob_size N abs(ob_size)
ob_size
ob_size
PyObject_HEAD PyObject_VAR_HEAD
_ob_prev _ob_next
tp_basicsize sizeof
GC
tp_basicsize
double tp_itemsize sizeof(double)
tp_basicsize sizeof(double) double
NULL
tp_itemsize
tp_itemsize
destructor PyTypeObject.tp_dealloc
None Ellipsis
Py_DECREF() Py_XDECREF()
tp_free Py_TPFLAGS_BASETYPE
tp_free
PyObject_New PyObject_NewVar
PyObject_Del() PyObject_GC_New PyObject_GC_NewVar
PyObject_GC_Del()
Py_TPFLAGS_HAVE_GC
PyObject_GC_UnTrack()
(Py_TPFLAGS_HEAPTYPE)
( Py_DECREF())
12.3. 249
The Python/C API, 3.12.1
Py_ssize_t PyTypeObject.tp_vectorcall_offset
vectorcall
tp_call
Py_TPFLAGS_HAVE_VECTORCALL
vectorcallfunc
vectorcallfunc NULL Py_TPFLAGS_HAVE_VECTORCALL
tp_call
Py_TPFLAGS_HAVE_VECTORCALL tp_call vector-
callfunc tp_call PyVectorcall_Call()
3.8 : 3.8 tp_print Python 2.x
Python 3.0 3.7
3.12 : 3.12 vectorcall Python
__call__ tp_call vectorcall 3.12
__call__ Py_TPFLAGS_HAVE_VECTORCALL vectorcall
Py_TPFLAGS_HAVE_VECTORCALL
vectorcall PyVectorcall_Call()
getattrfunc PyTypeObject.tp_getattr
tp_getattro C
Python
: tp_getattr, tp_getattro
tp_getattro tp_getattr tp_getattro NULL
tp_getattr tp_getattro
setattrfunc PyTypeObject.tp_setattr
tp_setattro C
Python
: tp_setattr, tp_setattro
tp_setattro tp_setattr tp_setattro
NULL tp_setattr tp_setattro
PyAsyncMethods *PyTypeObject.tp_as_async
C awaitable asynchronous iterator
Async Object Structures
3.5 : tp_compare tp_reserved
tp_as_async
reprfunc PyTypeObject.tp_repr
repr()
PyObject_Repr() :
Unicode
eval()
'<' '>'
tp_as_number
PySequenceMethods *PyTypeObject.tp_as_sequence
tp_as_sequence
PyMappingMethods *PyTypeObject.tp_as_mapping
tp_as_mapping
hashfunc PyTypeObject.tp_hash
hash()
PyObject_Hash() :
-1 -1
tp_richcompare TypeError
PyObject_HashNotImplemented()
PyObject_HashNotImplemented()
Python __hash__ = None isinstance(o, collections.
Hashable) False. Python __hash__
= None tp_hash PyObject_HashNotImplemented()
: tp_hash, tp_richcompare
This field is inherited by subtypes together with tp_richcompare: a subtype inherits both of
tp_richcompare and tp_hash, when the subtype’s tp_richcompare and tp_hash are both NULL.
ternaryfunc PyTypeObject.tp_call
An optional pointer to a function that implements calling the object. This should be NULL if the object is not
callable. The signature is the same as for PyObject_Call():
12.3. 251
The Python/C API, 3.12.1
reprfunc PyTypeObject.tp_str
An optional pointer to a function that implements the built-in operation str(). (Note that str is a type now,
and str() calls the constructor for that type. This constructor calls PyObject_Str() to do the actual
work, and PyObject_Str() will call this handler.)
The signature is the same as for PyObject_Str():
The function must return a string or a Unicode object. It should be a ”friendly” string representation of the
object, as this is the representation that will be used, among other things, by the print() function.
When this field is not set, PyObject_Repr() is called to return a string representation.
getattrofunc PyTypeObject.tp_getattro
An optional pointer to the get-attribute function.
The signature is the same as for PyObject_GetAttr():
It is usually convenient to set this field to PyObject_GenericGetAttr(), which implements the normal
way of looking for object attributes.
: tp_getattr, tp_getattro
This field is inherited by subtypes together with tp_getattr: a subtype inherits both tp_getattr and
tp_getattro from its base type when the subtype’s tp_getattr and tp_getattro are both NULL.
In addition, setting value to NULL to delete an attribute must be supported. It is usually convenient to set this
field to PyObject_GenericSetAttr(), which implements the normal way of setting object attributes.
: tp_setattr, tp_setattro
This field is inherited by subtypes together with tp_setattr: a subtype inherits both tp_setattr and
tp_setattro from its base type when the subtype’s tp_setattr and tp_setattro are both NULL.
PyBufferProcs *PyTypeObject.tp_as_buffer
Pointer to an additional structure that contains fields relevant only to objects which implement the buffer in-
terface. These fields are documented in Buffer Object Structures.
The tp_as_buffer field is not inherited, but the contained fields are inherited individually.
unsigned long PyTypeObject.tp_flags
This field is a bit mask of various flags. Some flags indicate variant semantics for certain situations; oth-
ers are used to indicate that certain fields in the type object (or in the extension structures referenced via
tp_as_number, tp_as_sequence, tp_as_mapping, and tp_as_buffer) that were historically
not always present are valid; if such a flag bit is clear, the type fields it guards must not be accessed and must
be considered to have a zero or NULL value instead.
Inheritance of this field is complicated. Most flag bits are inherited individually, i.e. if the base type has a flag
bit set, the subtype inherits this flag bit. The flag bits that pertain to extension structures are strictly inherited if
the extension structure is inherited, i.e. the base type’s value of the flag bit is copied into the subtype together
with a pointer to the extension structure. The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the
tp_traverse and tp_clear fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype
and the tp_traverse and tp_clear fields in the subtype exist and have NULL values. .. XXX are most
flag bits really inherited individually?
Py_TPFLAGS_HEAPTYPE
This bit is set when the type object itself is allocated on the heap, for example, types created dynamically
using PyType_FromSpec(). In this case, the ob_type field of its instances is considered a reference
to the type, and the type object is INCREF’ed when a new instance is created, and DECREF’ed when
an instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the
instance’s ob_type gets INCREF’ed or DECREF’ed).
Py_TPFLAGS_BASETYPE
Java ”final”
Py_TPFLAGS_READY
PyType_Ready()
Py_TPFLAGS_READYING
PyType_Ready()
12.3. 253
The Python/C API, 3.12.1
Py_TPFLAGS_HAVE_GC
This bit is set when the object supports garbage collection. If this bit is set, instances must be created using
PyObject_GC_New and destroyed using PyObject_GC_Del(). More information in section
. This bit also implies that the GC-related fields tp_traverse and
tp_clear are present in the type object.
Py_TPFLAGS_METHOD_DESCRIPTOR
This bit indicates that objects behave like unbound methods.
If this flag is set for type(meth), then:
• meth.__get__(obj, cls)(*args, **kwds) (with obj not None) must be equivalent
to meth(obj, *args, **kwds).
• meth.__get__(None, cls)(*args, **kwds) must be equivalent to meth(*args,
**kwds).
This flag enables an optimization for typical method calls like obj.meth(): it avoids creating a tem-
porary ”bound method” object for obj.meth.
3.8 .
This flag is never inherited by types without the Py_TPFLAGS_IMMUTABLETYPE flag set. For exten-
sion types, it is inherited whenever tp_descr_get is inherited.
Py_TPFLAGS_MANAGED_DICT
This bit indicates that instances of the class have a __dict__ attribute, and that the space for the
dictionary is managed by the VM.
If this flag is set, Py_TPFLAGS_HAVE_GC should also be set.
3.12 .
Py_TPFLAGS_ITEMS_AT_END
Only usable with variable-size types, i.e. ones with non-zero tp_itemsize.
Indicates that the variable-sized portion of an instance of this type is at the end of the instance’s memory
area, at an offset of Py_TYPE(obj)->tp_basicsize (which may be different in each subclass).
When setting this flag, be sure that all superclasses either use this memory layout, or are not variable-sized.
Python does not check this.
3.12 .
Py_TPFLAGS_LIST_SUBCLASS
Py_TPFLAGS_TUPLE_SUBCLASS
Py_TPFLAGS_BYTES_SUBCLASS
Py_TPFLAGS_UNICODE_SUBCLASS
Py_TPFLAGS_DICT_SUBCLASS
Py_TPFLAGS_BASE_EXC_SUBCLASS
Py_TPFLAGS_TYPE_SUBCLASS
These flags are used by functions such as PyLong_Check() to quickly determine if a type
is a subclass of a built-in type; such specific checks are faster than a generic check, like
PyObject_IsInstance(). Custom types that inherit from built-ins should have their tp_flags
set appropriately, or the code that interacts with such types will behave differently depending on what
kind of check is used.
Py_TPFLAGS_HAVE_FINALIZE
tp_finalize
3.4 .
3.8 :
tp_finalize
Py_TPFLAGS_HAVE_VECTORCALL
vectorcall tp_vectorcall_offset
tp_call
3.9 .
3.12 : __call__()
Py_TPFLAGS_IMMUTABLETYPE
PyType_Ready()
3.10 .
12.3. 255
The Python/C API, 3.12.1
Py_TPFLAGS_DISALLOW_INSTANTIATION
tp_new NULL __new__
PyType_Ready()
The flag is set automatically on static types if tp_base is NULL or &PyBaseObject_Type and
tp_new is NULL.
This flag is not inherited. However, subclasses will not be instantiable unless they provide a non-NULL
tp_new (which is only possible via the C API).
3.10 .
Py_TPFLAGS_MAPPING
This bit indicates that instances of the class may match mapping patterns when used as the subject of a
match block. It is automatically set when registering or subclassing collections.abc.Mapping,
and unset when registering collections.abc.Sequence.
: This flag is present in header files, but is an internal feature and should not be used. It will be
removed in a future version of CPython
More information about Python’s garbage collection scheme can be found in section
.
The tp_traverse pointer is used by the garbage collector to detect reference cycles. A typical imple-
mentation of a tp_traverse function simply calls Py_VISIT() on each of the instance’s members that
are Python objects that the instance owns. For example, this is function local_traverse() from the
_thread extension module:
static int
local_traverse(localobject *self, visitproc visit, void *arg)
{
Py_VISIT(self->args);
Py_VISIT(self->kw);
Py_VISIT(self->dict);
return 0;
}
Note that Py_VISIT() is called only on those members that can participate in reference cycles. Although
there is also a self->key member, it can only be NULL or a Python string and therefore cannot be part of
a reference cycle.
On the other hand, even if you know a member can never be part of a cycle, as a debugging aid you may want
to visit it anyway just so the gc module’s get_referents() function will include it.
: When implementing tp_traverse, only the members that the instance owns (by having
strong references to them) must be visited. For instance, if an object supports weak references via the
tp_weaklist slot, the pointer supporting the linked list (what tp_weaklist points to) must not be visited
as the instance does not directly own the weak references to itself (the weakreference list is there to support
the weak reference machinery, but the instance has no strong reference to the elements inside it, as they
are allowed to be removed even if the instance is still alive).
Note that Py_VISIT() requires the visit and arg parameters to local_traverse() to have these specific
names; don’t name them just anything.
Instances of heap-allocated types hold a reference to their type. Their traversal function must therefore either
visit Py_TYPE(self), or delegate this responsibility by calling tp_traverse of another heap-allocated
type (such as a heap-allocated superclass). If they do not, the type object may not be garbage-collected.
3.9 : Heap-allocated types are expected to visit Py_TYPE(self) in tp_traverse. In earlier
versions of Python, due to bug 40217, doing this may lead to crashes in subclasses.
12.3. 257
The Python/C API, 3.12.1
inquiry PyTypeObject.tp_clear
An optional pointer to a clear function for the garbage collector. This is only used if the
Py_TPFLAGS_HAVE_GC flag bit is set. The signature is:
The tp_clear member function is used to break reference cycles in cyclic garbage detected by the garbage
collector. Taken together, all tp_clear functions in the system must combine to break all reference cycles.
This is subtle, and if in any doubt supply a tp_clear function. For example, the tuple type does not imple-
ment a tp_clear function, because it’s possible to prove that no reference cycle can be composed entirely
of tuples. Therefore the tp_clear functions of other types must be sufficient to break any cycle containing
a tuple. This isn’t immediately obvious, and there’s rarely a good reason to avoid implementing tp_clear.
Implementations of tp_clear should drop the instance’s references to those of its members that may be
Python objects, and set its pointers to those members to NULL, as in the following example:
static int
local_clear(localobject *self)
{
Py_CLEAR(self->key);
Py_CLEAR(self->args);
Py_CLEAR(self->kw);
Py_CLEAR(self->dict);
return 0;
}
The Py_CLEAR() macro should be used, because clearing references is delicate: the reference to the con-
tained object must not be released (via Py_DECREF()) until after the pointer to the contained object is set
to NULL. This is because releasing the reference may cause the contained object to become trash, triggering
a chain of reclamation activity that may include invoking arbitrary Python code (due to finalizers, or weakref
callbacks, associated with the contained object). If it’s possible for such code to reference self again, it’s im-
portant that the pointer to the contained object be NULL at that time, so that self knows the contained object
can no longer be used. The Py_CLEAR() macro performs the operations in a safe order.
Note that tp_clear is not always called before an instance is deallocated. For example, when reference
counting is enough to determine that an object is no longer used, the cyclic garbage collector is not involved
and tp_dealloc is called directly.
Because the goal of tp_clear functions is to break reference cycles, it’s not necessary to clear contained
objects like Python strings or Python integers, which can’t participate in reference cycles. On the other hand, it
may be convenient to clear all contained Python objects, and write the type’s tp_dealloc function to invoke
tp_clear.
More information about Python’s garbage collection scheme can be found in section
.
The first parameter is guaranteed to be an instance of the type that is defined by PyTypeObject.
The function should return the result of the comparison (usually Py_True or Py_False). If the comparison
is undefined, it must return Py_NotImplemented, if another error occurred it must return NULL and set
an exception condition.
The following constants are defined to be used as the third argument for tp_richcompare and for
PyObject_RichCompare():
<
Py_LT
<=
Py_LE
==
Py_EQ
!=
Py_NE
>
Py_GT
>=
Py_GE
: tp_hash, tp_richcompare
This field is inherited by subtypes together with tp_hash: a subtype inherits tp_richcompare and
tp_hash when the subtype’s tp_richcompare and tp_hash are both NULL.
12.3. 259
The Python/C API, 3.12.1
This field is inherited by subtypes, but see the rules listed below. A subtype may override this offset; this means
that the subtype uses a different weak reference list head than the base type. Since the list head is always found
via tp_weaklistoffset, this should not be a problem.
iternextfunc PyTypeObject.tp_iternext
iterator :
When the iterator is exhausted, it must return NULL; a StopIteration exception may or may not be set.
When another error occurs, it must return NULL too. Its presence signals that the instances of this type are
iterators.
Iterator types should also define the tp_iter function, and that function should return the iterator instance
itself (not a new iterator instance).
This function has the same signature as PyIter_Next().
This field is not inherited by subtypes (methods are inherited through a different mechanism).
struct PyMemberDef *PyTypeObject.tp_members
An optional pointer to a static NULL-terminated array of PyMemberDef structures, declaring regular data
members (fields or slots) of instances of this type.
For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a
member descriptor.
This field is not inherited by subtypes (members are inherited through a different mechanism).
struct PyGetSetDef *PyTypeObject.tp_getset
An optional pointer to a static NULL-terminated array of PyGetSetDef structures, declaring computed
attributes of instances of this type.
For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a getset
descriptor.
This field is not inherited by subtypes (computed attributes are inherited through a different mechanism).
PyTypeObject *PyTypeObject.tp_base
An optional pointer to a base type from which type properties are inherited. At this level, only single inheritance
is supported; multiple inheritance require dynamically creating a type object by calling the metatype.
: Slot initialization is subject to the rules of initializing globals. C99 requires the initializers to be ”address
constants”. Function designators like PyType_GenericNew(), with implicit conversion to a pointer, are
valid C99 address constants.
However, the unary ’&’ operator applied to a non-static variable like PyBaseObject_Type is not required
to produce an address constant. Compilers may support this (gcc does), MSVC does not. Both compilers are
strictly standard conforming in this particular behavior.
Consequently, tp_base should be set in the extension module’s init function.
This field defaults to &PyBaseObject_Type (which to Python programmers is known as the type
object).
PyObject *PyTypeObject.tp_dict
The type’s dictionary is stored here by PyType_Ready().
This field should normally be initialized to NULL before PyType_Ready is called; it may also be initialized to
a dictionary containing initial attributes for the type. Once PyType_Ready() has initialized the type, extra
attributes for the type may be added to this dictionary only if they don’t correspond to overloaded operations
(like __add__()). Once initialization for the type has finished, this field should be treated as read-only.
Some types may not store their dictionary in this slot. Use PyType_GetDict() to retrieve the dictionary
for an arbitrary type.
3.12 : Internals detail: For static builtin types, this is always NULL. Instead, the dict for such types
is stored on PyInterpreterState. Use PyType_GetDict() to get the dict for an arbitrary type.
This field is not inherited by subtypes (though the attributes defined in here are inherited through a different
mechanism).
: It is not safe to use PyDict_SetItem() on or otherwise modify tp_dict with the dictionary
C-API.
descrgetfunc PyTypeObject.tp_descr_get
An optional pointer to a ”descriptor get” function.
:
12.3. 261
The Python/C API, 3.12.1
descrsetfunc PyTypeObject.tp_descr_set
An optional pointer to a function for setting and deleting a descriptor’s value.
:
Py_ssize_t PyTypeObject.tp_dictoffset
While this field is still supported, Py_TPFLAGS_MANAGED_DICT should be used instead, if at all possible.
If the instances of this type have a dictionary containing instance variables, this field is non-zero and
contains the offset in the instances of the type of the instance variable dictionary; this offset is used by
PyObject_GenericGetAttr().
Do not confuse this field with tp_dict; that is the dictionary for attributes of the type object itself.
The value specifies the offset of the dictionary from the start of the instance structure.
The tp_dictoffset should be regarded as write-only. To get the pointer to the dictionary call
PyObject_GenericGetDict(). Calling PyObject_GenericGetDict() may need to allocate
memory for the dictionary, so it is may be more efficient to call PyObject_GetAttr() when accessing
an attribute on the object.
It is an error to set both the Py_TPFLAGS_MANAGED_WEAKREF bit and tp_dictoffset.
This field is inherited by subtypes. A subtype should not override this offset; doing so could be un-
safe, if C code tries to access the dictionary at the previous offset. To properly support inheritance, use
Py_TPFLAGS_MANAGED_DICT.
This slot has no default. For static types, if the field is NULL then no __dict__ gets created for instances.
If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_dict field, then tp_dictoffset will be set
to -1, to indicate that it is unsafe to use this field.
initproc PyTypeObject.tp_init
An optional pointer to an instance initialization function.
This function corresponds to the __init__() method of classes. Like __init__(), it is possible to
create an instance without calling __init__(), and it is possible to reinitialize an instance by calling its
__init__() method again.
:
The self argument is the instance to be initialized; the args and kwds arguments represent positional and keyword
arguments of the call to __init__().
The tp_init function, if not NULL, is called when an instance is created normally by calling its type, after
the type’s tp_new function has returned an instance of the type. If the tp_new function returns an instance
of some other type that is not a subtype of the original type, no tp_init function is called; if tp_new
returns an instance of a subtype of the original type, the subtype’s tp_init is called.
0 -1 and sets an exception on error.
allocfunc PyTypeObject.tp_alloc
This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement).
For dynamic subtypes, this field is always set to PyType_GenericAlloc(), to force a standard heap
allocation strategy.
For static subtypes, PyBaseObject_Type uses PyType_GenericAlloc(). That is the recommended
value for all statically defined types.
newfunc PyTypeObject.tp_new
An optional pointer to an instance creation function.
:
The subtype argument is the type of the object being created; the args and kwds arguments represent positional
and keyword arguments of the call to the type. Note that subtype doesn’t have to equal the type whose tp_new
function is called; it may be a subtype of that type (but not an unrelated type).
The tp_new function should call subtype->tp_alloc(subtype, nitems) to allocate space for
the object, and then do only as much further initialization as is absolutely necessary. Initialization that can
safely be ignored or repeated should be placed in the tp_init handler. A good rule of thumb is that for
immutable types, all initialization should take place in tp_new, while for mutable types, most initialization
should be deferred to tp_init.
Set the Py_TPFLAGS_DISALLOW_INSTANTIATION flag to disallow creating instances of the type in
Python.
This field is inherited by subtypes, except it is not inherited by static types whose tp_base is NULL or
&PyBaseObject_Type.
For static types this field has no default. This means if the slot is defined as NULL, the type cannot be called to
create new instances; presumably there is some other way to create instances, like a factory function.
freefunc PyTypeObject.tp_free
An optional pointer to an instance deallocation function. Its signature is:
This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement)
In dynamic subtypes, this field is set to a deallocator suitable to match PyType_GenericAlloc() and the
value of the Py_TPFLAGS_HAVE_GC flag bit.
12.3. 263
The Python/C API, 3.12.1
The garbage collector needs to know whether a particular object is collectible or not. Normally, it is sufficient
to look at the object’s type’s tp_flags field, and check the Py_TPFLAGS_HAVE_GC flag bit. But some
types have a mixture of statically and dynamically allocated instances, and the statically allocated instances are
not collectible. Such types should define this function; it should return 1 for a collectible instance, and 0 for a
non-collectible instance. The signature is:
(The only example of this are types themselves. The metatype, PyType_Type, defines this function to
distinguish between statically and dynamically allocated types.)
This slot has no default. If this field is NULL, Py_TPFLAGS_HAVE_GC is used as the functional equivalent.
PyObject *PyTypeObject.tp_bases
Tuple of base types.
This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.
For dynamically created classes, the Py_tp_bases slot can be used instead of the bases argument of
PyType_FromSpecWithBases(). The argument form is preferred.
: Multiple inheritance does not work well for statically defined types. If you set tp_bases to a
tuple, Python will not raise an error, but some slots will only be inherited from the first base.
PyObject *PyTypeObject.tp_mro
object
This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.
PyType_Ready()
PyObject *PyTypeObject.tp_cache
void *PyTypeObject.tp_subclasses
A collection of subclasses. Internal use only. May be an invalid pointer.
To get a list of subclasses, call the Python method __subclasses__().
3.12 : For some types, this field does not hold a valid PyObject*. The type was changed to
void* to indicate this.
PyObject *PyTypeObject.tp_weaklist
Weak reference list head, for weak references to this type object. Not inherited. Internal use only.
3.12 : Internals detail: For the static builtin types this is always NULL, even if weakrefs are added.
Instead, the weakrefs for each are stored on PyInterpreterState. Use the public C-API or the internal
_PyObject_GET_WEAKREFS_LISTPTR() macro to avoid the distinction.
destructor PyTypeObject.tp_del
This field is deprecated. Use tp_finalize instead.
unsigned int PyTypeObject.tp_version_tag
Used to index into the method cache. Internal use only.
destructor PyTypeObject.tp_finalize
An optional pointer to an instance finalization function. Its signature is:
void tp_finalize(PyObject *self);
If tp_finalize is set, the interpreter calls it once when finalizing an instance. It is called either from the
garbage collector (if the instance is part of an isolated reference cycle) or just before the object is deallocated.
Either way, it is guaranteed to be called before attempting to break reference cycles, ensuring that it finds the
object in a sane state.
tp_finalize should not mutate the current exception status; therefore, a recommended way to write a
non-trivial finalizer is:
static void
local_finalize(PyObject *self)
{
PyObject *error_type, *error_value, *error_traceback;
/* ... */
Also, note that, in a garbage collected Python, tp_dealloc may be called from any Python thread, not just
the thread which created the object (if the object becomes part of a refcount cycle, that cycle might be collected
by a garbage collection on any thread). This is not a problem for Python API calls, since the thread on which
tp_dealloc is called will own the Global Interpreter Lock (GIL). However, if the object being destroyed in turn
destroys objects from some other C or C++ library, care should be taken to ensure that destroying those objects
on the thread which called tp_dealloc will not violate any assumptions of the library.
3.4 .
3.8 : Before version 3.8 it was necessary to set the Py_TPFLAGS_HAVE_FINALIZE flags bit in
order for this field to be used. This is no longer required.
:
”Safe object finalization” (PEP 442)
12.3. 265
The Python/C API, 3.12.1
vectorcallfunc PyTypeObject.tp_vectorcall
Vectorcall function to use for calls of this type object. In other words, it is used to implement vectorcall for
type.__call__. If tp_vectorcall is NULL, the default call implementation using __new__() and
__init__() is used.
Traditionally, types defined in C code are static, that is, a static PyTypeObject structure is defined directly in code
and initialized using PyType_Ready().
This results in types that are limited relative to types defined in Python:
• Static types are limited to one base, i.e. they cannot use multiple inheritance.
• Static type objects (but not necessarily their instances) are immutable. It is not possible to add or modify the
type object’s attributes from Python.
• Static type objects are shared across sub-interpreters, so they should not include any subinterpreter-specific
state.
Also, since PyTypeObject is only part of the Limited API as an opaque struct, any extension modules using static
types must be compiled for a specific Python minor version.
12.3.7
An alternative to static types is heap-allocated types, or heap types for short, which correspond closely to classes
created by Python’s class statement. Heap types have the Py_TPFLAGS_HEAPTYPE flag set.
This is done by filling a PyType_Spec structure and calling PyType_FromSpec(),
PyType_FromSpecWithBases(), PyType_FromModuleAndSpec(), or
PyType_FromMetaclass().
type PyNumberMethods
This structure holds pointers to the functions which an object uses to implement the number protocol. Each
function is used by the function of similar name documented in the section.
Here is the structure definition:
typedef struct {
binaryfunc nb_add;
binaryfunc nb_subtract;
binaryfunc nb_multiply;
binaryfunc nb_remainder;
binaryfunc nb_divmod;
ternaryfunc nb_power;
unaryfunc nb_negative;
unaryfunc nb_positive;
( )
( )
unaryfunc nb_absolute;
inquiry nb_bool;
unaryfunc nb_invert;
binaryfunc nb_lshift;
binaryfunc nb_rshift;
binaryfunc nb_and;
binaryfunc nb_xor;
binaryfunc nb_or;
unaryfunc nb_int;
void *nb_reserved;
unaryfunc nb_float;
binaryfunc nb_inplace_add;
binaryfunc nb_inplace_subtract;
binaryfunc nb_inplace_multiply;
binaryfunc nb_inplace_remainder;
ternaryfunc nb_inplace_power;
binaryfunc nb_inplace_lshift;
binaryfunc nb_inplace_rshift;
binaryfunc nb_inplace_and;
binaryfunc nb_inplace_xor;
binaryfunc nb_inplace_or;
binaryfunc nb_floor_divide;
binaryfunc nb_true_divide;
binaryfunc nb_inplace_floor_divide;
binaryfunc nb_inplace_true_divide;
unaryfunc nb_index;
binaryfunc nb_matrix_multiply;
binaryfunc nb_inplace_matrix_multiply;
} PyNumberMethods;
: Binary and ternary functions must check the type of all their operands, and implement the necessary
conversions (at least one of the operands is an instance of the defined type). If the operation is not defined
for the given operands, binary and ternary functions must return Py_NotImplemented, if another error
occurred they must return NULL and set an exception.
: The nb_reserved field should always be NULL. It was previously called nb_long, and was re-
named in Python 3.0.1.
binaryfunc PyNumberMethods.nb_add
binaryfunc PyNumberMethods.nb_subtract
binaryfunc PyNumberMethods.nb_multiply
binaryfunc PyNumberMethods.nb_remainder
binaryfunc PyNumberMethods.nb_divmod
ternaryfunc PyNumberMethods.nb_power
unaryfunc PyNumberMethods.nb_negative
unaryfunc PyNumberMethods.nb_positive
unaryfunc PyNumberMethods.nb_absolute
inquiry PyNumberMethods.nb_bool
unaryfunc PyNumberMethods.nb_invert
binaryfunc PyNumberMethods.nb_lshift
binaryfunc PyNumberMethods.nb_rshift
binaryfunc PyNumberMethods.nb_and
binaryfunc PyNumberMethods.nb_xor
binaryfunc PyNumberMethods.nb_or
unaryfunc PyNumberMethods.nb_int
void *PyNumberMethods.nb_reserved
unaryfunc PyNumberMethods.nb_float
binaryfunc PyNumberMethods.nb_inplace_add
binaryfunc PyNumberMethods.nb_inplace_subtract
binaryfunc PyNumberMethods.nb_inplace_multiply
binaryfunc PyNumberMethods.nb_inplace_remainder
ternaryfunc PyNumberMethods.nb_inplace_power
binaryfunc PyNumberMethods.nb_inplace_lshift
binaryfunc PyNumberMethods.nb_inplace_rshift
binaryfunc PyNumberMethods.nb_inplace_and
binaryfunc PyNumberMethods.nb_inplace_xor
binaryfunc PyNumberMethods.nb_inplace_or
binaryfunc PyNumberMethods.nb_floor_divide
binaryfunc PyNumberMethods.nb_true_divide
binaryfunc PyNumberMethods.nb_inplace_floor_divide
binaryfunc PyNumberMethods.nb_inplace_true_divide
unaryfunc PyNumberMethods.nb_index
binaryfunc PyNumberMethods.nb_matrix_multiply
binaryfunc PyNumberMethods.nb_inplace_matrix_multiply
type PyMappingMethods
This structure holds pointers to the functions which an object uses to implement the mapping protocol. It has
three members:
lenfunc PyMappingMethods.mp_length
This function is used by PyMapping_Size() and PyObject_Size(), and has the same signature. This
slot may be set to NULL if the object has no defined length.
binaryfunc PyMappingMethods.mp_subscript
This function is used by PyObject_GetItem() and PySequence_GetSlice(), and has the same
signature as PyObject_GetItem(). This slot must be filled for the PyMapping_Check() function to
return 1, it can be NULL otherwise.
objobjargproc PyMappingMethods.mp_ass_subscript
This function is used by PyObject_SetItem(), PyObject_DelItem(),
PySequence_SetSlice() and PySequence_DelSlice(). It has the same signature as
PyObject_SetItem(), but v can also be set to NULL to delete an item. If this slot is NULL, the
object does not support item assignment and deletion.
type PySequenceMethods
This structure holds pointers to the functions which an object uses to implement the sequence protocol.
lenfunc PySequenceMethods.sq_length
This function is used by PySequence_Size() and PyObject_Size(), and has the same signature. It
is also used for handling negative indices via the sq_item and the sq_ass_item slots.
binaryfunc PySequenceMethods.sq_concat
This function is used by PySequence_Concat() and has the same signature. It is also used by the +
operator, after trying the numeric addition via the nb_add slot.
ssizeargfunc PySequenceMethods.sq_repeat
This function is used by PySequence_Repeat() and has the same signature. It is also used by the *
operator, after trying numeric multiplication via the nb_multiply slot.
ssizeargfunc PySequenceMethods.sq_item
This function is used by PySequence_GetItem() and has the same signature. It is also used by
PyObject_GetItem(), after trying the subscription via the mp_subscript slot. This slot must be
filled for the PySequence_Check() function to return 1, it can be NULL otherwise.
Negative indexes are handled as follows: if the sq_length slot is filled, it is called and the sequence length is
used to compute a positive index which is passed to sq_item. If sq_length is NULL, the index is passed
as is to the function.
ssizeobjargproc PySequenceMethods.sq_ass_item
This function is used by PySequence_SetItem() and has the same signature. It is also used by
PyObject_SetItem() and PyObject_DelItem(), after trying the item assignment and deletion via
the mp_ass_subscript slot. This slot may be left to NULL if the object does not support item assignment
and deletion.
objobjproc PySequenceMethods.sq_contains
PySequence_Contains() NULL
PySequence_Contains()
binaryfunc PySequenceMethods.sq_inplace_concat
This function is used by PySequence_InPlaceConcat() and has the same signature. It
should modify its first operand, and return it. This slot may be left to NULL, in this case
PySequence_InPlaceConcat() will fall back to PySequence_Concat(). It is also used by the
augmented assignment +=, after trying numeric in-place addition via the nb_inplace_add slot.
ssizeargfunc PySequenceMethods.sq_inplace_repeat
This function is used by PySequence_InPlaceRepeat() and has the same signature. It
should modify its first operand, and return it. This slot may be left to NULL, in this case
PySequence_InPlaceRepeat() will fall back to PySequence_Repeat(). It is also used by the
augmented assignment *=, after trying numeric in-place multiplication via the nb_inplace_multiply
slot.
type PyBufferProcs
This structure holds pointers to the functions required by the Buffer protocol. The protocol defines how an
exporter object can expose its internal data to consumer objects.
getbufferproc PyBufferProcs.bf_getbuffer
The signature of this function is:
Handle a request to exporter to fill in view as specified by flags. Except for point (3), an implementation of this
function MUST take these steps:
(1) Check if the request can be met. If not, raise BufferError, set view->obj to NULL and return
-1.
(2) Fill in the requested fields.
(3) Increment an internal counter for the number of exports.
(4) Set view->obj to exporter and increment view->obj.
(5) Return 0.
If exporter is part of a chain or tree of buffer providers, two main schemes can be used:
• Re-export: Each member of the tree acts as the exporting object and sets view->obj to a new reference
to itself.
• Redirect: The buffer request is redirected to the root object of the tree. Here, view->obj will be a
new reference to the root object.
The individual fields of view are described in section Buffer structure, the rules how an exporter must react to
specific requests are in section Buffer request types.
All memory pointed to in the Py_buffer structure belongs to the exporter and must remain valid until there
are no consumers left. format, shape, strides, suboffsets and internal are read-only for the
consumer.
PyBuffer_FillInfo() provides an easy way of exposing a simple bytes buffer while dealing correctly
with all request types.
PyObject_GetBuffer() is the interface for the consumer that wraps this function.
releasebufferproc PyBufferProcs.bf_releasebuffer
The signature of this function is:
Handle a request to release the resources of the buffer. If no resources need to be released,
PyBufferProcs.bf_releasebuffer may be NULL. Otherwise, a standard implementation of this
function will take these optional steps:
(1) Decrement an internal counter for the number of exports.
(2) If the counter is 0, free all memory associated with view.
The exporter MUST use the internal field to keep track of buffer-specific resources. This field is guaranteed
to remain constant, while a consumer MAY pass a copy of the original buffer as the view argument.
This function MUST NOT decrement view->obj, since that is done automatically in
PyBuffer_Release() (this scheme is useful for breaking reference cycles).
PyBuffer_Release() is the interface for the consumer that wraps this function.
3.5 .
type PyAsyncMethods
This structure holds pointers to the functions required to implement awaitable and asynchronous iterator ob-
jects.
Here is the structure definition:
typedef struct {
unaryfunc am_await;
unaryfunc am_aiter;
unaryfunc am_anext;
sendfunc am_send;
} PyAsyncMethods;
unaryfunc PyAsyncMethods.am_await
The signature of this function is:
iterator PyIter_Check() 1
This slot may be set to NULL if an object is not an awaitable.
unaryfunc PyAsyncMethods.am_aiter
The signature of this function is:
Must return an awaitable object. See __anext__() for details. This slot may be set to NULL.
sendfunc PyAsyncMethods.am_send
The signature of this function is:
12.10
Python
defining-new-types new-types-topics
:
typedef struct {
PyObject_HEAD
const char *data;
} MyObject;
12.10. 273
The Python/C API, 3.12.1
CPython :
static PyTypeObject MyObject_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"mymod.MyObject", /* tp_name */
sizeof(MyObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)myobj_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
(reprfunc)myobj_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_flags */
PyDoc_STR("My objects"), /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
myobj_new, /* tp_new */
};
:
typedef struct {
PyObject_HEAD
const char *data;
} MyObject;
( )
.tp_repr = (reprfunc)myobj_repr,
.tp_hash = (hashfunc)myobj_hash,
.tp_richcompare = PyBaseObject_Type.tp_richcompare,
};
A str subclass that cannot be subclassed and cannot be called to create instances (e.g. uses a separate factory func)
using Py_TPFLAGS_DISALLOW_INSTANTIATION flag:
typedef struct {
PyUnicodeObject raw;
char *extra;
} MyStr;
typedef struct {
PyObject_HEAD
} MyObject;
typedef struct {
PyObject_VAR_HEAD
const char *data[1];
} MyObject;
12.11
Python
tp_flags Py_TPFLAGS_HAVE_GC
tp_traverse tp_clear
Py_TPFLAGS_HAVE_GC
12.11. 275
The Python/C API, 3.12.1
1. PyObject_GC_New PyObject_GC_NewVar
2. PyObject_GC_Track()
1. PyObject_GC_UnTrack()
2. PyObject_GC_Del()
: Py_TPFLAGS_HAVE_GC tp_traverse
PyType_Ready() API
PyType_FromSpecWithBases() PyType_FromSpec()
tp_flags, tp_traverse tp_clear
Py_TPFLAGS_HAVE_GC
PyObject_GC_New(TYPE, typeobj)
PyObject_New Py_TPFLAGS_HAVE_GC
PyObject_GC_NewVar(TYPE, typeobj, size)
PyObject_NewVar Py_TPFLAGS_HAVE_GC
PyObject *PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *type, size_t extra_size)
API
:
PyVarObject tp_itemsize
3.12 .
TYPE *PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize)
PyObject_NewVar NULL
op
void PyObject_GC_Track(PyObject *op)
ABI. op
tp_traverse
tp_traverse
typedef int (*traverseproc)(PyObject *self, visitproc visit, void *arg)
ABI. self visit
visit arg visit NULL
visit
tp_traverse Python Py_VISIT()
tp_traverse visit arg
void Py_VISIT(PyObject *o)
o NULL visit o arg visit
tp_traverse :
static int
my_traverse(Noddy *self, visitproc visit, void *arg)
{
Py_VISIT(self->foo);
Py_VISIT(self->bar);
return 0;
}
12.11. 277
The Python/C API, 3.12.1
12.11.1
C-API
Py_ssize_t PyGC_Collect(void)
ABI. gc.collect()
+
0 sys.unraisablehook
int PyGC_Enable(void)
ABI 3.10 . gc.enable() 0
1
3.10 .
int PyGC_Disable(void)
ABI 3.10 . gc.disable() 0
1
3.10 .
int PyGC_IsEnabled(void)
ABI 3.10 . gc.isenabled()
0 1
3.10 .
12.11.2
C-API
void PyUnstable_GC_VisitObjects(gcvisitobjects_t callback, void *arg)
API
3.12 .
typedef int (*gcvisitobjects_t)(PyObject *object, void *arg)
PyUnstable_GC_VisitObjects() arg
PyUnstable_GC_VisitObjects arg 0 1
3.12 .
API ABI
CPython
C API API ABI
PY_MAJOR_VERSION
3 (3.4.1a2 )
PY_MINOR_VERSION
4 (3.4.1a2 )
PY_MICRO_VERSION
1 (3.4.1a2 )
PY_RELEASE_LEVEL
a (3.4.1a2 3 ) 0xA alpha, 0xB beta, 0xC release candidate 0xF
final
PY_RELEASE_SERIAL
2 (3.4.1a2 )
PY_VERSION_HEX
Python
32 :
3.4.1a2
1 1-8 PY_MAJOR_VERSION 0x03
2 9-16 PY_MINOR_VERSION 0x04
3 17-24 PY_MICRO_VERSION 0x01
4 25-28 PY_RELEASE_LEVEL 0xA
29-32 PY_RELEASE_SERIAL 0x2
279
The Python/C API, 3.12.1
>>> Python
...
• Python
• Ellipsis
2to3 Python 2.x Python 3.x
__annotations__
variable annotation, function annotation, PEP 484 PEP 526
annotations-howto
argument -- function method
• : name= **
3 5 complex() :
complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})
• : /
* iterable 3 5 :
281
The Python/C API, 3.12.1
complex(3, 5)
complex(*(3, 5))
calls
strong reference
borrowed reference Py_INCREF() strong reference
Py_NewRef() strong
reference
bytes-like object -- C-contiguous bytes
bytearray array.array memoryview
282 Appendix A.
The Python/C API, 3.12.1
callback --
class --
class variable -- ( )
complex number --
-1 i j Python
j 3+1j math
cmath
contextvars
contiguous -- C Fortran C Fortran
C- Fortran
coroutine --
async def PEP 492
coroutine function -- coroutine async def
await async for async with PEP 492
CPython Python python.org ”CPython”
Jython IronPython
decorator -- @wrapper
classmethod() staticmethod()
:
def f(arg):
...
f = staticmethod(f)
@staticmethod
def f(arg):
...
283
The Python/C API, 3.12.1
Python
descriptors
dictionary -- __hash__()
__eq__() Perl hash
dictionary comprehension --
results = {n: n ** 2 for n in range(10)} n n **
2 comprehensions
dictionary view -- dict.keys(), dict.values() dict.items()
list(dictview) dict-views
docstring --
__doc__
duck-typing --
type() isinstance() ( )
hasattr() EAFP
EAFP Python
try except
LBYL C
expression --
statement while
/
: ,
io open()
file-like object -- file object
filesystem encoding and error handler -- Python
Unicode
128
API UnicodeError
sys.getfilesystemencoding() sys.getfilesystemencodeerrors()
284 Appendix A.
The Python/C API, 3.12.1
function
variable annotation PEP 484 annotations-howto
generator expression --
for if
:
generic function --
285
The Python/C API, 3.12.1
Python
frozenset
id()
IDLE Python idle Python
immutable --
/
interactive
interpreter shutdown -- Python
__main__
iterable --
list, str tuple dict, __iter__()
sequence __getitem__()
for (zip(), map(), ...)
iter()
iter()
for
iterator, sequence generator
iterator -- __next__() (
next()) StopIteration
__next__() StopIteration
__iter__()
286 Appendix A.
The Python/C API, 3.12.1
typeiter
CPython CPython __iter__()
key function --
locale.strxfrm()
Python min(), max(),
sorted(), list.sort(), heapq.merge(), heapq.nsmallest(), heapq.nlargest()
itertools.groupby()
str.lower()
lambda lambda r: (r[0], r[2]) operator.
attrgetter(), operator.itemgetter() operator.methodcaller()
287
The Python/C API, 3.12.1
metaclasses
method --
argument ( self) function nested scope
method resolution order --
Python 2.3 2.3 Python
module -- Python Python
importing Python
package
module spec -- importlib.
machinery.ModuleSpec
MRO method resolution order
mutable -- id() immutable
named tuple --
time.localtime() os.stat()
sys.float_info:
tuple
collections.
namedtuple()
namespace --
builtins.open
os.open()
random.seed() itertools.islice()
random itertools
namespace package -- PEP 420 package
regular package __init__.py
module
nested scope --
nonlocal
288 Appendix A.
The Python/C API, 3.12.1
• positional-or-keyword
foo bar:
• positional-only
/ posonly1 posonly2:
• keyword-only
*
kw_only1 kw_only2:
• var-positional
* args:
• var-keyword
** kwargs
PEP Python
PEP
PEP 1
portion -- zip
PEP 420
positional argument -- argument
provisional API -- API API
-- API
289
The Python/C API, 3.12.1
API
PEP
411
provisional package -- provisional API
Python 3000 Python 3.x 3
Py3k
Pythonic Python
Python for
Python
:
for i in range(len(food)):
print(food[i])
Pythonic :
qualified name --
PEP 3155
:
>>> class C:
... class D:
... def meth(self):
... pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'
email.mime.text:
reference count --
Python
CPython sys.getrefcount()
290 Appendix A.
The Python/C API, 3.12.1
collections.abc.Sequence __getitem__()
__len__() count(), index(), __contains__() __reversed__()
register()
set comprehension --
results = {c for c in 'abracadabra' if c not in 'abc'}
{'r', 'd'} comprehensions
single dispatch -- generic function
slice -- sequence []
variable_name[1:3:5]
slice
special method -- Python
specialnames
statement -- expression
if while for
static type checker -- Python
typing
strong reference -- Python C API
Py_INCREF() Py_DECREF()
Py_NewRef()
Py_DECREF()
borrowed reference
text encoding -- Python Unicode U+0000--
U+10FFFF
” ” ”
”
” ”
text file -- str file object
text encoding 'r' 'w'
sys.stdin sys.stdout io.StringIO
binary file
triple-quoted string -- ” ’
type -- Python
__class__ type(obj)
type alias --
:
def remove_gray_shades(
colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
pass
291
The Python/C API, 3.12.1
class C:
field: 'annotation'
int :
count: int = 0
annassign
function annotation, PEP 484 PEP 526 annotations-howto
292 Appendix A.
APPENDIX B
Python
reporting-bugs
B.1 Python
Python Python
293
The Python/C API, 3.12.1
294 Appendix B.
APPENDIX C
C.1
GPL
0.9.0 1.2 n/a 1991-1995 CWI
1.3 1.5.2 1.2 1995-1999 CNRI
1.6 1.5.2 2000 CNRI
2.0 1.6 2000 BeOpen.com
1.6.1 1.6 2001 CNRI
2.1 2.0+1.6.1 2001 PSF
2.0.1 2.0+1.6.1 2001 PSF
2.1.1 2.1+2.0.1 2001 PSF
2.1.2 2.1.1 2002 PSF
2.1.3 2.1.2 2002 PSF
2.2 2.1.1 2001 PSF
295
The Python/C API, 3.12.1
Guido
C.2 Python
Python PSF
Python 3.8.6 PSF BSD
Python
prepared by Licensee.
agrees to include in any such work a brief summary of the changes made␣
,→to Python
3.12.1.
USE OF PYTHON 3.12.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.12.1
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A␣
,→RESULT OF
296 Appendix C.
The Python/C API, 3.12.1
Agreement does not grant permission to use PSF trademarks or trade name␣
,→in a
third party.
BEOPEN PYTHON 1
2. Subject to the terms and conditions of this BeOpen Python License Agreement,
BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
to reproduce, analyze, test, perform and/or display publicly, prepare derivative
works, distribute, and otherwise use the Software alone or in any derivative
version, provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
ADVISED OF THE POSSIBILITY THEREOF.
( )
granted on that web page.
2. Subject to the terms and conditions of this License Agreement, CNRI hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version
prepared by Licensee. Alternately, in lieu of CNRI's License Agreement,
Licensee may substitute the following text (omitting the quotes): "Python 1.6.1
is made available subject to the terms and conditions in CNRI's License
Agreement. This Agreement together with Python 1.6.1 may be located on the
internet using the following unique, persistent identifier (known as a handle):
1895.22/1013. This Agreement may also be obtained from a proxy server on the
internet using the following URL: http://hdl.handle.net/1895.22/1013."
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI
MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE,
BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
298 Appendix C.
The Python/C API, 3.12.1
( )
sense to endorse or promote products or services of Licensee, or any third
party.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting documentation, and that
the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
publicity pertaining to distribution of the software without specific, written
prior permission.
C.2.5 ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3.12.1 DOCU-
MENTATION
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
C.3
Python
C.3. 299
The Python/C API, 3.12.1
C.3.2
300 Appendix C.
The Python/C API, 3.12.1
( )
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
C.3.3
test.support.asynchat test.support.asyncore :
C.3.4 Cookie
http.cookies :
C.3. 301
The Python/C API, 3.12.1
( )
pertaining to distribution of the software without specific, written
prior permission.
C.3.5
trace :
Permission to use, copy, modify, and distribute this Python software and
its associated documentation for any purpose without fee is hereby
granted, provided that the above copyright notice appears in all copies,
and that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of neither Automatrix,
Bioreason or Mojam Media be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
uu :
302 Appendix C.
The Python/C API, 3.12.1
( )
LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
C.3.7 XML
xmlrpc.client :
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.
C.3.8 test_epoll
test.test_epoll :
C.3. 303
The Python/C API, 3.12.1
( )
the following conditions:
select kqueue :
Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
C.3.10 SipHash24
<MIT License>
Copyright (c) 2013 Marek Majkowski <[email protected]>
The above copyright notice and this permission notice shall be included in
( )
304 Appendix C.
The Python/C API, 3.12.1
( )
all copies or substantial portions of the Software.
</MIT License>
Original location:
https://github.com/majek/csiphash/
/****************************************************************
*
* The author of this software is David M. Gay.
*
* Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*
***************************************************************/
C.3.12 OpenSSL
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Legal Entity" shall mean the union of the acting entity and all
( )
C.3. 305
The Python/C API, 3.12.1
( )
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
306 Appendix C.
The Python/C API, 3.12.1
( )
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
( )
C.3. 307
The Python/C API, 3.12.1
( )
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
C.3.13 expat
Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
and Clark Cooper
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
308 Appendix C.
The Python/C API, 3.12.1
( )
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
C.3.14 libffi
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
C.3.15 zlib
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
( )
C.3. 309
The Python/C API, 3.12.1
( )
C.3.16 cfuhash
tracemalloc cfuhash :
C.3.17 libmpdec
310 Appendix C.
The Python/C API, 3.12.1
( )
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
C.3. 311
The Python/C API, 3.12.1
C.3.19 audioop
312 Appendix C.
APPENDIX D
Python
© 2001-2023 Python
© 2000 BeOpen.com
© 1995-2000 Corporation for National Research Initiatives
© 1991-1995 Stichting Mathematisch Centrum
313
The Python/C API, 3.12.1
314 Appendix D.
_PyObject_NewVar (C function), 233
..., 281 _PyTuple_Resize (C function), 139
2to3, 281 _thread
>>>, 281 module, 188
__all__ ( ), 66 , 150
__dict__ ( ), 155
__doc__ ( ), 155 method -- , 291
__file__ ( ), 155
__future__, 285 __PYVENV_LAUNCHER__, 208, 214
__import__ PATH, 11
, 66 PYTHONCOERCECLOCALE, 219
__loader__ ( ), 155 PYTHONDEBUG, 178, 213
__main__ PYTHONDEVMODE, 209
module, 11, 181, 194, 195 PYTHONDONTWRITEBYTECODE, 178, 216
__name__ ( ), 155 PYTHONDUMPREFS, 210, 248
__package__ ( ), 155 PYTHONEXECUTABLE, 214
__PYVENV_LAUNCHER__, 208, 214 PYTHONFAULTHANDLER, 210
__slots__, 290 PYTHONHASHSEED, 179, 211
_frozen (C struct), 69 PYTHONHOME, 11, 179, 185, 211
_inittab (C struct), 69 PYTHONINSPECT, 179, 211
_inittab.name (C member), 69 PYTHONINTMAXSTRDIGITS, 211
_Py_c_diff (C function), 119 PYTHONIOENCODING, 182, 215
_Py_c_neg (C function), 119 PYTHONLEGACYWINDOWSFSENCODING, 179,
_Py_c_pow (C function), 119 205
_Py_c_prod (C function), 119 PYTHONLEGACYWINDOWSSTDIO, 180, 212
_Py_c_quot (C function), 119 PYTHONMALLOC, 224, 227, 229
_Py_c_sum (C function), 119 PYTHONMALLOC`
_Py_InitializeMain (C function), 221 ``PYTHONMALLOC=malloc`, 230
_Py_NoneStruct (C var), 233 PYTHONMALLOCSTATS, 212, 224
_PyBytes_Resize (C function), 122 PYTHONNODEBUGRANGES, 209
_PyCFunctionFast (C type), 236 PYTHONNOUSERSITE, 180, 216
_PyCFunctionFastWithKeywords (C type), 236 PYTHONOPTIMIZE, 180, 213
_PyCode_GetExtra, 153 PYTHONPATH, 11, 179, 212
_PyCode_SetExtra, 153 PYTHONPERFSUPPORT, 215
_PyEval_RequestCodeExtraIndex, 153 PYTHONPLATLIBDIR, 212
_PyFrameEvalFunction (C type), 191 PYTHONPROFILEIMPORTTIME, 211
_PyInterpreterFrame (C struct), 169 PYTHONPYCACHEPREFIX, 214
_PyInterpreterState_GetEvalFrameFunc PYTHONSAFEPATH, 208
(C function), 191 PYTHONTRACEMALLOC, 215
_PyInterpreterState_SetEvalFrameFunc PYTHONUNBUFFERED, 180, 209
(C function), 191 PYTHONUTF8, 205, 219
_PyObject_GetDictPtr (C function), 84 PYTHONVERBOSE, 181, 216
_PyObject_New (C function), 233 PYTHONWARNINGS, 216
315
The Python/C API, 3.12.1
A D
abort(), 66 decorator -- , 283
abs descrgetfunc (C type), 272
, 93 descriptor -- , 283
abstract base class -- , 281 descrsetfunc (C type), 272
allocfunc (C type), 272 destructor (C type), 272
annotation -- , 281 dictionary --
argument -- , 281 object -- , 142
argv ( sys ), 184 dictionary -- , 284
ascii dictionary comprehension -- ,
, 85 284
asynchronous context manager -- dictionary view -- , 284
, 282 divmod
asynchronous generator -- , , 92
282 docstring -- , 284
asynchronous generator iterator -- duck-typing -- , 284
, 282
asynchronous iterable -- E
, 282 EAFP, 284
asynchronous iterator -- , 282 EOFError ( ), 154
attribute -- , 282 exc_info() ( sys ), 10
awaitable -- , 282 executable ( sys ), 183
exit(), 66
B expression -- , 284
BDFL, 282 extension module -- , 284
binary file -- , 282
binaryfunc (C type), 273 F
borrowed reference -- , 282 f-string -- f- , 284
builtins file object -- , 284
module, 11, 181, 194, 195 file-like object -- , 284
bytearray filesystem encoding and error
object -- , 122 handler --
bytecode -- , 283 , 284
bytes-like object -- , 282 finder -- , 284
float
C , 94
C , 101, 283 floor division -- , 285
callable -- , 283 Fortran , 101, 283
callback -- , 283 free(), 223
calloc(), 223 freefunc (C type), 272
Capsule frozenset
316
The Python/C API, 3.12.1
object -- , 145 K
function -- key function -- , 287
object -- , 147 KeyboardInterrupt ( ), 54
function -- , 285 keyword argument -- , 287
function annotation -- , 285
L
G lambda, 287
garbage collection -- , 285 LBYL, 287
gcvisitobjects_t (C type), 278 len
generator -- , 285 , 86, 95, 96, 141, 143, 146
generator -- , 285 lenfunc (C type), 273
generator expression -- , list
285 object -- , 141
generator expression -- , list -- , 287
285 list comprehension -- , 287
generator iterator -- , 285 loader -- , 287
generic function -- , 285 locale encoding -- , 287
generic type -- , 285 LONG_MAX, 114
getattrfunc (C type), 272
getattrofunc (C type), 272 M
getbufferproc (C type), 273 magic method -- , 287
getiterfunc (C type), 272 main(), 182, 184
GIL, 285 malloc(), 223
global interpreter lock -- mapping --
, 186 object -- , 142
global interpreter lock -- mapping -- , 287
, 285 memoryview
object -- , 165
H meta path finder -- , 287
hash metaclass -- , 287
, 86, 251 METH_CLASS (C macro), 237
hash-based pyc -- pyc, 286 METH_COEXIST (C macro), 237
hashable -- , 286 METH_FASTCALL (C macro), 237
hashfunc (C type), 272 METH_KEYWORDS (C macro), 237
METH_METHOD (C macro), 237
I METH_NOARGS (C macro), 237
IDLE, 286 METH_O (C macro), 237
immutable -- , 286 METH_STATIC (C macro), 237
import path -- , 286 METH_VARARGS (C macro), 236
importer -- , 286 method --
importing -- , 286 object -- , 149
incr_item(), 10, 11 , 291
initproc (C type), 272 , 287
inquiry (C type), 277 method -- , 288
instancemethod method resolution order --
object -- , 149 , 288
int MethodType (types ), 147, 149
, 94 module
integer __main__, 11, 181, 194, 195
object -- , 113 _thread, 188
interactive -- , 286 builtins, 11, 181, 194, 195
interpreted -- , 286 object -- , 155
interpreter shutdown -- , 286 signal, 54
iterable -- , 286 sys, 11, 181, 194, 195
iterator -- , 286 path, 11, 181, 183
iternextfunc (C type), 273 module -- , 288
module spec -- , 288
modules ( sys ), 66, 181
317
The Python/C API, 3.12.1
318
The Python/C API, 3.12.1
319
The Python/C API, 3.12.1
320
The Python/C API, 3.12.1
321
The Python/C API, 3.12.1
322
The Python/C API, 3.12.1
323
The Python/C API, 3.12.1
324
The Python/C API, 3.12.1
325
The Python/C API, 3.12.1
326
The Python/C API, 3.12.1
327
The Python/C API, 3.12.1
328
The Python/C API, 3.12.1
329
The Python/C API, 3.12.1
330
The Python/C API, 3.12.1
331
The Python/C API, 3.12.1
332
The Python/C API, 3.12.1
333
The Python/C API, 3.12.1
334
The Python/C API, 3.12.1
335
The Python/C API, 3.12.1
T_USHORT, 241
ternaryfunc (C type), 273 object -- , 154
text encoding -- , 291
text file -- , 291 object -- , 117
traverseproc (C type), 277 , 66
triple-quoted string -- , WRITE_RESTRICTED, 239
291
type Z
object -- , 6, 107 Zen of Python -- Python , 292
, 86
type -- , 291
type alias -- , 291
type hint -- , 292
U
ULONG_MAX, 115
unaryfunc (C type), 273
universal newlines -- , 292
V
variable annotation -- , 292
object -- , 138
, 96, 142
__import__, 66
abs, 93
ascii, 85
divmod, 92
float, 94
hash, 86, 251
int, 94
len, 86, 95, 96, 141, 143, 146
pow, 92, 94
repr, 85, 250
type, 86
, 96, 142
, 85
, 237
, 67
, 237
, 69
__all__, 66
vectorcallfunc (C type), 88
version ( sys ), 184
virtual environment -- , 292
virtual machine -- , 292
visitproc (C type), 277
object -- , 120
, 85
W
path, module, 11, 181, 183
object -- , 113
336