0% found this document useful (0 votes)
2 views

c-api

The document is the Python/C API documentation version 3.12.1, authored by Guido van Rossum and the Python development team. It includes detailed sections on the C API, API specifications, and various functionalities related to Python. The document serves as a comprehensive guide for developers working with the Python/C interface.

Uploaded by

cyberamurie
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

c-api

The document is the Python/C API documentation version 3.12.1, authored by Guido van Rossum and the Python development team. It includes detailed sections on the C API, API specifications, and various functionalities related to Python. The document serves as a comprehensive guide for developers working with the Python/C interface.

Uploaded by

cyberamurie
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 344

The Python/C API

3.12.1

Guido van Rossum and the Python development team

19, 2023

Python Software Foundation


Email: [email protected]
Contents

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

13 API ABI 279

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

Python C C++ API


extending-index API

Contents 1
The Python/C API, 3.12.1

2 Contents
CHAPTER 1

Python API C C++ Python API


C++ Python/C API Python/C API
Python C
Python
embedding Python

Python Python

API Python Python


Python

1.1

CPython C PEP 7
Python
Python

1.2

Python/C API

#define PY_SSIZE_T_CLEAN
#include <Python.h>

<stdio.h> <string.h> <errno.h> <limits.h> <assert.h>


<stdlib.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

Python Unix prefix/include/pythonversion/


exec_prefix/include/pythonversion/ prefix exec_prefix Python
configure version '%d.%d' % sys.version_info[:2]
Windows prefix/include prefix

#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 :

static struct PyModuleDef spam_module = {


PyModuleDef_HEAD_INIT,
.m_name = "spam",
...
};

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

Python ( Py_DEBUG ) Py_ALWAYS_INLINE

static inline Py_ALWAYS_INLINE int random(void) { return 4; }

3.11 .
Py_CHARMASK(c)
[-128, 127] [0, 255] c unsigned
char
Py_DEPRECATED(version)

Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);

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)

Py_NO_INLINE static int random(void) { return 4; }

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

PEP 7 PyDoc_STRVAR Python

PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");

static PyMethodDef deque_methods[] = {


// ...
{"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
// ...
}

PyDoc_STR(str)

PEP 7 PyDoc_STR Python

static PyMethodDef pysqlite_row_methods[] = {


{"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
PyDoc_STR("Returns the keys of the row.")},
{NULL, NULL}
};

1.4

Python/C API PyObject*


Python Python Python
C
Python PyObject
PyObject* type
PyTypeObject
Python Python type reference count
types
a Python PyList_Check(a)

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()

PyObject_, PyNumber_, PySequence_ PyMapping_


strong reference ( )
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 *tuple, *list;

tuple = Py_BuildValue("(iis)", 1, 2, "three");


list = Py_BuildValue("[iis]", 1, 2, "three");

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

Python/C API C int, long, double


char*

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) */

item = PyObject_GetItem(dict, key);


if (item == NULL) {
/* Handle KeyError only: */
if (!PyErr_ExceptionMatches(PyExc_KeyError))
goto error;

/* Clear the error and use zero: */


PyErr_Clear();
( )

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;

incremented_item = PyNumber_Add(item, const_one);


if (incremented_item == NULL)
goto error;

if (PyObject_SetItem(dict, key, incremented_item) < 0)


goto error;
rv = 0; /* Success */
/* Continue with cleanup code */

error:
/* Cleanup code, shared by success and failure path */

/* Use Py_XDECREF() to ignore NULL references */


Py_XDECREF(item);
Py_XDECREF(const_one);
Py_XDECREF(incremented_item);

return rv; /* -1 for error, 0 for success */


}

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

Py_DEBUG Python Py_DEBUG Unix


--with-pydebug ./configure Python
_DEBUG Py_DEBUG Unix
Python Debug Build
Py_TRACE_REFS ( configure --with-trace-refs )
PyObject

Python Misc/SpecialBuilds.txt

12 Chapter 1.
CHAPTER 2

C API

Python C API PEP 387


new API API 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

PyUnstable API CPython


3.9 3.10 3.10.0
3.10.1

API CPython

13
The Python/C API, 3.12.1

2.2

API ABI API


Python

2.2.1 C API

Python 3.2 API Python C API API


Python API
Py_LIMITED_API
Python.h API API
Py_LIMITED_API Python PY_VERSION_HEX
Python 3
API
PY_VERSION_HEX 0x030A0000
Python 3.10 Python
Py_LIMITED_API 3 0x03020000 Python 3.2
API

2.2.2 ABI

Python ABI: Python 3.x


ABI API API

Windows ABI python3.dll python39.


dll
Python abi3 ( mymodule.abi3.so)
ABI ( ) 3.10+
API Python
ABI Python
C

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

Py_LIMITED_API API ABI


Py_LIMITED_API API
Py_LIMITED_API Python
NULL Python 3.9 NULL Python 3.8
NULL
Py_LIMITED_API API

Python

API API
Py_LIMITED_API

API Python 3.8 Py_LIMITED_API


Python 3.12 Python 3.12 ABI
API

2.3

ABI Python ABI


OS
Python ABI Python
python.org Windows macOS

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

"???" closeit PyRun_SimpleFileExFlags()

int PyRun_SimpleString(const char *command)


PyRun_SimpleStringFlags() PyCompilerFlags*
NULL
int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
flags __main__ Python __main__
0 -1 flags

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()

: Windows fp ( fopen(filename, "rb")) Python


LF

int PyRun_InteractiveOne(FILE *fp, const char *filename)


PyRun_InteractiveOneFlags() flags NULL
int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
flags sys.ps1
sys.ps2 filename filesystem encoding and error handler
0 -1
Python errcode.h errcode.h
Python.h
int PyRun_InteractiveLoop(FILE *fp, const char *filename)
PyRun_InteractiveLoopFlags() flags NULL
int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
EOF sys.ps1 sys.ps2
filename filesystem encoding and error handler EOF 0

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

PyObject *PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)


ABI. PyEval_EvalCodeEx()
NULL
PyObject *PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject *const *args, int
argcount, PyObject *const *kws, int kwcount, PyObject *const *defs, int
defcount, PyObject *kwdefs, PyObject *closure)
ABI.

PyObject *PyEval_EvalFrame(PyFrameObject *f)


ABI. PyEval_EvalFrameEx()

PyObject *PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)


ABI. Python f
throwflag
throw()
3.4 :
int PyEval_MergeCompilerFlags(PyCompilerFlags *cf)

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

PyObject *Py_NewRef(PyObject *o)


ABI 3.10 . strong reference: o Py_INCREF()
o
strong reference Py_DECREF()
o NULL o NULL Py_XNewRef()

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

void Py_IncRef(PyObject *o)


ABI. o strong reference Py_XINCREF()
Python
void Py_DecRef(PyObject *o)
ABI. o strong reference Py_XDECREF()
Python
Py_SETREF(dst, src)
dst strong reference dst src
Py_CLEAR() :

Py_DECREF(dst);
dst = src;

Py_SETREF(dst, src);

dst _ _ dst src dst


dst
3.6 .
3.12 :
Py_XSETREF(dst, src)
Py_XDECREF() Py_DECREF() Py_SETREF
3.6 .
3.12 :

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

3.4 : obj NULL


3.8 : sys.unraisablehook()
void PyErr_DisplayException(PyObject *exc)
ABI 3.12 . exc sys.stderr
3.12 .

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

PyObject *PyErr_SetFromErrno(PyObject *type)


NULL ABI. C C
errno errno
strerror() PyErr_SetObject(type, object) Unix
errno EINTR PyErr_CheckSignals()
NULL
return PyErr_SetFromErrno(type);
PyObject *PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)
NULL ABI. PyErr_SetFromErrno() filenameObject
NULL type OSError
filename
PyObject *PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject,
PyObject *filenameObject2)
NULL ABI 3.7 .
PyErr_SetFromErrnoWithFilenameObject() filename
filename
3.4 .
PyObject *PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
NULL ABI. PyErr_SetFromErrnoWithFilenameObject()
C filename filesystem encoding and error handler
PyObject *PyErr_SetFromWindowsErr(int ierr)
NULL ABI on Windows 3.7 . WindowsError
ierr 0 GetLastError()
Win32 FormatMessage() ierr GetLastError()
Windows ierr
FormatMessage() PyErr_SetObject(PyExc_WindowsError,
object) NULL
: Windows
PyObject *PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
NULL ABI on Windows 3.7 .
PyErr_SetFromWindowsErr()
: Windows
PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
NULL ABI on Windows 3.7 . PyErr_SetFromWindowsErr()
filename NULL (os.fsdecode())
OSError filename
: Windows
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject
*filename)
NULL ABI on Windows 3.7 .
PyErr_SetExcFromWindowsErr() filename NULL
OSError filename
: Windows
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject
*filename, PyObject *filename2)
NULL ABI on Windows 3.7 .
PyErr_SetExcFromWindowsErrWithFilenameObject() filename

: 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()

int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)


ABI. category NULL message
UTF-8 stack_level
stack_level 1 PyErr_WarnEx() 2

PyExc_Warning PyExc_Warning PyExc_Exception


PyExc_RuntimeWarning Python

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()

int PyErr_ExceptionMatches(PyObject *exc)


ABI. PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)

int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)


ABI. given exc exc
given exc

PyObject *PyErr_GetRaisedException(void)
ABI 3.12 .

5.4. 51
The Python/C API, 3.12.1

{
PyObject *exc = PyErr_GetRaisedException();

/* ... code that might produce other errors ... */

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);

/* ... code that might produce other errors ... */

PyErr_Restore(type, value, traceback);


}

void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)


ABI. 3.12 : PyErr_SetRaisedException()
type, value traceback
NULL NULL NULL

: PyErr_Fetch()

void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)


ABI. 3.12 : PyErr_GetRaisedException()

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

: SIGINT Python KeyboardInterrupt

void PyErr_SetInterrupt()
ABI. SIGINT
PyErr_SetInterruptEx(SIGINT)

: GIL C

int PyErr_SetInterruptEx(int signum)


ABI 3.10 . PyErr_CheckSignals()
Python
Python
Ctrl-C C
Python ( signal.SIG_DFL signal.SIG_IGN)

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

PyObject *PyErr_NewException(const char *name, PyObject *base, PyObject *dict)


ABI. name
module.classname C base dict NULL
Exception C PyExc_Exception
__module__ name
base
dict
PyObject *PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject
*dict)
ABI. PyErr_NewException()
doc
3.2 .

5.7

PyObject *PyException_GetTraceback(PyObject *ex)


ABI.
__traceback__ Python NULL
int PyException_SetTraceback(PyObject *ex, PyObject *tb)
ABI. tb Py_None
PyObject *PyException_GetContext(PyObject *ex)
ABI. ex
__context__ Python
NULL
void PyException_SetContext(PyObject *ex, PyObject *ctx)
ABI. ctx NULL ctx
ctx
PyObject *PyException_GetCause(PyObject *ex)
ABI. None raise
... from ... __cause__ Python
void PyException_SetCause(PyObject *ex, PyObject *cause)
ABI. cause NULL
cause None cause
__suppress_context__ True
PyObject *PyException_GetArgs(PyObject *ex)
ABI 3.12 . ex args
void PyException_SetArgs(PyObject *ex, PyObject *args)
ABI 3.12 . ex args args
PyObject *PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs)

API

except* orig excs


orig except*

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

where UTF-8 " in instance check"


RecursionError
3.9 : API
void Py_LeaveRecursiveCall(void)
ABI 3.9 . Py_EnterRecursiveCall()
Py_EnterRecursiveCall()
3.9 : API
tp_repr tp_repr
C reprlib.
recursive_repr()
int Py_ReprEnter(PyObject *object)
ABI. tp_repr
tp_repr
dict {...} list [...]
tp_repr NULL
tp_repr
void Py_ReprLeave(PyObject *object)
ABI. Py_ReprEnter() Py_ReprEnter()

5.10

Python PyExc_ Python


PyObject* :

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

3.3 : PyExc_BlockingIOError, PyExc_BrokenPipeError,


PyExc_ChildProcessError, PyExc_ConnectionError, PyExc_ConnectionAbortedError,
PyExc_ConnectionRefusedError, PyExc_ConnectionResetError,
PyExc_FileExistsError, PyExc_FileNotFoundError, PyExc_InterruptedError,
PyExc_IsADirectoryError, PyExc_NotADirectoryError, PyExc_PermissionError,
PyExc_ProcessLookupError and PyExc_TimeoutError PEP 3151.
3.5 : PyExc_StopAsyncIteration PyExc_RecursionError.
1

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

Python PyExc_ Python


PyObject* :

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

PyObject *PyOS_FSPath(PyObject *path)


ABI 3.6 . path
str bytes strong reference os.PathLike
str bytes __fspath__() TypeError
NULL
3.6 .
int Py_FdIsInteractive(FILE *fp, const char *filename)
filename Return true (nonzero) if the standard I/O fp
isatty(fileno(fp)) PyConfig.
interactive filename NULL '<stdin>'
'???'
Python
void PyOS_BeforeFork()
ABI on platforms with fork() 3.7 .
fork() fork()

: C fork() ”main” ( ”main” )


PyOS_BeforeFork()

3.7 .
void PyOS_AfterFork_Parent()
ABI on platforms with fork() 3.7 .
fork()
fork()

61
The Python/C API, 3.12.1

: C fork() ”main” ( ”main” )


PyOS_AfterFork_Parent()

3.7 .
void PyOS_AfterFork_Child()
ABI on platforms with fork() 3.7 .
fork()
Python fork()

: C fork() ”main” ( ”main” )


PyOS_AfterFork_Child()

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)

PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)


ABI. i h sigaction()
signal() PyOS_sighandler_t void
(*)(int)
wchar_t *Py_DecodeLocale(const char *arg, size_t *size)
ABI 3.7 .

: PyConfig API Python


PyConfig_SetBytesString()
This function must not be called before Python
LC_CTYPE Py_PreInitialize()

filesystem encoding and error handler surrogateescape


U+DC80..U+DCFF
surrogateescape

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

filesystem encoding and error handler PyConfig_Read() : PyConfig


filesystem_encoding filesystem_errors
Py_DecodeLocale()

: This function must not be called before Python


LC_CTYPE Py_PreInitialize()

:
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

PyObject *PySys_GetObject(const char *name)


ABI. sys name
NULL
int PySys_SetObject(const char *name, PyObject *v)
ABI. sys name v v NULL name sys
0 -1
void PySys_ResetWarnOptions()
ABI. sys.warnoptions Py_Initialize()

void PySys_AddWarnOption(const wchar_t *s)


ABI. API PyConfig.warnoptions
Python
s sys.warnoptions Py_Initialize()

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

format 1000 -- 1000


”%s” ”%.<N>s”
<N> <N> 1000
”%f”
sys.stdout (C ) stdout
void PySys_WriteStderr(const char *format, ...)
ABI. PySys_WriteStdout() sys.stderr stderr

64 Chapter 6.
The Python/C API, 3.12.1

void PySys_FormatStdout(const char *format, ...)


ABI. PySys_WriteStdout() PyUnicode_FromFormatV()

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

int (*)(const char *event, PyObject *args, void


*userData) args PyTupleObject
Python GIL
PEP 578

6.2. 65
The Python/C API, 3.12.1

sys.addaudithook
Exception

3.8 .

6.3

void Py_FatalError(const char *message)


ABI.
Python
Unix C abort() core
The Py_FatalError() function is replaced with a macro which logs automatically the name of the current
function, unless the Py_LIMITED_API macro is defined.
3.9 :
void Py_Exit(int status)
ABI. Py_FinalizeEx() C
exit(status) Py_FinalizeEx() 120
3.6 :
int Py_AtExit(void (*func)())
ABI. Py_FinalizeEx()
32 Py_AtExit() 0
-1
Python Python API func

6.4

PyObject *PyImport_ImportModule(const char *name)


ABI. PyImport_ImportModuleEx()
globals locals NULL level 0 name
fromlist ['*']
name
__all__
NULL sys.modules

PyObject *PyImport_ImportModuleNoBlock(const char *name)


ABI. PyImport_ImportModule()
3.3 : Python 3.3

PyObject *PyImport_ImportModuleEx(const char *name, PyObject *globals, PyObject *locals, PyObject


*fromlist)
Python __import__()

NULL
__import__()
fromlist
PyImport_ImportModule()

66 Chapter 6.
The Python/C API, 3.12.1

PyObject *PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals,


PyObject *fromlist, int level)
ABI 3.7 .
Python __import__() __import__()
NULL
__import__()
fromlist
3.3 .
PyObject *PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
PyObject *fromlist, int level)
ABI. PyImport_ImportModuleLevelObject()
UTF-8 Unicode
3.3 : level
PyObject *PyImport_Import(PyObject *name)
ABI.
level 0 __builtins__ __import__()

PyObject *PyImport_ReloadModule(PyObject *m)


ABI.
NULL
PyObject *PyImport_AddModuleObject(PyObject *name)
ABI 3.7 . name
package.module modules
modules NULL

:
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

__spec__ __loader__ spec


__loader__ SourceFileLoader

__file__ co_filename __cached__


PyImport_ReloadModule()

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)

PyObject *PyImport_GetModule(PyObject *name)


ABI 3.8 .
NULL NULL
3.7 .
PyObject *PyImport_GetImporter(PyObject *path)
ABI. sys.path/pkg.__path__ path
sys.path_importer_cache
sys.path_hooks
None path based finder sys.
path_importer_cache
int PyImport_ImportFrozenModuleObject(PyObject *name)
ABI 3.7 . name 1
0 -1

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;
};

3.11 : is_package size

const struct _frozen *PyImport_FrozenModules


_frozen NULL

int PyImport_AppendInittab(const char *name, PyObject *(*initfunc)(void))


ABI. PyImport_ExtendInittab()
-1 name initfunc
Py_Initialize()
struct _inittab
Python
PyImport_ExtendInittab()
:
const char *name
ASCII
int PyImport_ExtendInittab(struct _inittab *newtab)
newtab NULL name
0
-1 Py_Initialize()
Python PyImport_AppendInittab()
PyImport_ExtendInittab() Python

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

void PyMarshal_WriteLongToFile(long value, FILE *file, int version)


long value marshal file value 32
long version
PyErr_Occurred()
void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version)
Python value marshal file version
PyErr_Occurred()
PyObject *PyMarshal_WriteObjectToString(PyObject *value, int version)
value marshal version

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()

(EOFError, ValueError TypeError) NULL


PyObject *PyMarshal_ReadObjectFromString(const char *data, Py_ssize_t len)
data len Python

(EOFError, ValueError TypeError) NULL

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

s (str) [const char *] Unicode C


C Python
ValueError Unicode
'utf-8' C UnicodeError

: bytes-like objects C
O& PyUnicode_FSConverter()

3.5 : Python null TypeError


s* (str or bytes-like object) [Py_buffer] Unicode
Py_buffer C NUL Unicode
'utf-8' C
s# (str, read-only bytes-like object) [const char *, Py_ssize_t] s*
C C
Unicode 'utf-8' C
z (str or None) [const char *] s Python None C
NULL
z* (str, bytes-like object or None) [Py_buffer] s* Python None
Py_buffer buf NULL

6.6. 71
The Python/C API, 3.12.1

z# (str, read-only bytes-like object None) [const char *, Py_ssize_t] s# Python


None C NULL
y (read-only bytes-like object) [const char *]
C Unicode
ValueError exception is raised.
3.5 : null TypeError
y* (bytes-like object) [Py_buffer] s* Unicode

y# (read-only bytes-like object) [const char *, Py_ssize_t] s# Unicode

S (bytes) [PyBytesObject *] Python bytes


bytes TypeError C PyObject*
Y (bytearray) [PyByteArrayObject *] Python bytearray
bytearray TypeError C PyObject*
U (str) [PyObject *] Python Unicode Unicode
TypeError C PyObject*
w* ( bytes-like object) [Py_buffer]
Py_buffer null
PyBuffer_Release()
es (str) [const char *encoding, char **buffer] s Unicode
NUL
const char* NUL
NULL 'utf-8' Python
char**

PyArg_ParseTuple()
*buffer PyMem_Free()

et (str, bytes or bytearray) [const char *encoding, char **buffer] es

es# (str) [const char *encoding, char **buffer, Py_ssize_t *buffer_length] s#


Unicode es NUL
const char* NUL
NULL 'utf-8' Python
char**

*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#

3.12 : u, u#, Z Z# Py_UNICODE*

72 Chapter 6.
The Python/C API, 3.12.1

b (int) [unsigned char] Python C unsigned char


B (int) [unsigned char] Python C unsigned
char
h (int) [short int] Python C short int
H (int) [unsigned short int] Python C unsigned short int
i (int) [int] Python C int
I (int) [unsigned int] Python C unsigned int
l (int) [long int] Python C long int
k (int) [unsigned long] Python C unsigned long
L (int) [long long] Python C long long
K (int) [unsigned long long] Python C:C:expr:’unsigned long-long’
n (int) [Py_ssize_t] Python C Py_ssize_t Python
c (bytes bytearray 1) [char] Python 1 bytes
bytearray C char
3.3 : bytearray
C (str 1) [int] Python 1 str C int
f (float) [float] Python C float
d (float) [double] Python C double
D (complex) [Py_complex] Python C Py_complex Python

O (object) [PyObject *] Python C C


strong reference
NULL
O! (object) [typeobject, PyObject *] Python C O
C Python C ( PyObject*)
Python TypeError
O& (object) [converter, anything] converter Python C
C void*
status = converter(object, address);

object Python address PyArg_Parse* void*


status 1 0 converter
address
converter Py_CLEANUP_SUPPORTED
object NULL ;
NULL ; NULL NULL NULL address

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

(items) (tuple) [matching-items] Python items C


items
”long” ( LONG_MAX ) ---
( C
--- )

| Python C
PyArg_ParseTuple() C ( )
$ PyArg_ParseTupleAndKeywords() only Python
| $

3.3 .
: (PyArg_ParseTuple()
)
; : ;

Python

arg PyArg_Parse*
PyArg_Parse*

API

int PyArg_ParseTuple(PyObject *args, const char *format, ...)


ABI.
true false
int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)
ABI. PyArg_ParseTuple() va_list

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_Parse(PyObject *args, const char *format, ...)


ABI. METH_OLDARGS
Python 3

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;

if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {


result = PyWeakref_NewRef(object, callback);
}
return result;
}

PyArg_UnpackTuple() PyArg_ParseTuple():
PyArg_ParseTuple(args, "O|O:ref", &object, &callback)

6.6.2

PyObject *Py_BuildValue(const char *format, ...)


ABI. PyArg_Parse*
NULL NULL

Py_BuildValue()
None
0 1

s s#
Py_BuildValue()
malloc() Py_BuildValue()
Py_BuildValue() free()
() Python
[] C ( )
( s#)

s (str None) [const char *] 'utf-8' C Python str


C NULL None
s# (str None) [const char *, Py_ssize_t] 'utf-8' C
Python str C NULL None

6.6. 75
The Python/C API, 3.12.1

y (bytes) [const char *] C Python bytes C NULL


None
y# (bytes) [const char *, Py_ssize_t] C Python
C NULL None
z (str or None) [const char *] s
z# (str None) [const char *, Py_ssize_t] s#
u (str) [const wchar_t *] wchar_t Unicode UTF-16 UCS-4
Python Unicode Unicode NULL None
u# (str) [const wchar_t *, Py_ssize_t] Unicode UTF-16 UCS-4
Python Unicode Unicode NULL None
U (str None) [const char *] s
U# (str None) [const char *, Py_ssize_t] s#
i (int) [int] C int Python
b (int) [char] C char Python
h (int) [short int] C short int Python
l (int) [long int] C long int Python
B (int) [unsigned char] C unsigned char Python
H (int) [unsigned short int] C unsigned short int Python
I (int) [unsigned int] C unsigned int Python
k (int) [unsigned long] C unsigned long Python
L (int) [long long] C long long Python
K (int) [unsigned long long] C unsigned long long Python
n (int) [Py_ssize_t] C Py_ssize_t Python
c (bytes 1 ) [char] C int 1 Python bytes
C (str 1) [int] C int 1 Python str
d (float) [double] C double Python
f (float) [float] C float Python
D (complex) [Py_complex *] C Py_complex Python
O (object) [PyObject *] Python strong reference (
) NULL
Py_BuildValue() NULL
SystemError
S (object) [PyObject *] O
N (object) [PyObject *] O strong reference

O& (object) [converter, anything] converter anything Python


anything ( void*) ” ” Python
NULL
(items) (tuple) [matching-items] C Python
[items] (list) [ ] C Python
{items} (dict) [ ] C Python C

SystemError NULL

76 Chapter 6.
The Python/C API, 3.12.1

PyObject *Py_VaBuildValue(const char *format, va_list vargs)


ABI. Py_BuildValue() va_list

6.7

int PyOS_snprintf(char *str, size_t size, const char *format, ...)


ABI. format size str Unix
snprintf(3)
int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
ABI. format va size str Unix
vsnprintf(3)
PyOS_snprintf() PyOS_vsnprintf() C snprintf() vsnprintf()
C
str[size-1] '\0' size ( '\0')
str str != NULL, size > 0, format != NULL size < INT_MAX
C99 n = snprintf(NULL, 0, ...)
rv
• 0 <= rv < size rv str ( str[rv]
'\0' )
• rv >= size rv + 1
str[size-1] '\0'
• rv < 0 ” ” str[size-1] '\0' str

double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception)


ABI. s double Python
Python float() s

endptr NULL ValueError -1.0

endptr NULL *endptr


*endptr
ValueError -1.0
s "1e500"
overflow_exception NULL Py_HUGE_VAL
overflow_exception Python
-1.0 *endptr
Python
-1.0
3.1 .
char *PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype)
ABI. double val format_code, precision flags
, 'e', 'E', 'f', 'F', 'g', 'G' 'r' 'r' ,
0 'r' repr()

6.7. 77
The Python/C API, 3.12.1

flags Py_DTSF_SIGN, Py_DTSF_ADD_DOT_0 Py_DTSF_ALT


• Py_DTSF_SIGN val
• Py_DTSF_ADD_DOT_0
• Py_DTSF_ALT ” ” PyOS_snprintf() '#'

ptype NULL Py_DTST_FINITE, Py_DTST_INFINITE


Py_DTST_NAN val
buffer NULL
PyMem_Free()
3.1 .
int PyOS_stricmp(const char *s1, const char *s2)
strcmp()
int PyOS_strnicmp(const char *s1, const char *s2, Py_ssize_t size)
strncmp()

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

int PyCodec_Register(PyObject *search_function)


ABI.
encodings

78 Chapter 6.
The Python/C API, 3.12.1

int PyCodec_Unregister(PyObject *search_function)


ABI 3.10 .
0 -1
3.10 .
int PyCodec_KnownEncoding(const char *encoding)
ABI. encoding 1 0
PyObject *PyCodec_Encode(PyObject *object, const char *encoding, const char *errors)
ABI. API
object errors encoding errors NULL
LookupError
PyObject *PyCodec_Decode(PyObject *object, const char *encoding, const char *errors)
ABI. API
object errors encoding errors NULL
LookupError

6.9.1 Codec API

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

6.9.2 Unicode API

int PyCodec_RegisterError(const char *name, PyObject *error)


ABI. name error
/ name encode/decode error

UnicodeEncodeError, UnicodeDecodeError
UnicodeTranslateError
Unicode

/
0 -1

6.9. 79
The Python/C API, 3.12.1

PyObject *PyCodec_LookupError(const char *name)


ABI. name
NULL ”strict”
PyObject *PyCodec_StrictErrors(PyObject *exc)
NULL ABI. exc
PyObject *PyCodec_IgnoreErrors(PyObject *exc)
ABI. unicode
PyObject *PyCodec_ReplaceErrors(PyObject *exc)
ABI. ? U+FFFD unicode
PyObject *PyCodec_XMLCharRefReplaceErrors(PyObject *exc)
ABI. XML unicode
PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc)
ABI. (\x, \u \U) unicode
PyObject *PyCodec_NameReplaceErrors(PyObject *exc)
ABI 3.7 . \N{...} unicode
3.5 .

6.10 Perf Maps

Linux perf map Python


perf /tmp
Linux Perf
Python API
API GIL
int PyUnstable_PerfMapState_Init(void)

API

/tmp/perf-$pid.map
PyUnstable_WritePerfMapEntry()
PyUnstable_WritePerfMapEntry()

0 / perf map -1 -2 errno

int PyUnstable_WritePerfMapEntry(const void *code_addr, unsigned int code_size, const char


*entry_name)

API

/tmp/perf-$pid.map
:
# address size name
7f3529fcf759 b py::bar:/run/t.py

PyUnstable_PerfMapState_Init() perf map


0 PyUnstable_PerfMapState_Init()

80 Chapter 6.
The Python/C API, 3.12.1

void PyUnstable_PerfMapState_Fini(void)

API

PyUnstable_PerfMapState_Init() perf map

6.10. Perf Maps 81


The Python/C API, 3.12.1

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()

int PyObject_HasAttrString(PyObject *o, const char *attr_name)


ABI. PyObject_HasAttr() attr_name const char* UTF-8
PyObject*

: __getattr__() __getattribute__() str


PyObject_GetAttrString()

83
The Python/C API, 3.12.1

PyObject *PyObject_GetAttr(PyObject *o, PyObject *attr_name)


ABI. o attr_name
NULL Python o.attr_name
PyObject *PyObject_GetAttrString(PyObject *o, const char *attr_name)
ABI. PyObject_GetAttr() attr_name const
char* UTF-8 PyObject*
PyObject *PyObject_GenericGetAttr(PyObject *o, PyObject *name)
ABI. tp_getattro
MRO __dict__
descriptors
AttributeError
int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)
ABI. o attr_name v -1
0 Python o.attr_name = v
v NULL PyObject_DelAttr()

int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)


ABI. PyObject_SetAttr() attr_name const char* UTF-8
PyObject*
v NULL PyObject_DelAttrString()
int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)
ABI. tp_setattro
MRO
__dict__ 0
AttributeError -1
int PyObject_DelAttr(PyObject *o, PyObject *attr_name)
o attr_name -1 Python del o.attr_name
int PyObject_DelAttrString(PyObject *o, const char *attr_name)
PyObject_DelAttr() attr_name const char* UTF-8
PyObject*
PyObject *PyObject_GenericGetDict(PyObject *o, void *context)
ABI 3.10 . __dict__

o __dict__ NULL context


PyObject_GetAttr()

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

PyObject *PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)


ABI. opid o1 o2 Py_LT,
Py_LE, Py_EQ, Py_NE, Py_GT Py_GE <, <=, ==, !=, > >=
Python o1 op o2 op opid
NULL
int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid)
ABI. opid o1 o2 Py_LT, Py_LE, Py_EQ,
Py_NE, Py_GT Py_GE <, <=, ==, !=, > >= -1
0 1 Python o1 op o2 op opid

: o1 o2 PyObject_RichCompareBool() Py_EQ 1
Py_NE 0

PyObject *PyObject_Format(PyObject *obj, PyObject *format_spec)


ABI. obj format_spec Python format(obj, format_spec)
format_spec NULL format(obj)
NULL
PyObject *PyObject_Repr(PyObject *o)
ABI. o
NULL Python repr(o) repr()
3.4 :
PyObject *PyObject_ASCII(PyObject *o)
ABI. PyObject_Repr() o
PyObject_Repr() \x \u \U ASCII
Python 2 PyObject_Repr() ascii()
PyObject *PyObject_Str(PyObject *o)
ABI. o
NULL Python str(o) str() print()
3.4 :
PyObject *PyObject_Bytes(PyObject *o)
ABI. o NULL
o Python bytes(o) bytes(o) o
0 TypeError
int PyObject_IsSubclass(PyObject *derived, PyObject *cls)
ABI. derived cls 1 0
-1
cls cls 1 1 0
PEP 3119 cls __subclasscheck__()
derived cls.__mro__ cls

type __bases__

int PyObject_IsInstance(PyObject *inst, PyObject *cls)


ABI. inst cls 1 0
-1
cls cls 1 1 0
PEP 3119 cls __subclasscheck__()
derived cls cls

7.1. 85
The Python/C API, 3.12.1

inst __class__
cls __bases__

Py_hash_t PyObject_Hash(PyObject *o)


ABI. o -1 Python hash(o)
3.2 : Py_hash_t Py_ssize_t
Py_hash_t PyObject_HashNotImplemented(PyObject *o)
ABI. TypeError type(o) hashable -1
tp_hash
int PyObject_IsTrue(PyObject *o)
ABI. o true 1 0 Python not not
o -1
int PyObject_Not(PyObject *o)
ABI. o true 1 0 Python not not
o -1
PyObject *PyObject_Type(PyObject *o)
ABI. o NULL o
SystemError NULL Python type(o)
strong reference Py_TYPE()
PyTypeObject* strong reference
int PyObject_TypeCheck(PyObject *o, PyTypeObject *type)
o type 0 NULL
Py_ssize_t PyObject_Size(PyObject *o)
Py_ssize_t PyObject_Length(PyObject *o)
ABI. o o
-1 Python len(o)
Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
o __length_hint__()
-1 Python operator.length_hint(o,
defaultvalue)
3.4 .
PyObject *PyObject_GetItem(PyObject *o, PyObject *key)
ABI. key o NULL
Python o[key]
int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v)
ABI. key v -1 0 Python
o[key] = v v
int PyObject_DelItem(PyObject *o, PyObject *key)
ABI. o key -1 Python del
o[key]
PyObject *PyObject_Dir(PyObject *o)
ABI. Python dir(o)
NULL NULL Python dir()
locals NULL PyErr_Occurred()
false

86 Chapter 7.
The Python/C API, 3.12.1

PyObject *PyObject_GetIter(PyObject *o)


ABI. Python iter(o)
TypeError
NULL
PyObject *PyObject_GetAIter(PyObject *o)
ABI 3.10 . Python aiter(o)
AsyncIterable AsyncIterator
AsyncIterator TypeError
NULL
3.10 .
void *PyObject_GetTypeData(PyObject *o, PyTypeObject *cls)
ABI 3.12 . cls
o cls cls PyType_Spec.basicsize Python

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 :

PyObject *tp_call(PyObject *callable, PyObject *args, PyObject *kwargs);

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

3.12 : Py_TPFLAGS_HAVE_VECTORCALL __call__()


tp_call vectorcall
Python vectorcall
vectorcall *tp_call* vectorcall
args kwargs dict vectorcall
Py_TPFLAGS_HAVE_VECTORCALL tp_vectorcall_offset
vectorcallfunc vectorcall :
typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
ABI 3.12 .
• callable
• args C
NULL
• nargsf PY_VECTORCALL_ARGUMENTS_OFFSET nargsf
PyVectorcall_NARGS()
• kwnames kwargs
(str ) kwnames
NULL
PY_VECTORCALL_ARGUMENTS_OFFSET
ABI 3.12 . vectorcall nargsf
args[-1] args 1 0
args[-1]
PyObject_VectorcallMethod() args[0]

PY_VECTORCALL_ARGUMENTS_OFFSET
self
3.8 .
vectorcall call API
PyObject_Vectorcall()

: CPython 3.8 vectorcall API :


_PyObject_Vectorcall, _Py_TPFLAGS_HAVE_VECTORCALL, _PyObject_VectorcallMethod,
_PyVectorcall_Function, _PyObject_CallOneArg, _PyObject_CallMethodNoArgs,
_PyObject_CallMethodOneArg PyObject_VectorcallDict
_PyObject_FastCallDict

88 Chapter 7.
The Python/C API, 3.12.1

tp_call : CPython tp_call


Py_EnterRecursiveCall() Py_LeaveRecursiveCall()
vectorcall Py_EnterRecursiveCall
Py_LeaveRecursiveCall

Vectorcall API

Py_ssize_t PyVectorcall_NARGS(size_t nargsf)


ABI 3.12 . vectorcall nargsf :

(Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET)

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

Callable args kwargs


PyObject_Call() PyObject * dict/NULL
PyObject_CallNoArgs() PyObject * --- ---
PyObject_CallOneArg() PyObject * 1 ---
PyObject_CallObject() PyObject * /NULL ---
PyObject_CallFunction() PyObject * format ---
PyObject_CallMethod() + char* format ---
PyObject_CallFunctionObjArgs() PyObject * ---
PyObject_CallMethodObjArgs() + ---
PyObject_CallMethodNoArgs() + --- ---
PyObject_CallMethodOneArg() + 1 ---
PyObject_Vectorcall() PyObject * vectorcall vectorcall
PyObject_VectorcallDict() PyObject * vectorcall dict/NULL
PyObject_VectorcallMethod() + vectorcall vectorcall

7.2. 89
The Python/C API, 3.12.1

PyObject *PyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs)


ABI. Python callable args
kwargs
args NULL kwargs
NULL
NULL
Python callable(*args, **kwargs)
PyObject *PyObject_CallNoArgs(PyObject *callable)
ABI 3.10 . Python callable
Python
NULL
3.9 .
PyObject *PyObject_CallOneArg(PyObject *callable, PyObject *arg)
Python callable 1 arg
NULL
3.9 .
PyObject *PyObject_CallObject(PyObject *callable, PyObject *args)
ABI. Python callable args
args NULL
NULL
Python callable(*args)
PyObject *PyObject_CallFunction(PyObject *callable, const char *format, ...)
ABI. Python callable C
C Py_BuildValue() format NULL

NULL
Python callable(*args)
PyObject* PyObject_CallFunctionObjArgs()

3.4 : format char *


PyObject *PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...)
ABI. obj name C
C Py_BuildValue()
NULL
NULL
Python obj.name(arg1, arg2, ...)
PyObject* PyObject_CallMethodObjArgs()

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

PyObject *PyObject_CallMethodObjArgs(PyObject *obj, PyObject *name, ...)


ABI. Python obj name
Python PyObject* NULL

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

int PyCallable_Check(PyObject *o)


ABI. o 1 0

7.3

int PyNumber_Check(PyObject *o)


ABI. o 1
3.8 : o 1
PyObject *PyNumber_Add(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL Python
o1 + o2
PyObject *PyNumber_Subtract(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL Python
o1 - o2
PyObject *PyNumber_Multiply(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL Python
o1 * o2
PyObject *PyNumber_MatrixMultiply(PyObject *o1, PyObject *o2)
ABI 3.7 . o1 o2
NULL Python o1 @ o2
3.5 .
PyObject *PyNumber_FloorDivide(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL
Python o1 // o2
PyObject *PyNumber_TrueDivide(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL
” ”
Python o1 / o2
PyObject *PyNumber_Remainder(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL
Python o1 % o2
PyObject *PyNumber_Divmod(PyObject *o1, PyObject *o2)
ABI. divmod() NULL Python
divmod(o1, o2)
PyObject *PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3)
ABI. pow() NULL Python
pow(o1, o2, o3) o3 o3 Py_None
NULL
PyObject *PyNumber_Negative(PyObject *o)
ABI. o NULL Python
-o
PyObject *PyNumber_Positive(PyObject *o)
ABI. o NULL Python +o

92 Chapter 7.
The Python/C API, 3.12.1

PyObject *PyNumber_Absolute(PyObject *o)


ABI. o NULL Python
abs(o)
PyObject *PyNumber_Invert(PyObject *o)
ABI. o NULL
Python ~o
PyObject *PyNumber_Lshift(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL
Python o1 << o2
PyObject *PyNumber_Rshift(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL
Python o1 >> o2
PyObject *PyNumber_And(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL
Python o1 & o2
PyObject *PyNumber_Xor(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL
Python o1 ^ o2
PyObject *PyNumber_Or(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL
Python o1 | o2
PyObject *PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL o1
Python o1 += o2
PyObject *PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL o1
Python o1 -= o2
PyObject *PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2)
ABI. o1 o2* “NULL“ *o1
Python o1 *= o2
PyObject *PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2)
ABI 3.7 . o1 o2
NULL o1 Python o1 @= o2
3.5 .
PyObject *PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL
o1 Python o1 //= o2
PyObject *PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL
” ”
o1
Python o1 /= o2
PyObject *PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL o1
Python o1 %= o2

7.3. 93
The Python/C API, 3.12.1

PyObject *PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3)


ABI. pow() NULL o1
o3 Py_None Python o1 **= o2
pow(o1, o2, o3) o3 Py_None NULL

PyObject *PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2)


ABI. o1 o2 NULL o1
Python o1 <<= o2
PyObject *PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL o1
Python o1 >>= o2
PyObject *PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2)
ABI. o1 o2 ” ” NULL
o1 Python o1 &= o2
PyObject *PyNumber_InPlaceXor(PyObject *o1, PyObject *o2)
ABI. o1 o2 ” NULL
o1 Python o1 ^= o2
PyObject *PyNumber_InPlaceOr(PyObject *o1, PyObject *o2)
ABI. o1 o2 ” ” NULL
o1 Python o1 |= o2
PyObject *PyNumber_Long(PyObject *o)
ABI. o NULL
Python int(o)
PyObject *PyNumber_Float(PyObject *o)
ABI. o NULL
Python float(o)
PyObject *PyNumber_Index(PyObject *o)
ABI. o Python int NULL
TypeError
3.10 : int int
PyObject *PyNumber_ToBase(PyObject *n, int base)
ABI. n base base
2 8 10 16 2 8 16 '0b',
'0o', or '0x' n Python int PyNumber_Index()

Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc)


ABI. o o Py_ssize_t
-1
o Python int Py_ssize_t OverflowError
exc ( IndexError OverflowError) exc NULL
PY_SSIZE_T_MIN
PY_SSIZE_T_MAX
int PyIndex_Check(PyObject *o)
ABI 3.8 . 1 o nb_index
tp_as_number 0

94 Chapter 7.
The Python/C API, 3.12.1

7.4

int PySequence_Check(PyObject *o)


ABI. 1 0 __getitem__()
Python 1 dict

Py_ssize_t PySequence_Size(PyObject *o)


Py_ssize_t PySequence_Length(PyObject *o)
ABI. *o* , -1 . Python len(o) .
PyObject *PySequence_Concat(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL Python
o1 + o2
PyObject *PySequence_Repeat(PyObject *o, Py_ssize_t count)
ABI. o count NULL
Python o * count
PyObject *PySequence_InPlaceConcat(PyObject *o1, PyObject *o2)
ABI. o1 o2 NULL o1
Python o1 += o2
PyObject *PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
ABI. Return the result of repeating sequence object o
count NULL o Python
o *= count
PyObject *PySequence_GetItem(PyObject *o, Py_ssize_t i)
ABI. o i NULL Python
o[i]
PyObject *PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)
ABI. o i1 i2 NULL
Python o[i1:i2]
int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v)
ABI. v o i -1 0
Python o[i] = v v
v NULL PySequence_DelItem()
int PySequence_DelItem(PyObject *o, Py_ssize_t i)
ABI. o i -1 Python del o[i]
int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v)
ABI. v o i1 i2 Python o[i1:i2]
= v
int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)
ABI. o i1 i2 -1 Python del
o[i1:i2]
Py_ssize_t PySequence_Count(PyObject *o, PyObject *value)
ABI. value o o[key] == value
-1 Python o.count(value)
int PySequence_Contains(PyObject *o, PyObject *value)
ABI. o value o value 1 0
-1 Python value in o

7.4. 95
The Python/C API, 3.12.1

Py_ssize_t PySequence_Index(PyObject *o, PyObject *value)


ABI. *i*, o[i] == value . , -1 . Python
o.index(value) .
PyObject *PySequence_List(PyObject *o)
ABI. o
NULL Python list(o)
PyObject *PySequence_Tuple(PyObject *o)
ABI. o
NULL o
Python tuple(o)
PyObject *PySequence_Fast(PyObject *o, const char *m)
ABI. o PySequence_Fast*
TypeError m
NULL
PySequence_Fast* o PyTupleObject
PyListObject o
CPython o
Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o)
o PySequence_Fast() o NULL o o
PySequence_Size() PySequence_Fast_GET_SIZE()
o
PyObject *PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i)
o PySequence_Fast() o NULL id
o i
PyObject **PySequence_Fast_ITEMS(PyObject *o)
PyObject o PySequence_Fast() o NULL
, , items . ,
.
PyObject *PySequence_ITEM(PyObject *o, Py_ssize_t i)
o i NULL PySequence_GetItem()
o PySequence_Check()

7.5

PyObject_GetItem() PyObject_SetItem() PyObject_DelItem()


int PyMapping_Check(PyObject *o)
ABI. 1 0
__getitem__() Python 1

Py_ssize_t PyMapping_Size(PyObject *o)


Py_ssize_t PyMapping_Length(PyObject *o)
ABI. o -1 Python len(o)
PyObject *PyMapping_GetItemString(PyObject *o, const char *key)
ABI. PyObject_GetItem() key const
char* UTF-8 PyObject*

96 Chapter 7.
The Python/C API, 3.12.1

int PyMapping_SetItemString(PyObject *o, const char *key, PyObject *v)


ABI. PyObject_SetItem() key const char* UTF-8
PyObject*
int PyMapping_DelItem(PyObject *o, PyObject *key)
PyObject_DelItem()
int PyMapping_DelItemString(PyObject *o, const char *key)
PyObject_DelItem() key const char* UTF-8
PyObject*
int PyMapping_HasKey(PyObject *o, PyObject *key)
ABI. key 1 0 Python key in
o

: __getitem__()
PyObject_GetItem()

int PyMapping_HasKeyString(PyObject *o, const char *key)


ABI. PyMapping_HasKey() key const char* UTF-8
PyObject*

: __getitem__() str
PyMapping_GetItemString()

PyObject *PyMapping_Keys(PyObject *o)


ABI. o NULL
3.7 :
PyObject *PyMapping_Values(PyObject *o)
ABI. o NULL
3.7 :
PyObject *PyMapping_Items(PyObject *o)
ABI. o
NULL
3.7 :

7.6

int PyIter_Check(PyObject *o)


ABI 3.8 . Return non-zero if the object o
PyIter_Next() 0
int PyAIter_Check(PyObject *o)
ABI 3.10 . o AsyncIterator
0
3.10 .

7.6. 97
The Python/C API, 3.12.1

PyObject *PyIter_Next(PyObject *o)


ABI. o PyIter_Check()
NULL
NULL
C

PyObject *iterator = PyObject_GetIter(obj);


PyObject *item;

if (iterator == NULL) {
/* propagate error */
}

while ((item = PyIter_Next(iterator))) {


/* do something with item */
...
/* release reference when done */
Py_DECREF(item);
}

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

PyBUF_FORMAT format NULL


itemsize
shape product(shape) * itemsize == len
itemsize

7.7. 99
The Python/C API, 3.12.1

shape NULL PyBUF_SIMPLE PyBUF_WRITABLE


itemsize itemsize == 1
const char *format
struct NUL NULL "B"
( )
PyBUF_FORMAT
int ndim
n 0 buf
shape, strides suboffsets NULL PyBUF_MAX_NDIM

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

shape strides suboffsets


:
PyBUF_MAX_NDIM

PyBUF_MAX_NDIM 64

7.7.2

PyObject_GetBuffer()
flags
Py_buffer

100 Chapter 7.
The Python/C API, 3.12.1

flags obj, buf len itemsize ndim

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

NULL NULL NULL


PyBUF_SIMPLE

C Fortran C-

NULL C
PyBUF_C_CONTIGUOUS

NULL F
PyBUF_F_CONTIGUOUS

NULL C F
PyBUF_ANY_CONTIGUOUS

PyBUF_ND NULL NULL C

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

NULL NULL C 0 NULL


PyBUF_CONTIG

NULL NULL C 1 0 NULL


PyBUF_CONTIG_RO

7.7.3

NumPy-

NumPy itemsize ndim shape strides


ndim == 0 buf itemsize shape strides
NULL
strides NULL n C
n

ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1];


item = *((typeof(item) *)ptr);

buf

def verify_structure(memlen, itemsize, ndim, shape, strides, offset):


"""Verify that the parameters represent a valid array within
the bounds of the allocated memory:
char *mem: start of the physical memory block
memlen: length of the physical memory block
offset: (char *)buf - mem
"""
if offset % itemsize:
( )

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

imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)


if strides[j] <= 0)
imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)
if strides[j] > 0)

return 0 <= offset+imin and offset+imax+itemsize <= memlen

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

int PyObject_CheckBuffer(PyObject *obj)


ABI 3.11 . obj 1 0 1
PyObject_GetBuffer()
int PyObject_GetBuffer(PyObject *exporter, Py_buffer *view, int flags)
ABI 3.11 . exporter flags view exporter
BufferError view->obj NULL -1
view view->obj exporter 0
view->obj exporter ( )
PyObject_GetBuffer() PyBuffer_Release() malloc()
free() PyBuffer_Release()
void PyBuffer_Release(Py_buffer *view)
ABI 3.11 . view view->obj strong
reference ( )

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

int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len)


ABI. obj
0 buffer buffer_len
-1 TypeError
int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
ABI. obj
0 buffer buffer_len -1
TypeError
int PyObject_CheckReadBuffer(PyObject *o)
ABI. o 1 0

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

unsigned long PyType_GetFlags(PyTypeObject *type)


ABI. type tp_flags Py_LIMITED_API
Python tp_flags API

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.

int PyType_AddWatcher(PyType_WatchCallback callback)


callback ID PyType_Watch()
ID , -1
3.12 .
int PyType_ClearWatcher(int watcher_id)
watcher_id ( PyType_AddWatcher() ) watcher 0
watcher_id -1
PyType_ClearWatcher PyType_AddWatcher()
watcher_id
3.12 .
int PyType_Watch(int watcher_id, PyObject *type)
type PyType_Modified() type PyType_AddWatcher()
watcher_id type
_PyType_Lookup()
PyType_Watch PyType_AddWatcher()
watcher_id
3.12 .
typedef int (*PyType_WatchCallback)(PyObject *type)

type PyType_Modified() type MRO

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

int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)


ABI. a b
__subclasscheck__() b
PyObject_IsSubclass() issubclass()
PyObject *PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
ABI. tp_alloc Python
NULL
PyObject *PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
ABI. tp_new
tp_alloc
int PyType_Ready(PyTypeObject *type)
ABI.
0 -1

: GC Py_TPFLAGS_HAVE_GC
GC
Py_TPFLAGS_HAVE_GC GC tp_traverse

PyObject *PyType_GetName(PyTypeObject *type)


ABI 3.11 . __name__

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

void *PyType_GetModuleState(PyTypeObject *type)


ABI 3.10 .
PyType_GetModule() PyModule_GetState()
TypeError NULL
type NULL NULL
3.9 .
PyObject *PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)
PyModuleDef def
TypeError NULL
PyModule_GetState() ( tp_init nb_add)
PyCMethod
3.11 .
int PyUnstable_Type_AssignVersionTag(PyTypeObject *type)

API

1
0
3.12 .

PyObject *PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec,


PyObject *bases)
ABI 3.12 . spec ( Py_TPFLAGS_HEAPTYPE)
metaclass metaclass NULL bases ( bases
NULL Py_tp_base[s] )
tp_new tp_new NULL PyType_From*
tp_new
Python 3.14+
bases bases NULL
Py_tp_bases NULL Py_tp_base NULL
object
module NULL
NULL PyType_GetModule()

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

Python/C API None PyTypeObject None


C == PyNone_Check()
PyObject *Py_None
Python None
3.12 : Py_None
Py_RETURN_NONE
Py_None

8.2

8.2.1

PyLong_As* API (return type)-1


PyErr_Occurred()
type PyLongObject
API ( ). Python PyObject
PyTypeObject PyLong_Type
ABI. PyTypeObject Python Python int
int PyLong_Check(PyObject *p)
PyLongObject PyLongObject True

int PyLong_CheckExact(PyObject *p)


PyLongObject PyLongObject

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

PyObject *PyLong_FromUnsignedLongLong(unsigned long long v)


ABI. C unsigned long long PyLongObject
NULL
PyObject *PyLong_FromDouble(double v)
ABI. v PyLongObject
NULL
PyObject *PyLong_FromString(const char *str, char **pend, int base)
ABI. str PyLongObject base
NULL pend NULL *pend str
base 0 str integers
ValueError base 0 2
36
str NULL ValueError
:
Python int.to_bytes() int.from_bytes() PyLongObject /
256 PyObject_CallMethod() C
PyObject *PyLong_FromUnicodeObject(PyObject *u, int base)
u Unicode Python
3.3 .
PyObject *PyLong_FromVoidPtr(void *p)
ABI. p Python PyLong_AsVoidPtr()

long PyLong_AsLong(PyObject *obj)


ABI. obj C long obj PyLongObject
__index__() PyLongObject
obj long OverflowError
-1 PyErr_Occurred()
3.8 : __index__()
3.10 : __int__()
long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow)
ABI. obj C long obj PyLongObject
__index__() PyLongObject
obj LONG_MAX LONG_MIN *overflow 1 -1 -1
*overflow 0 *overflow 0 -1
-1 PyErr_Occurred()
3.8 : __index__()
3.10 : __int__()
long long PyLong_AsLongLong(PyObject *obj)
ABI. obj C long long obj PyLongObject
__index__() PyLongObject
obj long long OverflowError
-1 PyErr_Occurred()
3.8 : __index__()
3.10 : __int__()

114 Chapter 8.
The Python/C API, 3.12.1

long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow)


ABI. obj C long long obj PyLongObject
__index__() PyLongObject
obj LLONG_MAX LLONG_MIN *overflow 1 -1
-1 *overflow 0 *overflow 0 -1
-1 PyErr_Occurred()
3.2 .
3.8 : __index__()
3.10 : __int__()
Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)
ABI. pylong C Py_ssize_t pylong PyLongObject
pylong Py_ssize_t OverflowError
-1 PyErr_Occurred()
unsigned long PyLong_AsUnsignedLong(PyObject *pylong)
ABI. pylong C unsigned long pylong PyLongObject
pylong unsigned long OverflowError
(unsigned long)-1 PyErr_Occurred()
size_t PyLong_AsSize_t(PyObject *pylong)
ABI. pylong C size_t pylong PyLongObject
pylong size_t OverflowError
(size_t)-1 PyErr_Occurred()
unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong)
ABI. pylong C unsigned long long pylong PyLongObject

pylong unsigned long long OverflowError


(unsigned long long)-1 PyErr_Occurred()
3.1 : pylong OverflowError TypeError
unsigned long PyLong_AsUnsignedLongMask(PyObject *obj)
ABI. obj C unsigned long obj PyLongObject
__index__() PyLongObject
obj unsigned long ULONG_MAX + 1
(unsigned long)-1 PyErr_Occurred()
3.8 : __index__()
3.10 : __int__()
unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj)
ABI. obj C unsigned long long obj PyLongObject
__index__() PyLongObject
obj unsigned long long ULLONG_MAX + 1

(unsigned long long)-1 PyErr_Occurred()


3.8 : __index__()
3.10 : __int__()

8.2. 115
The Python/C API, 3.12.1

double PyLong_AsDouble(PyObject *pylong)


ABI. pylong C double pylong PyLongObject
pylong double OverflowError
-1.0 PyErr_Occurred()
void *PyLong_AsVoidPtr(PyObject *pylong)
ABI. Python pylong C void pylong
OverflowError PyLong_FromVoidPtr()
void
NULL PyErr_Occurred()
int PyUnstable_Long_IsCompact(const PyLongObject *op)

API

op 1 0

PyUnstable_Long_CompactValue() PyLong_As*
int.to_bytes()

Py_ssize_t PyUnstable_Long_CompactValue(const PyLongObject *op)

API

op PyUnstable_Long_IsCompact()

8.2.2

Python Py_False Py_True

PyTypeObject PyBool_Type
ABI. PyTypeObject Python Python bool

int PyBool_Check(PyObject *o)


o PyBool_Type
PyObject *Py_False
Python False
3.12 : Py_False
PyObject *Py_True
Python True
3.12 : Py_True
Py_RETURN_FALSE
Py_False

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

int PyFloat_CheckExact(PyObject *p)


PyFloatObject PyFloatObject

PyObject *PyFloat_FromString(PyObject *str)


ABI. str PyFloatObject
NULL
PyObject *PyFloat_FromDouble(double v)
ABI. v PyFloatObject NULL
double PyFloat_AsDouble(PyObject *pyfloat)
ABI. pyfloat C double pyfloat Python
__float__() pyfloat
__float__() __index__() -1.0
PyErr_Occurred()
3.8 : __index__()
double PyFloat_AS_DOUBLE(PyObject *pyfloat)
pyfloat C double
PyObject *PyFloat_GetInfo(void)
ABI. structseq float
float.h
double PyFloat_GetMax()
ABI. C double DBL_MAX
double PyFloat_GetMin()
ABI. C double DBL_MIN

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

C API Python Python Python


C API

API
type Py_complex
Python C

typedef struct {
double real;
double imag;
} Py_complex;

Py_complex _Py_c_sum(Py_complex left, Py_complex right)


C Py_complex
Py_complex _Py_c_diff(Py_complex left, Py_complex right)
C Py_complex
Py_complex _Py_c_neg(Py_complex num)
num C Py_complex
Py_complex _Py_c_prod(Py_complex left, Py_complex right)
C Py_complex
Py_complex _Py_c_quot(Py_complex dividend, Py_complex divisor)
C Py_complex
divisor errno EDOM
Py_complex _Py_c_pow(Py_complex num, Py_complex exp)
num exp C Py_complex
num exp errno EDOM

Python

type PyComplexObject
C PyObject Python
PyTypeObject PyComplex_Type
ABI. PyTypeObject Python Python
complex
int PyComplex_Check(PyObject *p)
PyComplexObject PyComplexObject

int PyComplex_CheckExact(PyObject *p)


PyComplexObject PyComplexObject

PyObject *PyComplex_FromCComplex(Py_complex v)
C Py_complex Python

8.2. 119
The Python/C API, 3.12.1

PyObject *PyComplex_FromDoubles(double real, double imag)


ABI. real imag C PyComplexObject

double PyComplex_RealAsDouble(PyObject *op)


ABI. C double op
double PyComplex_ImagAsDouble(PyObject *op)
ABI. C double op
Py_complex PyComplex_AsCComplex(PyObject *op)
op C Py_complex
op Python __complex__() op
Python __complex__() __float__() __float__()
__index__() -1.0
3.8 : __index__()

8.3

; Python

8.3.1 bytes

TypeError
type PyBytesObject
PyObject Python
PyTypeObject PyBytes_Type
ABI. PyTypeObject Python Python bytes

int PyBytes_Check(PyObject *o)


o bytes bytes
int PyBytes_CheckExact(PyObject *o)
o bytes bytes

PyObject *PyBytes_FromString(const char *v)


ABI. v
NULL v NULL
PyObject *PyBytes_FromStringAndSize(const char *v, Py_ssize_t len)
ABI. v len
NULL v NULL
PyObject *PyBytes_FromFormat(const char *format, ...)
ABI. C printf() format
Python
C format :

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

PyObject *PyBytes_FromFormatV(const char *format, va_list vargs)


ABI. PyBytes_FromFormat()
PyObject *PyBytes_FromObject(PyObject *o)
ABI. *o*
Py_ssize_t PyBytes_Size(PyObject *o)
ABI. *o*
Py_ssize_t PyBytes_GET_SIZE(PyObject *o)
PyBytes_Size()
char *PyBytes_AsString(PyObject *o)
ABI. o o len(o) + 1

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

void PyBytes_ConcatAndDel(PyObject **bytes, PyObject *newpart)


ABI. *bytes bytes newpart
newpart strong reference ( )
int _PyBytes_Resize(PyObject **bytes, Py_ssize_t newsize)

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

int PyByteArray_Check(PyObject *o)


o bytearray bytearray

int PyByteArray_CheckExact(PyObject *o)


o bytearray bytearray

API

PyObject *PyByteArray_FromObject(PyObject *o)


ABI. o

PyObject *PyByteArray_FromStringAndSize(const char *string, Py_ssize_t len)


ABI. string len bytearray
NULL
PyObject *PyByteArray_Concat(PyObject *a, PyObject *b)
ABI. a b
Py_ssize_t PyByteArray_Size(PyObject *bytearray)
ABI. NULL bytearray
char *PyByteArray_AsString(PyObject *bytearray)
ABI. NULL bytearray

int PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len)


ABI. bytearray len

122 Chapter 8.
The Python/C API, 3.12.1

char *PyByteArray_AS_STRING(PyObject *bytearray)


PyByteArray_AsString()
Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray)
PyByteArray_Size()

8.3.3 Unicode

Unicode

python3.3 PEP 393 Unicode


Unicode 128 256 65536
1114112 Unicode
UTF-8 Unicode

: Py_UNICODE Python 3.12 API PEP 623

Unicode

Python Unicode Unicode


type Py_UCS4
type Py_UCS2
type Py_UCS1
ABI. 32 16 8
Unicode Py_UCS4
3.3 .
type Py_UNICODE
wchar_t 16 32
3.3 : 16 32
Unicode Python
type PyASCIIObject
type PyCompactUnicodeObject
type PyUnicodeObject
PyObject Python Unicode
Unicode API PyObject
3.3 .
PyTypeObject PyUnicode_Type
ABI. PyTypeObject Python Unicode str Python

API C Unicode
int PyUnicode_Check(PyObject *obj)
obj Unicode Unicode

8.3. 123
The Python/C API, 3.12.1

int PyUnicode_CheckExact(PyObject *obj)


obj Unicode
int PyUnicode_READY(PyObject *unicode)
0 API
3.3 .
3.10 : API Python 3.12
Py_ssize_t PyUnicode_GET_LENGTH(PyObject *unicode)
Unicode unicode Unicode

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

Py_UCS4 PyUnicode_MAX_CHAR_VALUE(PyObject *unicode)


unicode

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

Py_UCS4 Py_UNICODE_TOUPPER(Py_UCS4 ch)


ch
3.3 :
Py_UCS4 Py_UNICODE_TOTITLE(Py_UCS4 ch)
ch
3.3 :
int Py_UNICODE_TODECIMAL(Py_UCS4 ch)
ch -1
int Py_UNICODE_TODIGIT(Py_UCS4 ch)
ch -1
double Py_UNICODE_TONUMERIC(Py_UCS4 ch)
ch -1.0
API
int Py_UNICODE_IS_SURROGATE(Py_UCS4 ch)
ch (0xD800 <= ch <= 0xDFFF)
int Py_UNICODE_IS_HIGH_SURROGATE(Py_UCS4 ch)
ch (0xD800 <= ch <= 0xDBFF)
int Py_UNICODE_IS_LOW_SURROGATE(Py_UCS4 ch)
ch (0xDC00 <= ch <= 0xDFFF)
Py_UCS4 Py_UNICODE_JOIN_SURROGATES(Py_UCS4 high, Py_UCS4 low)
Py_UCS4 high low
high [0xD800; 0xDBFF] low [0xDC00; 0xDFFF]

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

PyObject *PyUnicode_FromFormat(const char *format, ...)


ABI. C printf() format
Python Unicode
C format ASCII

1. '%'
2.
3. '*' ( )
int
4. '.' ( ) '*' ( )
int
5.
6.

0
- 0

(d, i, o, u, x, or X) ( int):

l long unsigned long


ll long long unsigned long long
j intmax_t uintmax_t
z size_t ssize_t
t ptrdiff_t

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)

3.2 : "%lld" "%llu"


3.3 : "%li", "%lli" "%zi"
3.4 : "%s", "%A", "%U", "%V", "%S", "%R"
3.12 : o X j t
l s V * -
SystemError

PyObject *PyUnicode_FromFormatV(const char *format, va_list vargs)


ABI. PyUnicode_FromFormat()
PyObject *PyUnicode_FromObject(PyObject *obj)
ABI. Unicode Unicode
obj Unicode strong
reference
Unicode TypeError
PyObject *PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)
ABI. obj Unicode
bytes, bytearray encoding errors
NULL

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

PyObject *PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t length, const char *errors)


ABI 3.7 . Android VxWorks
UTF-8 "strict"
"surrogateescape" (PEP 383) errors NULL "strict"
str
PyUnicode_DecodeFSDefaultAndSize() filesystem encoding and error handler

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

filesystem encoding and error handler (PEP 383 PEP 529)


bytes "O&" PyUnicode_FSConverter()

int PyUnicode_FSConverter(PyObject *obj, void *result)


ABI. ParseTuple str -- os.PathLike --
PyUnicode_EncodeFSDefault() bytes bytes result
PyBytesObject*
3.1 .
3.6 : path-like object

130 Chapter 8.
The Python/C API, 3.12.1

str "O&" PyUnicode_FSDecoder()

int PyUnicode_FSDecoder(PyObject *obj, void *result)


ABI. ParseTuple bytes -- os.PathLike
-- PyUnicode_DecodeFSDefaultAndSize() str str
result PyUnicodeObject*
3.2 .
3.6 : path-like object
PyObject *PyUnicode_DecodeFSDefaultAndSize(const char *str, Py_ssize_t size)
ABI. filesystem encoding and error handler

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 encoding errors str()

encoding NULL UTF-8


PyUnicode_FSConverter() filesystem encoding and error han-
dler
errors NULL
”strict” ( ValueError)

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

const char *PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size)


ABI 3.10 . Unicode UTF-8
size size NULL
size

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 == -1: little endian


*byteorder == 0: native order
*byteorder == 1: big endian

*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

PyObject *PyUnicode_AsUTF32String(PyObject *unicode)


ABI. UTF-32 Python
BOM ”strict” NULL

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 == -1: little endian


*byteorder == 0: native order
*byteorder == 1: big endian

*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

”Unicode Escape” API:


PyObject *PyUnicode_DecodeUnicodeEscape(const char *str, Py_ssize_t size, const char *errors)
ABI. Unicode-Escape str size
Unicode NULL
PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
ABI. Unicode-Escape Unicode
”strict” NULL

Raw-Unicode-Escape

”Raw Unicode Escape” API:


PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *str, Py_ssize_t size, const char *errors)
ABI. Raw-Unicode-Escape str size
Unicode NULL
PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
ABI. Raw-Unicode-Escape Unicode
”strict” NULL

Latin-1

Latin-1 API: Latin-1 256 Unicode

PyObject *PyUnicode_DecodeLatin1(const char *str, Py_ssize_t size, const char *errors)


ABI. Latin-1 str size Unicode
NULL
PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
ABI. Latin-1 Unicode Python
”strict” NULL

ASCII

ASCII API 7 ASCII


PyObject *PyUnicode_DecodeASCII(const char *str, Py_ssize_t size, const char *errors)
ABI. ASCII str size Unicode
NULL
PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
ABI. ASCII Unicode Python
”strict” NULL

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'

PyObject *PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)


ABI. mapping Unicode
”strict” NULL
mapping Unicode 0 255 None
LookupError None

API Unicode Unicode


PyObject *PyUnicode_Translate(PyObject *unicode, PyObject *table, const char *errors)
ABI. Unicode
NULL
Unicode Unicode None ( )
__getitem__()
LookupError
errors NULL

Windows MBCS

MBCS API Windows Win32 MBCS


MBCS DBCS

PyObject *PyUnicode_DecodeMBCS(const char *str, Py_ssize_t size, const char *errors)


ABI on Windows 3.7 . MBCS str
size Unicode NULL
PyObject *PyUnicode_DecodeMBCSStateful(const char *str, Py_ssize_t size, const char *errors,
Py_ssize_t *consumed)
ABI on Windows 3.7 . consumed
NULL PyUnicode_DecodeMBCS() consumed NULL
PyUnicode_DecodeMBCSStateful()
consumed
PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
ABI on Windows 3.7 . MBCS Unicode
Python ”strict” NULL

136 Chapter 8.
The Python/C API, 3.12.1

PyObject *PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors)


ABI on Windows 3.7 . Unicode
Python NULL CP_ACP
MBCS
3.3 .

API Unicode Unicode

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

int PyUnicode_Compare(PyObject *left, PyObject *right)


ABI. -1, 0, 1
-1 PyErr_Occurred()
int PyUnicode_CompareWithASCIIString(PyObject *unicode, const char *string)
ABI. Unicode unicode string -1, 0, 1
ASCII ASCII
ISO-8859-1

PyObject *PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)


ABI. Unicode :
• NULL
• Py_True Py_False
• Py_NotImplemented
op Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE
PyObject *PyUnicode_Format(PyObject *format, PyObject *args)
ABI. format args format
% args
int PyUnicode_Contains(PyObject *unicode, PyObject *substr)
ABI. substr unicode
substr Unicode -1
void PyUnicode_InternInPlace(PyObject **p_unicode)
ABI. *p_unicode Python Unicode
*p_unicode *p_unicode
( strong reference)
*p_unicode ( strong reference) (

)
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

int PyTuple_Check(PyObject *p)


p tuple tuple
int PyTuple_CheckExact(PyObject *p)
p tuple tuple
PyObject *PyTuple_New(Py_ssize_t len)
ABI. len NULL

138 Chapter 8.
The Python/C API, 3.12.1

PyObject *PyTuple_Pack(Py_ssize_t n, ...)


ABI. n
NULL Python n C PyTuple_Pack(2, a, b)
Py_BuildValue("(OO)", a, b)
Py_ssize_t PyTuple_Size(PyObject *p)
ABI.
Py_ssize_t PyTuple_GET_SIZE(PyObject *p)
p NULL
PyObject *PyTuple_GetItem(PyObject *p, Py_ssize_t pos)
ABI. p pos pos
NULL IndexError
PyObject *PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)
PyTuple_GetItem()
PyObject *PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high)
ABI. p low high
NULL Python p[low:high]
int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
ABI. p pos o 0 pos
-1 IndexError

: o

void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o)


PyTuple_SetItem()

: o PyTuple_SetItem()
pos

int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize)


newsize

0 *p *p
*p -1 *p NULL MemoryError
SystemError

8.3.5

namedtuple() C

PyTypeObject *PyStructSequence_NewType(PyStructSequence_Desc *desc)


ABI. desc
PyStructSequence_New()
void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc)
desc type

8.3. 139
The Python/C API, 3.12.1

int PyStructSequence_InitType2(PyTypeObject *type, PyStructSequence_Desc *desc)


PyStructSequence_InitType 0 -1
3.4 .
type PyStructSequence_Desc
ABI ( ).
const char *name

const char *doc


NULL
PyStructSequence_Field *fields
NULL
int n_in_sequence
Python
type PyStructSequence_Field
ABI ( ).
PyObject* PyStructSequence_Desc fields

const char *name


NULL PyStructSequence_UnnamedField

const char *doc


NULL
const char *const PyStructSequence_UnnamedField
ABI 3.11 .
3.9 : char *
PyObject *PyStructSequence_New(PyTypeObject *type)
ABI. type
PyStructSequence_NewType()
PyObject *PyStructSequence_GetItem(PyObject *p, Py_ssize_t pos)
ABI. p pos

PyObject *PyStructSequence_GET_ITEM(PyObject *p, Py_ssize_t pos)


PyStructSequence_GetItem()
void PyStructSequence_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
ABI. p pos o PyTuple_SET_ITEM()

: o

void PyStructSequence_SET_ITEM(PyObject *p, Py_ssize_t *pos, PyObject *o)


PyStructSequence_SetItem()

: 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

Py_ssize_t PyList_Size(PyObject *list)


ABI. list len(list)
Py_ssize_t PyList_GET_SIZE(PyObject *list)
PyList_Size()
PyObject *PyList_GetItem(PyObject *list, Py_ssize_t index)
ABI. list index
index (<0 or >=len(list)) NULL
IndexError
PyObject *PyList_GET_ITEM(PyObject *list, Py_ssize_t i)
PyList_GetItem()
int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item)
ABI. index item 0 index -1
IndexError

: item

void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o)


PyList_SetItem()

: item PyList_SetItem()
list i

int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item)


ABI. item list index 0
-1 list.insert(index, item)
int PyList_Append(PyObject *list, PyObject *item)
ABI. item list 0 -1
list.append(item)

8.3. 141
The Python/C API, 3.12.1

PyObject *PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high)


ABI. list low high
NULL list[low:high]
int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist)
ABI. list low high itemlist list[low:high]
= itemlist itemlist NULL 0
-1
int PyList_Sort(PyObject *list)
ABI. list 0 -1 list.
sort()
int PyList_Reverse(PyObject *list)
ABI. list 0 -1 list.
reverse()
PyObject *PyList_AsTuple(PyObject *list)
ABI. list
tuple(list)

8.4

8.4.1

type PyDictObject
PyObject Python
PyTypeObject PyDict_Type
ABI. Python PyTypeObject Python dict

int PyDict_Check(PyObject *p)


p dict dict
int PyDict_CheckExact(PyObject *p)
p dict dict
PyObject *PyDict_New()
ABI. NULL
PyObject *PyDictProxy_New(PyObject *mapping)
ABI. types.MappingProxyType

void PyDict_Clear(PyObject *p)


ABI.
int PyDict_Contains(PyObject *p, PyObject *key)
ABI. key p key p 1 0
-1 Python key in p
PyObject *PyDict_Copy(PyObject *p)
ABI. p
int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
ABI. key val p key hashable
TypeError 0 -1 val

142 Chapter 8.
The Python/C API, 3.12.1

int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)


ABI. PyDict_SetItem() key const char* UTF-8
PyObject*
int PyDict_DelItem(PyObject *p, PyObject *key)
ABI. p key key hashable TypeError
key KeyError 0 -1
int PyDict_DelItemString(PyObject *p, const char *key)
ABI. PyDict_DelItem() key const char* UTF-8
PyObject*
PyObject *PyDict_GetItem(PyObject *p, PyObject *key)
ABI. p key key
NULL

: __hash__() __eq__()
PyDict_GetItemWithError()

3.10 : GIL API


PyObject *PyDict_GetItemWithError(PyObject *p, PyObject *key)
ABI. PyDict_GetItem()
NULL NULL
PyObject *PyDict_GetItemString(PyObject *p, const char *key)
ABI. PyDict_GetItem() key const
char* UTF-8 PyObject*

: __hash__() __eq__() str


PyDict_GetItemWithError()
PyUnicode_FromString() key

PyObject *PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj)


Python dict.setdefault() key
p defaultobj defaultobj
key
3.4 .
PyObject *PyDict_Items(PyObject *p)
ABI. PyListObject
PyObject *PyDict_Keys(PyObject *p)
ABI. (keys) PyListObject
PyObject *PyDict_Values(PyObject *p)
ABI. (values) PyListObject
Py_ssize_t PyDict_Size(PyObject *p)
ABI. p len(p)
int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
ABI. p ppos
Py_ssize_t 0
pkey pvalue PyObject*
NULL ppos

8.4. 143
The Python/C API, 3.12.1

PyObject *key, *value;


Py_ssize_t pos = 0;

while (PyDict_Next(self->dict, &pos, &key, &value)) {


/* do something interesting with the values... */
...
}

p
:

PyObject *key, *value;


Py_ssize_t pos = 0;

while (PyDict_Next(self->dict, &pos, &key, &value)) {


long i = PyLong_AsLong(value);
if (i == -1 && PyErr_Occurred()) {
return -1;
}
PyObject *o = PyLong_FromLong(i + 1);
if (o == NULL)
return -1;
if (PyDict_SetItem(self->dict, key, o) < 0) {
Py_DECREF(o);
return -1;
}
Py_DECREF(o);
}

int PyDict_Merge(PyObject *a, PyObject *b, int override)


ABI. b a b
PyMapping_Keys() PyObject_GetItem() override b
a a
0 -1
int PyDict_Update(PyObject *a, PyObject *b)
ABI. C PyDict_Merge(a, b, 1) Python a.
update(b) PyDict_Update() ”keys”
0 -1
int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)
ABI. seq2 a seq2 2
override 0
-1 Python :

def PyDict_MergeFromSeq2(a, seq2, override):


for key, value in seq2:
if override or key not in a:
a[key] = value

int PyDict_AddWatcher(PyDict_WatchCallback callback)


callback watcher id PyDict_Watch()
watcher ID -1
3.12 .
int PyDict_ClearWatcher(int watcher_id)
PyDict_AddWatcher() watcher_id watcher 0
watcher_id -1
3.12 .

144 Chapter 8.
The Python/C API, 3.12.1

int PyDict_Watch(int watcher_id, PyObject *dict)


dict PyDict_AddWatcher() watcher_id dict
0 -1
3.12 .
int PyDict_Unwatch(int watcher_id, PyObject *dict)
dict PyDict_AddWatcher() watcher_id dict
0
-1
3.12 .
type PyDict_WatchEvent
: PyDict_EVENT_ADDED, PyDict_EVENT_MODIFIED,
PyDict_EVENT_DELETED, PyDict_EVENT_CLONED, PyDict_EVENT_CLEARED
PyDict_EVENT_DEALLOCATED
3.12 .
typedef int (*PyDict_WatchCallback)(PyDict_WatchEvent event, PyObject *dict, PyObject *key, PyObject
*new_value)

event PyDict_EVENT_CLEARED PyDict_EVENT_DEALLOCATED key new_value


NULL event PyDict_EVENT_ADDED PyDict_EVENT_MODIFIED new_value
key event PyDict_EVENT_DELETED key new_value
NULL
PyDict_EVENT_CLONED dict
PyDict_EVENT_ADDED
PyDict_EVENT_CLONED key
dict
Python dict
event PyDict_EVENT_DEALLOCATED

dict dict
-1
PyErr_WriteUnraisable() 0
0
API

3.12 .

8.4.2

set frozenset API


( PyObject_CallMethod(), PyObject_RichCompareBool(), PyObject_Hash(),
PyObject_Repr(), PyObject_IsTrue(), PyObject_Print() PyObject_GetIter())
( PyNumber_And(), PyNumber_Subtract(), PyNumber_Or(),
PyNumber_Xor(), PyNumber_InPlaceAnd(), PyNumber_InPlaceSubtract(),
PyNumber_InPlaceOr() PyNumber_InPlaceXor())
type PySetObject
PyObject set frozenset
PyDictObject

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

int PySet_CheckExact(PyObject *p)


p set
3.10 .
int PyAnySet_CheckExact(PyObject *p)
p set frozenset

int PyFrozenSet_CheckExact(PyObject *p)


p frozenset
PyObject *PySet_New(PyObject *iterable)
ABI. set iterable iterable
NULL NULL iterable
TypeError (c=set(s))
PyObject *PyFrozenSet_New(PyObject *iterable)
ABI. frozenset iterable
iterable NULL NULL
iterable TypeError
set frozenset
Py_ssize_t PySet_Size(PyObject *anyset)
ABI. set frozenset len(anyset) anyset set,
frozenset SystemError
Py_ssize_t PySet_GET_SIZE(PyObject *anyset)
PySet_Size()
int PySet_Contains(PyObject *anyset, PyObject *key)
ABI. 1 0 -1 Python
__contains__() key
TypeError anyset set, frozenset
SystemError

146 Chapter 8.
The Python/C API, 3.12.1

int PySet_Add(PyObject *set, PyObject *key)


ABI. key set frozenset PyTuple_SetItem()

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

int PyFunction_Check(PyObject *o)


o ( PyFunction_Type) NULL

PyObject *PyFunction_New(PyObject *code, PyObject *globals)


code globals

__module__ globals
defaults, annotations closure NULL __qualname__ co_qualname

PyObject *PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)


PyFunction_New() __qualname__
qualname unicode NULL NULL __qualname__
co_qualname
3.3 .
PyObject *PyFunction_GetCode(PyObject *op)
op

8.5. Function 147


The Python/C API, 3.12.1

PyObject *PyFunction_GetGlobals(PyObject *op)


*op*
PyObject *PyFunction_GetModule(PyObject *op)
op __module__ borrowed reference
NULL
Python
PyObject *PyFunction_GetDefaults(PyObject *op)
op NULL
int PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
op defaults Py_None
SystemError -1
void PyFunction_SetVectorcall(PyFunctionObject *func, vectorcallfunc vectorcall)
func vectorcall
API vectorcall
3.12 .
PyObject *PyFunction_GetClosure(PyObject *op)
op NULL cell
int PyFunction_SetClosure(PyObject *op, PyObject *closure)
op closure Py_None cell
SystemError -1
PyObject *PyFunction_GetAnnotations(PyObject *op)
op NULL
int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
op annotations Py_None
SystemError -1
int PyFunction_AddWatcher(PyFunction_WatchCallback callback)
callback PyFunction_ClearWatcher()
ID ID -1
3.12 .
int PyFunction_ClearWatcher(int watcher_id)
Clear watcher identified by previously returned from
PyFunction_AddWatcher() watcher_id 0
watcher_id -1
3.12 .
type PyFunction_WatchEvent
: - PyFunction_EVENT_CREATE
- PyFunction_EVENT_DESTROY - PyFunction_EVENT_MODIFY_CODE -
PyFunction_EVENT_MODIFY_DEFAULTS - PyFunction_EVENT_MODIFY_KWDEFAULTS
3.12 .
typedef int (*PyFunction_WatchCallback)(PyFunction_WatchEvent event, PyFunctionObject *func,
PyObject *new_value)

148 Chapter 8.
The Python/C API, 3.12.1

event PyFunction_EVENT_CREATE PyFunction_EVENT_DESTROY new_value


NULL new_value func
borrowed reference
func;
event PyFunction_EVENT_CREATE func
func func

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

PyObject *PyInstanceMethod_Function(PyObject *im)


im
PyObject *PyInstanceMethod_GET_FUNCTION(PyObject *im)
PyInstanceMethod_Function()

8.5.3

PyTypeObject PyMethod_Type
PyTypeObject Python types.MethodType Python

int PyMethod_Check(PyObject *o)


o ( PyMethod_Type) NULL

8.5. Function 149


The Python/C API, 3.12.1

PyObject *PyMethod_New(PyObject *func, PyObject *self)


func self
func self NULL
PyObject *PyMethod_Function(PyObject *meth)
meth
PyObject *PyMethod_GET_FUNCTION(PyObject *meth)
PyMethod_Function()
PyObject *PyMethod_Self(PyObject *meth)
meth
PyObject *PyMethod_GET_SELF(PyObject *meth)
PyMethod_Self()

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

int PyCell_Set(PyObject *cell, PyObject *value)


cell cell value cell value NULL
cell NULL cell -1 0
void PyCell_SET(PyObject *cell, PyObject *value)
cell cell value 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

PyCodeObject *PyUnstable_Code_NewWithPosOnlyArgs(int argcount, int posonlyargcount, 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

PyUnstable_Code_New() ”posonlyargcount”
PyUnstable_Code_New
3.8 : PyCode_NewWithPosOnlyArgs
3.11 : qualname exceptiontable
3.12 : PyUnstable_Code_NewWithPosOnlyArgs

PyCodeObject *PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)

Exception

8.5. Function 151


The Python/C API, 3.12.1

int PyCode_Addr2Line(PyCodeObject *co, int byte_offset)


byte_offset
PyFrame_GetLineNumber()
PEP 626 API
int PyCode_Addr2Location(PyObject *co, int byte_offset, int *start_line, int *start_column, int *end_line,
int *end_column)
int byte_offset
0
1 0
3.11 .
PyObject *PyCode_GetCode(PyCodeObject *co)
Python getattr(co, 'co_code')
PyBytesObject NULL
PyBytesObject CPython

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

C API CPython API

Py_ssize_t PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)

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

int PyUnstable_Code_SetExtra(PyObject *code, Py_ssize_t index, void *extra)

API

extra 0 -1
3.6 : _PyCode_SetExtra

8.5. Function 153


The Python/C API, 3.12.1

3.12 : Renamed to PyUnstable_Code_SetExtra. The old private name is deprecated, but


will be available until the API changes.

8.6

8.6.1

API Python 2 C API C I/O


(FILE*) Python 3 io I/O
API C
io API
PyObject *PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding,
const char *errors, const char *newline, int closefd)
ABI. fd Python
name, encoding, errors newline NULL buffering -1
name NULL
io.open()

: 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

int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)


ABI. obj p flags Py_PRINT_RAW
str() repr() 0 -1
int PyFile_WriteString(const char *s, PyObject *p)
ABI. s p 0 -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

PyObject *PyModule_NewObject(PyObject *name)


ABI 3.7 . __name__ name
__name__, __doc__, __package__, and __loader__
__name__ None __file__
3.3 .
3.4 : __package__ __loader__ None
PyObject *PyModule_New(const char *name)
ABI. PyModule_NewObject() UTF-8
Unicode
PyObject *PyModule_GetDict(PyObject *module)
ABI. module
__dict__ module
SystemError NULL
PyModule_* PyObject_* __dict__
PyObject *PyModule_GetNameObject(PyObject *module)
ABI 3.7 . module __name__
SystemError NULL
3.3 .
const char *PyModule_GetName(PyObject *module)
ABI. PyModule_GetNameObject() 'utf-8'
void *PyModule_GetState(PyObject *module)
ABI.
NULL PyModuleDef.m_size
PyModuleDef *PyModule_GetDef(PyObject *module)
ABI. PyModuleDef
NULL
PyObject *PyModule_GetFilenameObject(PyObject *module)
ABI. module __file__
Unicode SystemError NULL
Unicode
3.2 .

8.6. 155
The Python/C API, 3.12.1

const char *PyModule_GetFilename(PyObject *module)


ABI. PyModule_GetFilenameObject() ’utf-8’
3.2 : PyModule_GetFilename()
UnicodeEncodeError PyModule_GetFilenameObject()

PyImport_AppendInittab() building extending-with-embedding

PyModule_Create()

type PyModuleDef
ABI ( ).

PyModuleDef_Base m_base
PyModuleDef_HEAD_INIT
const char *m_name

const char *m_doc


PyDoc_STRVAR
Py_ssize_t m_size
PyModule_GetState()

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 :

PyObject *PyModule_Create(PyModuleDef *def)


def
PyModule_Create2() module_api_version PYTHON_API_VERSION
PyObject *PyModule_Create2(PyModuleDef *def, int module_api_version)
ABI. def
API module_api_version
RuntimeWarning

: 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

PyObject *PyModuleDef_Init(PyModuleDef *def)


ABI 3.5 . Python

PyObject* def NULL


3.5 .
m_slots PyModuleDef_Slot :
type PyModuleDef_Slot

int slot
ID
void *value
ID
3.5 .
m_slots id 0
:
Py_mod_create
value :
PyObject *create_module(PyObject *spec, PyModuleDef *def)

ModuleSpec PEP 451


NULL
Python

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

int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)


ABI 3.10 . *name* *module*

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;
}

Py_XDECREF() Py_DECREF() obj NULL


3.10 .
int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)
ABI. PyModule_AddObjectRef() value
0
PyModule_AddObjectRef() PyModule_AddObject()

: 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;
}

Py_XDECREF() Py_DECREF() obj NULL


int PyModule_AddIntConstant(PyObject *module, const char *name, long value)
ABI. *name* *module*
-1 0
int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)
ABI. *name* *module*
*value* NULL -1
0
PyModule_AddIntMacro(module, macro)
*module* *macro*
PyModule_AddIntMacro(module, AF_INET) *AF_INET* *AF_INET*
*module* -1 0
PyModule_AddStringMacro(module, macro)
*module*
int PyModule_AddType(PyObject *module, PyTypeObject *type)
ABI 3.10 . module
PyType_Ready() tp_name
-1 0
3.9 .

8.6. 161
The Python/C API, 3.12.1

PyObject *PyState_FindModule(PyModuleDef *def)


ABI. def
PyState_AddModule()
NULL
int PyState_AddModule(PyObject *module, PyModuleDef *def)
ABI 3.3 .
PyState_FindModule()

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()

int PySeqIter_Check(PyObject *op)


op PySeqIter_Type
PyObject *PySeqIter_New(PyObject *seq)
ABI. seq
IndexError
PyTypeObject PyCallIter_Type
ABI. PyCallIter_New() iter()

int PyCallIter_Check(PyObject *op)


op PyCallIter_Type

162 Chapter 8.
The Python/C API, 3.12.1

PyObject *PyCallIter_New(PyObject *callable, PyObject *sentinel)


ABI. callable
Python callable
sentinel

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)

PyObject *PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)


ABI.
int PyDescr_IsData(PyObject *descr)
descr
0 descr
PyObject *PyWrapper_New(PyObject*, PyObject*)
ABI.

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

3.2 : slice PySliceObject*

8.6. 163
The Python/C API, 3.12.1

int PySlice_GetIndicesEx(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop,


Py_ssize_t *step, Py_ssize_t *slicelength)
ABI. PySlice_GetIndices() slice start, stop step
length slicelength

0 -1

: PySlice_Unpack()
PySlice_AdjustIndices()

if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength) <␣


,→0) {

// return error
}

if (PySlice_Unpack(slice, &start, &stop, &step) < 0) {


// return error
}
slicelength = PySlice_AdjustIndices(length, &start, &stop, step);

3.2 : slice PySliceObject*


3.6.1 :
Py_LIMITED_API 0x03050400 0x03060000
0x03060100 PySlice_GetIndicesEx()
PySlice_Unpack() PySlice_AdjustIndices() start, stop step

3.6.1 : Py_LIMITED_API 0x03050400 0x03060000


0x03060100 PySlice_GetIndicesEx()
int PySlice_Unpack(PyObject *slice, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
ABI 3.7 . start, stop step C
PY_SSIZE_T_MAX PY_SSIZE_T_MAX PY_SSIZE_T_MIN
start stop PY_SSIZE_T_MIN -PY_SSIZE_T_MAX step
-PY_SSIZE_T_MAX
-1 0
3.6.1 .
Py_ssize_t PySlice_AdjustIndices(Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step)
ABI 3.7 . start/end

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

Py_buffer *PyMemoryView_GET_BUFFER(PyObject *mview)


memoryview mview memoryview

PyObject *PyMemoryView_GET_BASE(PyObject *mview)


memoryview memoryview
PyMemoryView_FromMemory() PyMemoryView_FromBuffer() NULL
mview memoryview

8.6.7

Python

int PyWeakref_Check(PyObject *ob)


ob
int PyWeakref_CheckRef(PyObject *ob)
ob
int PyWeakref_CheckProxy(PyObject *ob)
ob

8.6. 165
The Python/C API, 3.12.1

PyObject *PyWeakref_NewRef(PyObject *ob, PyObject *callback)


ABI. ob
callback
ob
callback None NULL ob callback
None NULL NULL TypeError
PyObject *PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
ABI. ob
callback
ob
callback None NULL ob callback
None NULL NULL TypeError
PyObject *PyWeakref_GetObject(PyObject *ref)
ABI. ref
Py_None

: borrowed reference
Py_INCREF()

PyObject *PyWeakref_GET_OBJECT(PyObject *ref)


PyWeakref_GetObject()
void PyObject_ClearWeakRefs(PyObject *object)
ABI. tp_dealloc
object

8.6.8 Capsule

using-capsules
3.1 .
type PyCapsule
PyObject void* Python
C C C
C API
type PyCapsule_Destructor
ABI. Capsule

typedef void (*PyCapsule_Destructor)(PyObject *);

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

destructor NULL capsule


capsule name modulename.
attributename PyCapsule_Import() capsule
void *PyCapsule_GetPointer(PyObject *capsule, const char *name)
ABI. capsule pointer NULL
name capsule capsule NULL
name NULL Python C strcmp() capsule
PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *capsule)
ABI. capsule NULL
capsule NULL NULL
PyCapsule_IsValid() PyErr_Occurred()
void *PyCapsule_GetContext(PyObject *capsule)
ABI. capsule NULL
capsule NULL NULL
PyCapsule_IsValid() PyErr_Occurred()
const char *PyCapsule_GetName(PyObject *capsule)
ABI. capsule NULL
capsule NULL NULL
PyCapsule_IsValid() PyErr_Occurred()
void *PyCapsule_Import(const char *name, int no_block)
ABI. C name
module.attribute name
capsule NULL
3.3 : no_block
int PyCapsule_IsValid(PyObject *capsule, const char *name)
ABI. capsule capsule NULL
PyCapsule_CheckExact() NULL name
PyCapsule_GetPointer() capsule
PyCapsule_IsValid() PyCapsule_Get

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

3.11 : C API What’s New entry


PyEval_GetFrame() PyThreadState_GetFrame()
Reflection 1
PyTypeObject PyFrame_Type
Python types.FrameType
3.11 : <frameobject.h>
int PyFrame_Check(PyObject *obj)
obj
3.11 : <frameobject.h>
PyFrameObject *PyFrame_GetBack(PyFrameObject *frame)
frame
strong reference frame NULL
3.9 .
PyObject *PyFrame_GetBuiltins(PyFrameObject *frame)
frame f_builtins
strong reference NULL
3.11 .
PyCodeObject *PyFrame_GetCode(PyFrameObject *frame)
ABI 3.10 . frame
strong reference
NULL
3.9 .
PyObject *PyFrame_GetGenerator(PyFrameObject *frame)
NULL
NULL
strong reference NULL
3.11 .
PyObject *PyFrame_GetGlobals(PyFrameObject *frame)
frame f_globals
strong reference NULL
3.11 .
int PyFrame_GetLasti(PyFrameObject *frame)
frame f_lasti
frame.f_lasti None -1
3.11 .

168 Chapter 8.
The Python/C API, 3.12.1

PyObject *PyFrame_GetVar(PyFrameObject *frame, PyObject *name)


frame name
• strong reference
• NameError NULL
• “NULL“
name str
3.12 .
PyObject *PyFrame_GetVarString(PyFrameObject *frame, const char *name)
PyFrame_GetVar() UTF-8 C
3.12 .
PyObject *PyFrame_GetLocals(PyFrameObject *frame)
frame f_locals (dict)
strong reference
3.11 .
int PyFrame_GetLineNumber(PyFrameObject *frame)
ABI 3.10 . frame

: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

int PyGen_Check(PyObject *ob)


ob generator ob NULL
int PyGen_CheckExact(PyObject *ob)
ob PyGen_Type ob NULL
PyObject *PyGen_New(PyFrameObject *frame)
frame frame
NULL
PyObject *PyGen_NewWithQualName(PyFrameObject *frame, PyObject *name, PyObject *qualname)
frame __name__
__qualname__ name qualname frame frame
NULL

8.6.11

3.5 .
async
type PyCoroObject
C
PyTypeObject PyCoro_Type

int PyCoro_CheckExact(PyObject *ob)


ob PyCoro_Type ob NULL
PyObject *PyCoro_New(PyFrameObject *frame, PyObject *name, PyObject *qualname)
frame __name__
__qualname__ name qualname frame frame
NULL

8.6.12

3.7.1 :

: Python 3.7.1 C API PyObject PyContext,


PyContextVar PyContextToken :

// 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

int PyContext_CheckExact(PyObject *o)


o PyContext_Type o NULL
int PyContextVar_CheckExact(PyObject *o)
o PyContextVar_Type o NULL
int PyContextToken_CheckExact(PyObject *o)
o PyContextToken_Type o NULL
:
PyObject *PyContext_New(void)
NULL
PyObject *PyContext_Copy(PyObject *ctx)
ctx NULL
PyObject *PyContext_CopyCurrent(void)
NULL
int PyContext_Enter(PyObject *ctx)
ctx 0 -1
int PyContext_Exit(PyObject *ctx)
ctx 0
-1
:
PyObject *PyContextVar_New(const char *name, PyObject *def)
ContextVar name
def NULL NULL
int PyContextVar_Get(PyObject *var, PyObject *default_value, PyObject **value)
’ ’ -1 ’ ’
’’0’’
value value

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

int PyDate_Check(PyObject *ob)


ob PyDateTime_DateType PyDateTime_DateType
ob NULL
int PyDate_CheckExact(PyObject *ob)
ob PyDateTime_DateType ob NULL
int PyDateTime_Check(PyObject *ob)
ob PyDateTime_DateTimeType PyDateTime_DateTimeType
ob NULL
int PyDateTime_CheckExact(PyObject *ob)
ob PyDateTime_DateTimeType ob NULL

int PyTime_Check(PyObject *ob)


ob PyDateTime_TimeType PyDateTime_TimeType
ob NULL
int PyTime_CheckExact(PyObject *ob)
ob PyDateTime_TimeType ob NULL
int PyDelta_Check(PyObject *ob)
ob PyDateTime_DeltaType PyDateTime_DeltaType
ob NULL
int PyDelta_CheckExact(PyObject *ob)
ob PyDateTime_DeltaType ob NULL
int PyTZInfo_Check(PyObject *ob)
ob PyDateTime_TZInfoType PyDateTime_TZInfoType
ob NULL
int PyTZInfo_CheckExact(PyObject *ob)
ob PyDateTime_TZInfoType ob NULL

PyObject *PyDate_FromDate(int year, int month, int day)


datetime.date
PyObject *PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int
usecond)
year, month, day, hour, minute, second microsecond
datetime.datetime
PyObject *PyDateTime_FromDateAndTimeAndFold(int year, int month, int day, int hour, int minute, int
second, int usecond, int fold)
year, month, day, hour, minute, second, microsecond fold
datetime.datetime
3.6 .
PyObject *PyTime_FromTime(int hour, int minute, int second, int usecond)
hour, minute, second and microsecond datetime.time

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

PyObject *PyDelta_FromDSU(int days, int seconds, int useconds)


datetime.timedelta
datetime.timedelta
PyObject *PyTimeZone_FromOffset(PyObject *offset)
datetime.timezone offset

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)

int PyDateTime_GET_MONTH(PyDateTime_Date *o)


0 12
int PyDateTime_GET_DAY(PyDateTime_Date *o)
0 31
PyDateTime_DateTime
NULL :
int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o)
0 23
int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o)
0 59
int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o)
0 59
int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o)
0 999999
int PyDateTime_DATE_GET_FOLD(PyDateTime_DateTime *o)
0 1
3.6 .
PyObject *PyDateTime_DATE_GET_TZINFO(PyDateTime_DateTime *o)
tzinfo ( None)
3.10 .
PyDateTime_Time
NULL :
int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o)
0 23
int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o)
0 59
int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o)
0 59

174 Chapter 8.
The Python/C API, 3.12.1

int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o)


0 999999
int PyDateTime_TIME_GET_FOLD(PyDateTime_Time *o)
0 1
3.6 .
PyObject *PyDateTime_TIME_GET_TZINFO(PyDateTime_Time *o)
tzinfo ( None)
3.10 .
PyDateTime_Delta
NULL :
int PyDateTime_DELTA_GET_DAYS(PyDateTime_Delta *o)
-999999999 999999999
3.3 .
int PyDateTime_DELTA_GET_SECONDS(PyDateTime_Delta *o)
0 86399
3.3 .
int PyDateTime_DELTA_GET_MICROSECONDS(PyDateTime_Delta *o)
0 999999
3.3 .
DB API :
PyObject *PyDateTime_FromTimestamp(PyObject *args)
datetime.datetime
datetime.datetime.fromtimestamp()
PyObject *PyDate_FromTimestamp(PyObject *args)
datetime.date
datetime.date.fromtimestamp()

8.6.14

-- GenericAlias Union GenericAlias


C
PyObject *Py_GenericAlias(PyObject *origin, PyObject *args)
ABI 3.9 . GenericAlias Python types.
GenericAlias origin args GenericAlias __origin__ __args__
origin PyTypeObject* args PyTupleObject* PyObject*
args __args__ (args,)
origin GenericAlias
__parameters__ __args__ NULL
:

...
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 Py_Initialize() Python/C API

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

bytes bytearray str bytes int 2

-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

PYTHON* PYTHONPATH PYTHONHOME


-E -I
3.12 .
int Py_InspectFlag
API PyConfig.inspect Python
-c
sys.stdin
-i PYTHONINSPECT
3.12 .
int Py_InteractiveFlag
API PyConfig.interactive 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

io.FileIO io._WindowsConsoleIO sys


PYTHONLEGACYWINDOWSSTDIO 1
PEP 528
: Windows
3.12 .
int Py_NoSiteFlag
API PyConfig.site_import Python
site sys.path site
( site.main())
-S
3.12 .
int Py_NoUserSiteDirectory
API PyConfig.user_site_directory 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

: Windows O_TEXT O_BINARY C


Python

void Py_InitializeEx(int initsigs)


ABI. initsigs 1 Py_Initialize() initsigs 0
Python
Py_InitializeFromConfig() Python
int Py_IsInitialized()
ABI. Python
Py_FinalizeEx() Py_Initialize()
int Py_FinalizeEx()
ABI 3.6 . Py_Initialize() Python/C
API Py_Initialize()
Py_NewInterpreter() ) Python
Py_Initialize()
0 -1
Python
DLL Python DLL
Python
Python
:
__del__() Python
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

int Py_SetStandardStreamEncoding(const char *encoding, const char *errors)


API PyConfig.stdio_encoding PyConfig.
stdio_errors Python
Py_Initialize() IO
str.encode()
PYTHONIOENCODING IO

encoding / errors NULL PYTHONIOENCODING /


sys.stderr ”backslashreplace”

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

const char *Py_GetVersion()


ABI. Return the version of this Python interpreter. This is a string that looks something like

"3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"

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

const char *Py_GetCompiler()


ABI. Python :

"[GCC 2.7.2.2]"

Python sys.version

const char *Py_GetBuildInfo()


ABI. Python

"#67, Aug 1 1997, 22:34:28"

Python sys.version

void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)


ABI. This API is kept for backward compatibility: setting PyConfig.argv, PyConfig.
parse_argv and PyConfig.safe_path should be used instead, see Python Initialization Configura-
tion.
Set sys.argv based on argc and argv. These parameters are similar to those passed to the program’s
main() function with the difference that the first entry should refer to the script file to be executed rather
than the executable hosting the Python interpreter. If there isn’t a script that will be run, the first entry in
argv can be an empty string. If this function fails to initialize sys.argv, a fatal condition is signalled using
Py_FatalError().
If updatepath is zero, this is all the function does. If updatepath is non-zero, the function also modifies sys.
path according to the following algorithm:
• If the name of an existing script is passed in argv[0], the absolute path of the directory where the
script is located is prepended to sys.path.
• Otherwise (that is, if argc is 0 or argv[0] doesn’t point to an existing file name), an empty string is
prepended to sys.path, which is the same as prepending the current working directory (".").
Use Py_DecodeLocale() to decode a bytes string to get a wchar_* string.

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:

PyRun_SimpleString("import sys; sys.path.pop(0)\n");

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

Save the thread state in a local variable.


Release the global interpreter lock.
... Do some blocking I/O operation ...
Reacquire the global interpreter lock.
Restore the thread state from the local variable.

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();

/* Perform Python actions here. */


result = CallSomeFunction();
/* evaluate result or handle exception */

/* Release the thread. No Python API allowed beyond this point. */


PyGILState_Release(gstate);

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.

9.5.3 Cautions about fork()

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

PyThreadState *PyThreadState_Swap(PyThreadState *tstate)


ABI. Swap the current thread state with the thread state given by the argument tstate, which may be
NULL. The global interpreter lock must be held and is not released.
The following functions use thread-local storage, and are not compatible with sub-interpreters:
PyGILState_STATE PyGILState_Ensure()
ABI. Ensure that the current thread is ready to call the Python C API regardless of the current
state of Python, or of the global interpreter lock. This may be called as many times as desired by a thread
as long as each call is matched with a call to PyGILState_Release(). In general, other thread-related
APIs may be used between PyGILState_Ensure() and PyGILState_Release() calls as long as
the thread state is restored to its previous state before the Release(). For example, normal usage of the
Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros is acceptable.
The return value is an opaque ”handle” to the thread state when PyGILState_Ensure() was called, and
must be passed to PyGILState_Release() to ensure Python is left in the same state. Even though
recursive calls are allowed, these handles cannot be shared - each unique call to PyGILState_Ensure()
must save the handle for its call to PyGILState_Release().
When the function returns, the current thread will hold the GIL and be able to call arbitrary Python code.
Failure is a fatal error.

: 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

All of the following functions must be called after Py_Initialize().


3.7 : Py_Initialize() now initializes the GIL.
PyInterpreterState *PyInterpreterState_New()
ABI. Create a new interpreter state object. The global interpreter lock need not be held, but may
be held if it is necessary to serialize calls to this function.
Raises an auditing event cpython.PyInterpreterState_New with no arguments.
void PyInterpreterState_Clear(PyInterpreterState *interp)
ABI. Reset all information in an interpreter state object. The global interpreter lock must be held.
Raises an auditing event cpython.PyInterpreterState_Clear with no arguments.
void PyInterpreterState_Delete(PyInterpreterState *interp)
ABI. Destroy an interpreter state object. The global interpreter lock need not be held. The interpreter
state must have been reset with a previous call to PyInterpreterState_Clear().
PyThreadState *PyThreadState_New(PyInterpreterState *interp)
ABI.

void PyThreadState_Clear(PyThreadState *tstate)


ABI. Reset all information in a thread state object. The global interpreter lock must be held.
3.9 : This function now calls the PyThreadState.on_delete callback. Previously, that
happened in PyThreadState_Delete().
void PyThreadState_Delete(PyThreadState *tstate)
ABI. Destroy a thread state object. The global interpreter lock need not be held. The thread state
must have been reset with a previous call to PyThreadState_Clear().
void PyThreadState_DeleteCurrent(void)
Destroy the current thread state and release the global interpreter lock. Like PyThreadState_Delete(),
the global interpreter lock need not be held. The thread state must have been reset with a previous call to
PyThreadState_Clear().
PyFrameObject *PyThreadState_GetFrame(PyThreadState *tstate)
ABI 3.10 . Get the current frame of the Python thread state tstate.
Return a strong reference. Return NULL if no frame is currently executing.
See also PyEval_GetFrame().
tstate must not be NULL.
3.9 .
uint64_t PyThreadState_GetID(PyThreadState *tstate)
ABI 3.10 . Get the unique thread state identifier of the Python thread state tstate.
tstate must not be NULL.
3.9 .

190 Chapter 9.
The Python/C API, 3.12.1

PyInterpreterState *PyThreadState_GetInterpreter(PyThreadState *tstate)


ABI 3.10 . Get the interpreter of the Python thread state tstate.
tstate must not be NULL.
3.9 .
void PyThreadState_EnterTracing(PyThreadState *tstate)
Suspend tracing and profiling in the Python thread state tstate.
Resume them using the PyThreadState_LeaveTracing() function.
3.11 .
void PyThreadState_LeaveTracing(PyThreadState *tstate)
Resume tracing and profiling in the Python thread state tstate suspended by the
PyThreadState_EnterTracing() function.
See also PyEval_SetTrace() and PyEval_SetProfile() functions.
3.11 .
PyInterpreterState *PyInterpreterState_Get(void)
ABI 3.9 .
Issue a fatal error if there no current Python thread state or no current interpreter. It cannot return NULL.
GIL
3.9 .
int64_t PyInterpreterState_GetID(PyInterpreterState *interp)
ABI 3.7 . Return the interpreter’s unique ID. If there was any error in doing so then -1
is returned and an error is set.
GIL
3.7 .
PyObject *PyInterpreterState_GetDict(PyInterpreterState *interp)
ABI 3.8 . Return a dictionary in which interpreter-specific data may be stored. If this
function returns NULL then no exception has been raised and the caller should assume no interpreter-specific
dict is available.
This is not a replacement for PyModule_GetState(), which extensions should use to store interpreter-
specific state information.
3.8 .
typedef PyObject *(*_PyFrameEvalFunction)(PyThreadState *tstate, _PyInterpreterFrame *frame, int
throwflag)

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

void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunction


eval_frame)
Set the frame evaluation function.
See the PEP 523 ”Adding a frame evaluation API to CPython”.
3.9 .
PyObject *PyThreadState_GetDict()
ABI. Return a dictionary in which extensions can store thread-specific state
information. Each extension should use a unique key to use to store state in the dictionary. It is okay to call
this function when no current thread state is available. If this function returns NULL, no exception has been
raised and the caller should assume no current thread state is available.
int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
ABI. Asynchronously raise an exception in a thread. The id argument is the thread id of the target
thread; exc is the exception object to be raised. This function does not steal any references to exc. To prevent
naive misuse, you must write your own C extension to call this. Must be called with the GIL held. Returns the
number of thread states modified; this is normally one, but will be zero if the thread id isn’t found. If exc is
NULL, the pending exception (if any) for the thread is cleared. This raises no exceptions.
3.7 : The type of the id parameter changed from long to unsigned long.
void PyEval_AcquireThread(PyThreadState *tstate)
ABI. Acquire the global interpreter lock and set the current thread state to tstate, which must not be
NULL. The lock must have been created earlier. If this thread already has the lock, 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.

3.8 : Updated to be consistent with PyEval_RestoreThread(),


Py_END_ALLOW_THREADS(), and PyGILState_Ensure(), and terminate the current thread
if called while the interpreter is finalizing.
PyEval_RestoreThread() is a higher-level function which is always available (even when threads have
not been initialized).
void PyEval_ReleaseThread(PyThreadState *tstate)
ABI. Reset the current thread state to NULL and release the global interpreter lock. The lock must
have been created earlier and must be held by the current thread. The tstate argument, which must not be
NULL, is only used to check that it represents the current thread state --- if it isn’t, a fatal error is reported.
PyEval_SaveThread() is a higher-level function which is always available (even when threads have not
been initialized).
void PyEval_AcquireLock()
ABI.
3.2 : This function does not update the current thread state. Please use
PyEval_RestoreThread() or PyEval_AcquireThread() instead.

: 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

3.8 : Updated to be consistent with PyEval_RestoreThread(),


Py_END_ALLOW_THREADS(), and PyGILState_Ensure(), and terminate the current thread
if called while the interpreter is finalizing.
void PyEval_ReleaseLock()
ABI. Release the global interpreter lock. The lock must have been created earlier.
3.2 : This function does not update the current thread state. Please use
PyEval_SaveThread() or PyEval_ReleaseThread() instead.

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

• For modules using multi-phase initialization, e.g. PyModule_FromDefAndSpec(), a separate


module object is created and initialized for each interpreter. Only C-level static and global variables
are shared between these module objects.
• For modules using single-phase initialization, e.g. PyModule_Create(), the first time a particular
extension is imported, it is initialized normally, and a (shallow) copy of its module’s dictionary is squir-
reled away. When the same extension is imported by another (sub-)interpreter, a new module is initialized
and filled with the contents of this copy; the extension’s init function is not called. Objects in the mod-
ule’s dictionary thus end up shared across (sub-)interpreters, which might cause unwanted behavior (see
Bugs and caveats below).
Note that this is different from what happens when an extension is imported after the interpreter has been
completely re-initialized by calling Py_FinalizeEx() and Py_Initialize(); in that case, the
extension’s initmodule function is called again. As with multi-phase initialization, this means that
only C-level static and global variables are shared between these modules.
PyThreadState *Py_NewInterpreter(void)
ABI. Create a new sub-interpreter. This is essentially just a wrapper around
Py_NewInterpreterFromConfig() with a config that preserves the existing behavior. The re-
sult is an unisolated sub-interpreter that shares the main interpreter’s GIL, allows fork/exec, allows daemon
threads, and allows single-phase init modules.
void Py_EndInterpreter(PyThreadState *tstate)
ABI. Destroy the (sub-)interpreter represented by the given thread state. The given thread state
must be the current thread state. See the discussion of thread states below. When the call returns, the current
thread state is NULL. All thread states associated with this interpreter are destroyed. The global interpreter
lock used by the target interpreter must be held before calling this function. No GIL is held when it returns.
Py_FinalizeEx() will destroy all sub-interpreters that haven’t been explicitly destroyed at that point.

9.6.1 A Per-Interpreter GIL

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

void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)


Set the profiler function to func. The obj parameter is passed to the function as its first parameter, and may
be any Python object, or NULL. If the profile function needs to maintain state, using a different value for obj
for each thread provides a convenient and thread-safe place to store it. The profile function is called for all
monitored events except PyTrace_LINE PyTrace_OPCODE and PyTrace_EXCEPTION.
See also the sys.setprofile() function.
The caller must hold the GIL.
void PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *obj)
Like PyEval_SetProfile() but sets the profile function in all running threads belonging to the current
interpreter instead of the setting it only on the current thread.
The caller must hold the GIL.
As PyEval_SetProfile(), this function ignores any exceptions raised while setting the profile functions
in all threads.
3.12 .
void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
Set the tracing function to func. This is similar to PyEval_SetProfile(), except the tracing function
does receive line-number events and per-opcode events, but does not receive any event related to C func-
tion objects being called. Any trace function registered using PyEval_SetTrace() will not receive
PyTrace_C_CALL, PyTrace_C_EXCEPTION or PyTrace_C_RETURN as a value for the what pa-
rameter.
See also the sys.settrace() function.
The caller must hold the GIL.
void PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *obj)
Like PyEval_SetTrace() but sets the tracing function in all running threads belonging to the current
interpreter instead of the setting it only on the current thread.
The caller must hold the GIL.
As PyEval_SetTrace(), this function ignores any exceptions raised while setting the trace functions in
all threads.
3.12 .

9.9

These functions are only intended to be used by advanced debugging tools.


PyInterpreterState *PyInterpreterState_Head()
Return the interpreter state object at the head of the list of all such objects.
PyInterpreterState *PyInterpreterState_Main()

PyInterpreterState *PyInterpreterState_Next(PyInterpreterState *interp)


Return the next interpreter state object after interp from the list of all such objects.
PyThreadState *PyInterpreterState_ThreadHead(PyInterpreterState *interp)
Return the pointer to the first PyThreadState object in the list of threads associated with the interpreter
interp.
PyThreadState *PyThreadState_Next(PyThreadState *tstate)
Return the next thread state object after tstate from the list of all such objects belonging to the same
PyInterpreterState object.

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.

9.10.1 Thread Specific Storage (TSS) API

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.

9.10.2 Thread Local Storage (TLS) API

3.7 : This API is superseded by Thread Specific Storage (TSS) API.

: 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

• Python Python Python


Python
• Python Python
LC_CTYPE
Py_RunMain() Python
Initialization, Finalization, and Threads.
:
PEP 587 ”Python ”.

10.1

Python :

int main(int argc, char **argv)


{
PyStatus status;

PyConfig config;
PyConfig_InitPythonConfig(&config);
config.isolated = 1;

/* Decode command line arguments.


Implicitly preinitialize Python (in isolated mode). */
status = PyConfig_SetBytesArgv(&config, argc, argv);
if (PyStatus_Exception(status)) {
goto exception;
}
( )

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

PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)


item list
Python
PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item)
item list index
index list item list
index 0
Python
:
Py_ssize_t length
List
wchar_t **items

202 Chapter 10. Python


The Python/C API, 3.12.1

10.3 PyStatus

type PyStatus

C
:
int exitcode
exit()
const char *err_msg

const char *func


NULL
:
PyStatus PyStatus_Ok(void)

PyStatus PyStatus_Error(const char *err_msg)

err_msg NULL
PyStatus PyStatus_NoMemory(void)

PyStatus PyStatus_Exit(int exitcode)


Python
:
int PyStatus_Exception(PyStatus status)

Py_ExitStatusException()
int PyStatus_IsError(PyStatus status)

int PyStatus_IsExit(PyStatus status)

void Py_ExitStatusException(PyStatus status)


status exit(exitcode) status
PyStatus_Exception(status)

: Python PyStatus.func func NULL

PyStatus alloc(void **ptr, size_t size)


{
*ptr = PyMem_RawMalloc(size);
if (*ptr == NULL) {
return PyStatus_NoMemory();
}
( )

10.3. PyStatus 203


The Python/C API, 3.12.1

( )
return PyStatus_Ok();
}

int main(int argc, char **argv)


{
void *ptr;
PyStatus status = alloc(&ptr, 16);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
PyMem_Free(ptr);
return 0;
}

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

204 Chapter 10. Python


The Python/C API, 3.12.1

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

10.4. PyPreConfig 205


The Python/C API, 3.12.1

10.5 PyPreConfig Python

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()

Python (PyPreConfig_InitPythonConfig()) Python


Python -X
utf8 Python UTF-8
PyMem_SetAllocator() Py_PreInitialize() Py_InitializeFromConfig()
PyPreConfig.allocator
PYMEM_ALLOCATOR_NOT_SET Py_PreInitialize()
PyMem_RawMalloc() Python Python
malloc() free() Py_DecodeLocale() Python
Python UTF-8 :

PyStatus status;
PyPreConfig preconfig;
PyPreConfig_InitPythonConfig(&preconfig);

preconfig.utf8_mode = 1;

status = Py_PreInitialize(&preconfig);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}

/* at this point, Python speaks UTF-8 */

Py_Initialize();
/* ... use Python API here ... */
Py_Finalize();

206 Chapter 10. Python


The Python/C API, 3.12.1

10.6 PyConfig

type PyConfig
Python
PyConfig_Clear()
:
void PyConfig_InitPythonConfig(PyConfig *config)
Python
void PyConfig_InitIsolatedConfig(PyConfig *config)

PyStatus PyConfig_SetString(PyConfig *config, wchar_t *const *config_str, const wchar_t *str)


str *config_str
Python
PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t *const *config_str, const char *str)
Py_DecodeLocale() str *config_str
Python
PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t *const *argv)
argv (config argv )
Python
PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char *const *argv)
argv (config argv ) Py_DecodeLocale()

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 Python Python


(PyPreConfig) PyConfig PyPreConfig
PyConfig

10.6. PyConfig 207


The Python/C API, 3.12.1

• 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)

• (python -c code python)

-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

208 Chapter 10. Python


The Python/C API, 3.12.1

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

10.6. PyConfig 209


The Python/C API, 3.12.1

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"

210 Chapter 10. Python


The Python/C API, 3.12.1

• "surrogatepass" ( UTF-8 )
filesystem_encoding
unsigned long hash_seed

int use_hash_seed

use_hash_seed Python hash_seed


PYTHONHASHSEED
use_hash_seed Python -1 0
wchar_t *home
Python
Py_SetPythonHome() NULL
PYTHONHOME
: NULL.
Python
int import_time

-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 .

10.6. PyConfig 211


The Python/C API, 3.12.1

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

212 Chapter 10. Python


The Python/C API, 3.12.1

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

• 0: Peephole __debug__ True


• 1: 0 __debug__ False
• 2: 1
-O PYTHONOPTIMIZE
: 0.
PyWideStringList orig_argv
Python : sys.orig_argv
orig_argv argv PyConfig_Read()
argv argv orig_argv ( parse_argv )
argv Py_GetArgcArgv()

3.10 .
int parse_argv

1 Python argv argv


Python
PyConfig_Read() PyConfig.argv PyConfig.
parse_argv 2 Python PyConfig.argv
Python
Python 1 0
3.10 : PyConfig.parse_argv 1 PyConfig.argv

int parser_debug
0
-d PYTHONDEBUG
Python ( Py_DEBUG )
: 0.
int pathconfig_warnings
stderr 0

Python 1 0
Python
3.11 : Windows

10.6. PyConfig 213


The Python/C API, 3.12.1

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()

python3 script.py arg script.py


PyConfig.skip_source_first_line
: NULL.
wchar_t *run_module
-m
Py_RunMain()
: NULL.
int show_ref_count

-X showrefcount 1
Python ( Py_REF_DEBUG )

214 Chapter 10. Python


The Python/C API, 3.12.1

: 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 .

10.6. PyConfig 215


The Python/C API, 3.12.1

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

parse_argv argv Python


argv Python
xoptions -X
3.9 : show_alloc_count

216 Chapter 10. Python


The Python/C API, 3.12.1

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);

/* Set the program name. Implicitly preinitialize Python. */


status = PyConfig_SetString(&config, &config.program_name,
L"/path/to/my_program");
if (PyStatus_Exception(status)) {
goto exception;
}

status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto exception;
}
PyConfig_Clear(&config);
return;

exception:
PyConfig_Clear(&config);
Py_ExitStatusException(status);
}

3.11

PyStatus init_python(const char *program_name)


{
PyStatus status;

PyConfig config;
PyConfig_InitPythonConfig(&config);

/* Set the program name before reading the configuration


(decode byte string from the locale encoding).

Implicitly preinitialize Python. */


status = PyConfig_SetBytesString(&config, &config.program_name,
program_name);
( )

10.7. PyConfig 217


The Python/C API, 3.12.1

( )
if (PyStatus_Exception(status)) {
goto done;
}

/* Read all configuration at once */


status = PyConfig_Read(&config);
if (PyStatus_Exception(status)) {
goto done;
}

/* Specify sys.path explicitly */


/* If you want to modify the default set of paths, finish
initialization first and then use PySys_GetObject("path") */
config.module_search_paths_set = 1;
status = PyWideStringList_Append(&config.module_search_paths,
L"/path/to/stdlib");
if (PyStatus_Exception(status)) {
goto done;
}
status = PyWideStringList_Append(&config.module_search_paths,
L"/path/to/more/modules");
if (PyStatus_Exception(status)) {
goto done;
}

/* Override executable computed by PyConfig_Read() */


status = PyConfig_SetString(&config, &config.executable,
L"/path/to/my_executable");
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

218 Chapter 10. Python


The Python/C API, 3.12.1

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

base_prefix base_exec_prefix prefix exec_prefix

Py_RunMain() Py_Main() sys.path:

10.9. Python 219


The Python/C API, 3.12.1

• run_filename __main__.py run_filename


sys.path
• isolated
– run_module sys.path

– 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()

void Py_GetArgcArgv(int *argc, wchar_t ***argv)


Python
PyConfig.orig_argv

220 Chapter 10. Python


The Python/C API, 3.12.1

10.13 API

API PEP 432


• Python



– sys : sys.path
• ” ” Python
– importlib


– sys ( sys.stdout sys.path)
– faulthandler tracemalloc
– site
– .
API
• PyConfig._init_main: 0 Py_InitializeFromConfig()

PyStatus _Py_InitializeMain(void)
Python
importlib :
Python Python sys.meta_path

Python PEP 432


API
API API
Python :

void init_python(void)
{
PyStatus status;

PyConfig config;
PyConfig_InitPythonConfig(&config);
config._init_main = 0;

/* ... customize 'config' configuration ... */

status = Py_InitializeFromConfig(&config);
PyConfig_Clear(&config);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}

/* Use sys.stderr because sys.stdout is only created


by _Py_InitializeMain() */
int res = PyRun_SimpleString(
( )

10.13. API 221


The Python/C API, 3.12.1

( )
"import sys; "
"print('Run Python code before _Py_InitializeMain', "
"file=sys.stderr)");
if (res < 0) {
exit(1);
}

/* ... put more configuration code here ... */

status = _Py_InitializeMain();
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
}

222 Chapter 10. Python


CHAPTER 11

11.1

Python Python heap


Python Python memory manager Python

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

PyMem_RawMalloc() Python PyObject_Malloc()

• * *
GIL
• ”Mem” Python GIL
Python
• Python Python
PyMem_Free()
PyMem_Malloc()

11.3

: malloc(), calloc(), realloc() free()


malloc(1) ( calloc(1, 1))
3.4 .
void *PyMem_RawMalloc(size_t n)
n void* NULL
NULL PyMem_RawMalloc(1)

void *PyMem_RawCalloc(size_t nelem, size_t elsize)


nelem elsize void*
NULL
NULL PyMem_RawCalloc(1, 1)
3.5 .
void *PyMem_RawRealloc(void *p, size_t n)
p n
p NULL PyMem_RawMalloc(n) n 0
NULL

224 Chapter 11.


The Python/C API, 3.12.1

p NULL PyMem_RawMalloc() PyMem_RawRealloc()


PyMem_RawCalloc()
PyMem_RawRealloc() NULL p
void PyMem_RawFree(void *p)
p p PyMem_RawMalloc() PyMem_RawRealloc()
PyMem_RawCalloc() PyMem_RawFree(p)

p NULL,

11.4

ANSI C Python
pymalloc .

: GIL

3.6 : pymalloc malloc()


void *PyMem_Malloc(size_t n)
ABI. n void*
NULL
NULL PyMem_Malloc(1)

void *PyMem_Calloc(size_t nelem, size_t elsize)


ABI 3.7 . nelem elsize
void* NULL
NULL PyMem_Calloc(1, 1)
3.5 .
void *PyMem_Realloc(void *p, size_t n)
ABI. p n

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)

void *PyObject_Calloc(size_t nelem, size_t elsize)


ABI 3.7 . nelem elsize
void* NULL
NULL PyObject_Calloc(1, 1)
3.5 .
void *PyObject_Realloc(void *p, size_t n)
ABI. p n

*p* NULL PyObject_Malloc(n) n 0


NULL
p NULL PyObject_Malloc() PyObject_Realloc()
PyObject_Calloc()
PyObject_Realloc() NULL p

226 Chapter 11.


The Python/C API, 3.12.1

void PyObject_Free(void *p)


ABI. p p PyObject_Malloc()
PyObject_Realloc() PyObject_Calloc()
PyObject_Free(p)
p NULL,

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

pymalloc "malloc_debug" malloc + debug malloc + debug malloc + debug

• PYTHONMALLOC
• malloc C C malloc() calloc() realloc() free()
• pymalloc pymalloc .
• ”+ debug”: Python .
• Python

11.7

3.4 .
type PyMemAllocatorEx
:

void *ctx

void* malloc(void *ctx, size_t size)


void* calloc(void *ctx, size_t nelem, size_t 0
elsize)
void* realloc(void *ctx, void *ptr, size_t
new_size)
void free(void *ctx, void *ptr)

3.5 : PyMemAllocator PyMemAllocatorEx calloc

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)

void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)

NULL
PYMEM_DOMAIN_RAW GIL
GIL
PyMem_SetupDebugHooks()

PyPreConfig.allocator Preinitialize Python with PyPreConfig

: PyMem_SetAllocator() :
• Py_PreInitialize() Py_InitializeFromConfig()

Raw Domain GIL

• Python Py_InitializeFromConfig()
must

3.12 :
void PyMem_SetupDebugHooks(void)
Python

228 Chapter 11.


The Python/C API, 3.12.1

11.8 Python

Python PyMem_SetupDebugHooks() Python


Python
PYTHONMALLOC Python
PYTHONMALLOC=debug
PyMem_SetupDebugHooks() PyMem_SetAllocator()
0xCD
PYMEM_CLEANBYTE 0xDD PYMEM_DEADBYTE
0xFD PYMEM_FORBIDDENBYTE
ASCII

• API PyMem_Malloc() PyObject_Free()




• PYMEM_DOMAIN_OBJ ( : PyObject_Malloc()) PYMEM_DOMAIN_MEM ( :
PyMem_Malloc()) GIL
tracemalloc tracemalloc
Python
S = sizeof(size_t) 2*S N
p malloc realloc (p[i:j] *(p+i)
*(p+j) Python :
p[-2*S:-S] size_t
p[-S] API ASCII :
• 'r' PYMEM_DOMAIN_RAW
• 'm' PYMEM_DOMAIN_MEM
• 'o' PYMEM_DOMAIN_OBJ
p[-S+1:0] PYMEM_FORBIDDENBYTE
p[0:N] PYMEM_CLEANBYTE
realloc PYMEM_CLEANBYTE
free PYMEM_DEADBYTE
realloc PYMEM_DEADBYTE

p[N:N+S] PYMEM_FORBIDDENBYTE
p[N+S:N+2*S] PYMEM_DEBUG_SERIALNO
malloc realloc 1 size_t

obmalloc.c bumpserialno()

realloc free PYMEM_FORBIDDENBYTE


stderr Py_FatalError()

PYMEM_DEADBYTE ( )
PYMEM_CLEANBYTE ( )

11.8. Python 229


The Python/C API, 3.12.1

3.6 : PyMem_SetupDebugHooks() Python


tracemalloc
PYMEM_DOMAIN_OBJ PYMEM_DOMAIN_MEM GIL
3.8 : 0xCB (PYMEM_CLEANBYTE) 0xDB (PYMEM_DEADBYTE) 0xFB
(PYMEM_FORBIDDENBYTE) 0xCD 0xDD 0xFD Windows CRT malloc()
free()

11.9 pymalloc

Python 512 pymalloc


arena 32 256 KiB 64 1 MiB
512 PyMem_RawMalloc() PyMem_RawRealloc()
pymalloc PYMEM_DOMAIN_MEM ( : PyMem_Malloc()) PYMEM_DOMAIN_OBJ ( :
PyObject_Malloc())
arena
• Windows VirtualAlloc() VirtualFree()
• mmap() munmap()
• malloc() free()
Python --without-pymalloc
PYTHONMALLOC` ``PYTHONMALLOC=malloc`

11.9.1 pymalloc Arena

3.4 .
type PyObjectArenaAllocator
arena

void *ctx

void* alloc(void *ctx, size_t size) size


void free(void *ctx, void *ptr, size_t
size)

void PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)


arena
void PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
arena

230 Chapter 11.


The Python/C API, 3.12.1

11.10 tracemalloc C API

3.7 .
int PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr, size_t size)
tracemalloc
0 -1 ( ) tracemalloc -2

int PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr)


tracemalloc
tracemalloc -2 0

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

char *buf1 = PyMem_New(char, BUFSIZ);


char *buf2 = (char *) malloc(BUFSIZ);
char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
...
PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
free(buf2); /* Right -- allocated via malloc() */
free(buf1); /* Fatal -- should be PyMem_Del() */

Python Python PyObject_New


PyObject_NewVar PyObject_Del()
C

11.10. tracemalloc C API 231


The Python/C API, 3.12.1

232 Chapter 11.


CHAPTER 12

12.1

PyObject *_PyObject_New(PyTypeObject *type)

PyVarObject *_PyObject_NewVar(PyTypeObject *type, Py_ssize_t size)

PyObject *PyObject_Init(PyObject *op, PyTypeObject *type)


ABI. op
type

PyVarObject *PyObject_InitVar(PyVarObject *op, PyTypeObject *type, Py_ssize_t size)


ABI. PyObject_Init()

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)

void PyObject_Del(void *op)


PyObject_New PyObject_NewVar
tp_dealloc
Python

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 .

234 Chapter 12.


The Python/C API, 3.12.1

int Py_IsFalse(PyObject *x)


ABI 3.10 . False Python x is False

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
:

PyObject *PyCFunction(PyObject *self,


PyObject *args);

12.2. 235
The Python/C API, 3.12.1

type PyCFunctionWithKeywords
ABI. C METH_VARARGS | METH_KEYWORDS Python
:

PyObject *PyCFunctionWithKeywords(PyObject *self,


PyObject *args,
PyObject *kwargs);

type _PyCFunctionFast
C METH_FASTCALL Python :

PyObject *_PyCFunctionFast(PyObject *self,


PyObject *const *args,
Py_ssize_t nargs);

type _PyCFunctionFastWithKeywords
C METH_FASTCALL | METH_KEYWORDS Python
:

PyObject *_PyCFunctionFastWithKeywords(PyObject *self,


PyObject *const *args,
Py_ssize_t nargs,
PyObject *kwnames);

type PyCMethod
C METH_METHOD | METH_FASTCALL | METH_KEYWORDS Python
:

PyObject *PyCMethod(PyObject *self,


PyTypeObject *defining_class,
PyObject *const *args,
Py_ssize_t nargs,
PyObject *kwnames)

3.9 .
type PyMethodDef
ABI ( ). :
const char *ml_name

PyCFunction ml_meth
C
int ml_flags

const char *ml_doc

ml_meth C PyObject*
PyCFunction PyCFunction
PyObject* self C
ml_flags
:
METH_VARARGS
PyCFunction PyObject*
self ( args)

236 Chapter 12.


The Python/C API, 3.12.1

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

const char *doc


PyDoc_STR

( 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 :

static PyMemberDef spam_type_members[] = {


{"__vectorcalloffset__", Py_T_PYSSIZET,
offsetof(Spam_object, vectorcall), Py_READONLY},
{NULL} /* Sentinel */
};

offsetof() #include <stddef.h>


tp_dictoffset tp_weaklistoffset "__dictoffset__"
"__weaklistoffset__"
Py_TPFLAGS_MANAGED_DICT Py_TPFLAGS_MANAGED_WEAKREF
3.12 : PyMemberDef "structmember.h"
PyObject *PyMember_GetOne(const char *obj_addr, struct PyMemberDef *m)
ABI. Get an attribute belonging to the object at address obj_addr
PyMemberDef m NULL
3.12 : PyMember_GetOne "structmember.
h"

238 Chapter 12.


The Python/C API, 3.12.1

int PyMember_SetOne(char *obj_addr, struct PyMemberDef *m, PyObject *o)


ABI. obj_addr o
PyMemberDef m 0
3.12 : PyMember_SetOne "structmember.
h"

PyMemberDef.flags:
Py_READONLY

Py_AUDIT_READ
object.__getattr__
Py_RELATIVE_OFFSET
PyMemberDef offset PyObject

basicsize Py_tp_members

PyTypeSlot tp_members Python


PyMemberDef.offset PyObject
3.10 : #include "structmember.h" RESTRICTED READ_RESTRICTED
WRITE_RESTRICTED READ_RESTRICTED RESTRICTED Py_AUDIT_READ
WRITE_RESTRICTED
3.12 : READONLY Py_READONLY PY_AUDIT_READ Py_
#include "structmember.h"

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

long long int


Py_T_LONGLONG

unsigned char int


Py_T_UBYTE

unsigned int int


Py_T_UINT

unsigned short int


Py_T_USHORT

unsigned long int


Py_T_ULONG

unsigned long long int


Py_T_ULONGLONG

Py_ssize_t int
Py_T_PYSSIZET

float float
Py_T_FLOAT

double float
Py_T_DOUBLE

char ( 0 1) bool
Py_T_BOOL

const char* (*) str (RO)


Py_T_STRING

const char[] (*) str (RO)


Py_T_STRING_INPLACE

char (0-127) str (**)


Py_T_CHAR

PyObject* object (D)


Py_T_OBJECT_EX

(*): UTF8 C Py_T_STRING C


Py_T_STRING_INPLACE

240 Chapter 12.


The Python/C API, 3.12.1

(**): 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):

typedef PyObject *(*getter)(PyObject *, void *);

NULL
set PyObject* ( ) ( closure):

typedef int (*setter)(PyObject *, PyObject *, void *);

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

242 Chapter 12.


The Python/C API, 3.12.1

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

nb_add binaryfunc __add__ __radd__


nb_inplace_add binaryfunc __iadd__
nb_subtract binaryfunc __sub__ __rsub__
nb_inplace_subtract binaryfunc __isub__
nb_multiply binaryfunc __mul__ __rmul__
nb_inplace_multiply binaryfunc __imul__
nb_remainder binaryfunc __mod__ __rmod__
nb_inplace_remainder binaryfunc __imod__
nb_divmod binaryfunc __divmod__
__rdivmod__
nb_power ternaryfunc __pow__ __rpow__
nb_inplace_power ternaryfunc __ipow__
nb_negative unaryfunc __neg__
nb_positive unaryfunc __pos__
nb_absolute unaryfunc __abs__
nb_bool inquiry __bool__
nb_invert unaryfunc __invert__
nb_lshift binaryfunc __lshift__ __rlshift__
nb_inplace_lshift binaryfunc __ilshift__

<>: NULL
[]:
<R> ( ) ( NULL)
2

”O”: PyBaseObject_Type
”T”: PyType_Type
”D”: ( NULL)

X - PyType_Ready sets this value if it is NULL


~ - PyType_Ready always sets this value (it should be NULL)
? - PyType_Ready may set this value depending on other slots

Also see the inheritance column ("I").


”I”:
X - type slot is inherited via *PyType_Ready* if defined with a *NULL* value
% - the slots of the sub-struct are inherited individually
G - inherited, but only in combination with other slots; see the slot's description
? - it's complicated; see the slot's description

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__

mp_length lenfunc __len__


mp_subscript binaryfunc __getitem__
mp_ass_subscript objobjargproc __setitem__,
__delitem__

sq_length lenfunc __len__


sq_concat binaryfunc __add__
sq_repeat ssizeargfunc __mul__
sq_item ssizeargfunc __getitem__
sq_ass_item ssizeobjargproc __setitem__
__delitem__
sq_contains objobjproc __contains__
sq_inplace_concat binaryfunc __iadd__
sq_inplace_repeat ssizeargfunc __imul__

bf_getbuffer getbufferproc()
bf_releasebuffer releasebufferproc()

244 Chapter 12.


The Python/C API, 3.12.1

typedef

typedef
allocfunc PyObject *
PyTypeObject *
Py_ssize_t

destructor PyObject * void


freefunc void * void
traverseproc int
PyObject *
visitproc
void *

newfunc PyObject *
PyObject *
PyObject *
PyObject *

initproc int
PyObject *
PyObject *
PyObject *

reprfunc PyObject * PyObject *


getattrfunc PyObject *
PyObject *
const char *

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

hashfunc PyObject * Py_hash_t


richcmpfunc PyObject *
The Python/C API, 3.12.1

Slot Type typedefs

12.3.2 PyTypeObject

PyTypeObject Include/object.h
:

typedef struct _typeobject {


PyObject_VAR_HEAD
const char *tp_name; /* For printing, in format "<module>.<name>" */
Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

/* Methods to implement standard operations */

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;

/* Method suites for standard classes */

PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;

/* More standard operations (here for binary compatibility) */

hashfunc tp_hash;
ternaryfunc tp_call;
reprfunc tp_str;
getattrofunc tp_getattro;
setattrofunc tp_setattro;

/* Functions to access object as input/output buffer */


PyBufferProcs *tp_as_buffer;

/* Flags to define presence of optional/expanded features */


unsigned long tp_flags;

const char *tp_doc; /* Documentation string */

/* Assigned meaning in release 2.0 */


/* call function for all accessible objects */
traverseproc tp_traverse;

/* delete references to contained objects */


inquiry tp_clear;

/* Assigned meaning in release 2.1 */


/* rich comparisons */
richcmpfunc tp_richcompare;

/* weak reference enabler */


Py_ssize_t tp_weaklistoffset;

/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
( )

246 Chapter 12.


The Python/C API, 3.12.1

( )

/* Attribute descriptor and subclassing stuff */


struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;
// Strong reference on a heap type, borrowed reference on a static type
struct _typeobject *tp_base;
PyObject *tp_dict;
descrgetfunc tp_descr_get;
descrsetfunc tp_descr_set;
Py_ssize_t tp_dictoffset;
initproc tp_init;
allocfunc tp_alloc;
newfunc tp_new;
freefunc tp_free; /* Low-level free-memory routine */
inquiry tp_is_gc; /* For PyObject_IS_GC */
PyObject *tp_bases;
PyObject *tp_mro; /* method resolution order */
PyObject *tp_cache;
PyObject *tp_subclasses;
PyObject *tp_weaklist;
destructor tp_del;

/* Type attribute cache version tag. Added in version 2.6 */


unsigned int tp_version_tag;

destructor tp_finalize;
vectorcallfunc tp_vectorcall;

/* bitset of which type-watchers care about this type */


unsigned char tp_watched;
} PyTypeObject;

12.3.3 PyObject

PyVarObject ob_size type_new()


class PyType_Type tp_itemsize
ob_size
Py_ssize_t PyObject.ob_refcnt
ABI. PyObject_HEAD_INIT 1
ob_type

PyTypeObject *PyObject.ob_type
ABI. PyObject_HEAD_INIT
&PyType_Type
Windows NULL
PyObject_HEAD_INIT

Foo_Type.ob_type = &PyType_Type;

PyType_Ready() ob_type NULL


ob_type PyType_Ready()

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

const char *PyTypeObject.tp_name


NUL

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

248 Chapter 12.


The Python/C API, 3.12.1

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

void tp_dealloc(PyObject *self);

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()

static void foo_dealloc(foo_object *self) {


PyObject_GC_UnTrack(self);
Py_CLEAR(self->ref);
Py_TYPE(self)->tp_free((PyObject *)self);
}

(Py_TPFLAGS_HEAPTYPE)
( Py_DECREF())

static void foo_dealloc(foo_object *self) {


PyTypeObject *tp = Py_TYPE(self);
// free references and buffers here
tp->tp_free(self);
Py_DECREF(tp);
}

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() :

250 Chapter 12.


The Python/C API, 3.12.1

PyObject *tp_repr(PyObject *self);

Unicode
eval()
'<' '>'

<%s object at %p> %s


%p
PyNumberMethods *PyTypeObject.tp_as_number

Number Object Structures

tp_as_number
PySequenceMethods *PyTypeObject.tp_as_sequence

Sequence Object Structures

tp_as_sequence
PyMappingMethods *PyTypeObject.tp_as_mapping

Mapping Object Structures

tp_as_mapping
hashfunc PyTypeObject.tp_hash
hash()
PyObject_Hash() :

Py_hash_t tp_hash(PyObject *);

-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

PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);

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():

PyObject *tp_str(PyObject *self);

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():

PyObject *tp_getattro(PyObject *self, PyObject *attr);

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.

PyBaseObject_Type uses PyObject_GenericGetAttr().


setattrofunc PyTypeObject.tp_setattro

The signature is the same as for PyObject_SetAttr():

int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);

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.

PyBaseObject_Type uses PyObject_GenericSetAttr().

252 Chapter 12.


The Python/C API, 3.12.1

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?

PyBaseObject_Type Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE


:
| OR tp_flags
PyType_HasFeature() tp f tp->tp_flags & f

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.

Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear


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.
Py_TPFLAGS_DEFAULT
This is a bitmask of all the bits that pertain to the existence of certain fields in the
type object and its extension structures. Currently, it includes the following bits:
Py_TPFLAGS_HAVE_STACKLESS_EXTENSION.

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 .

This flag is inherited unless the tp_dictoffset field is set in a superclass.


Py_TPFLAGS_MANAGED_WEAKREF
This bit indicates that instances of the class should be weakly referenceable.
3.12 .

This flag is inherited unless the tp_weaklistoffset field is set in a superclass.

254 Chapter 12.


The Python/C API, 3.12.1

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 .

This flag is inherited.


Py_TPFLAGS_LONG_SUBCLASS

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).

: ( abstract base class)


tp_new

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.

: Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE are mutually exclusive; it is an


error to enable both flags simultaneously.

This flag is inherited by types that do not already set Py_TPFLAGS_SEQUENCE.


:
PEP 634
3.10 .
Py_TPFLAGS_SEQUENCE
This bit indicates that instances of the class may match sequence patterns when used as the subject
of a match block. It is automatically set when registering or subclassing collections.abc.
Sequence, and unset when registering collections.abc.Mapping.

: Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE are mutually exclusive; it is an


error to enable both flags simultaneously.

This flag is inherited by types that do not already set Py_TPFLAGS_MAPPING.


:
PEP 634
3.10 .
Py_TPFLAGS_VALID_VERSION_TAG
Internal. Do not set or unset this flag. To indicate that a class has changed call PyType_Modified()

: 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

256 Chapter 12.


The Python/C API, 3.12.1

const char *PyTypeObject.tp_doc


An optional pointer to a NUL-terminated C string giving the docstring for this type object. This is exposed as
the __doc__ attribute on the type and instances of the type.

This field is not inherited by subtypes.


traverseproc PyTypeObject.tp_traverse
An optional pointer to a traversal function for the garbage collector. This is only used if the
Py_TPFLAGS_HAVE_GC flag bit is set. The signature is:

int tp_traverse(PyObject *self, visitproc visit, void *arg);

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.

Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear


This field is inherited by subtypes together with tp_clear and the Py_TPFLAGS_HAVE_GC flag bit: the
flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.

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:

int tp_clear(PyObject *);

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
.

Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear


This field is inherited by subtypes together with tp_traverse and the Py_TPFLAGS_HAVE_GC flag bit:
the flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the
subtype.
richcmpfunc PyTypeObject.tp_richcompare
An optional pointer to the rich comparison function, whose signature is:

PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);

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.

258 Chapter 12.


The Python/C API, 3.12.1

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

Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, op)


Return Py_True or Py_False from the function, depending on the result of a comparison. VAL_A
and VAL_B must be orderable by C comparison operators (for example, they may be C ints or floats).
The third argument specifies the requested operation, as for PyObject_RichCompare().
The returned value is a new strong reference.
On error, sets an exception and returns NULL from the function.
3.7 .

: 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.

PyBaseObject_Type provides a tp_richcompare implementation, which may be inherited. How-


ever, if only tp_hash is defined, not even the inherited function is used and instances of the type will not be
able to participate in any comparisons.
Py_ssize_t PyTypeObject.tp_weaklistoffset
While this field is still supported, Py_TPFLAGS_MANAGED_WEAKREF should be used instead, if at all
possible.
If the instances of this type are weakly referenceable, this field is greater than zero and contains the offset in
the instance structure of the weak reference list head (ignoring the GC header, if present); this offset is used
by PyObject_ClearWeakRefs() and the PyWeakref_* functions. The instance structure needs to
include a field of type PyObject* which is initialized to NULL.
Do not confuse this field with tp_weaklist; that is the list head for weak references to the type object itself.
It is an error to set both the Py_TPFLAGS_MANAGED_WEAKREF bit and tp_weaklist.

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.

If the Py_TPFLAGS_MANAGED_WEAKREF bit is set in the tp_dict field, then tp_weaklistoffset


will be set to a negative value, to indicate that it is unsafe to use this field.
getiterfunc PyTypeObject.tp_iter
iterator iterable
( )
This function has the same signature as PyObject_GetIter():

PyObject *tp_iter(PyObject *self);

iternextfunc PyTypeObject.tp_iternext
iterator :

PyObject *tp_iternext(PyObject *self);

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().

struct PyMethodDef *PyTypeObject.tp_methods


An optional pointer to a static NULL-terminated array of PyMethodDef structures, declaring regular meth-
ods of this type.
For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a
method descriptor.

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.

260 Chapter 12.


The Python/C API, 3.12.1

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 is not inherited by subtypes (obviously).

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).

If this field is NULL, PyType_Ready() will assign a new dictionary to it.

: 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.
:

PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);

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.
:

int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);

The value argument is set to NULL to delete the 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.
:

int tp_init(PyObject *self, PyObject *args, PyObject *kwds);

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.

262 Chapter 12.


The Python/C API, 3.12.1

allocfunc PyTypeObject.tp_alloc

PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);

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.
:

PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);

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:

void tp_free(void *self);

An initializer that is compatible with this signature is PyObject_Free().

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

For static subtypes, PyBaseObject_Type uses PyObject_Del().


inquiry PyTypeObject.tp_is_gc

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:

int tp_is_gc(PyObject *self);

(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.

264 Chapter 12.


The Python/C API, 3.12.1

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;

/* Save the current exception, if any. */


PyErr_Fetch(&error_type, &error_value, &error_traceback);

/* ... */

/* Restore the saved exception. */


PyErr_Restore(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.

3.9 : 3.8 3.9


unsigned char PyTypeObject.tp_watched
Internal. Do not use.
3.12 .

12.3.6 Static Types

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().

12.4 Number Object Structures

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;
( )

266 Chapter 12.


The Python/C API, 3.12.1

( )
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

12.4. Number Object Structures 267


The Python/C API, 3.12.1

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

268 Chapter 12.


The Python/C API, 3.12.1

12.5 Mapping Object Structures

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.

12.6 Sequence Object Structures

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()

12.5. Mapping Object Structures 269


The Python/C API, 3.12.1

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.

12.7 Buffer Object Structures

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:

int (PyObject *exporter, Py_buffer *view, int flags);

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:

void (PyObject *exporter, Py_buffer *view);

270 Chapter 12.


The Python/C API, 3.12.1

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.

12.8 Async Object Structures

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:

PyObject *am_await(PyObject *self);

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:

PyObject *am_aiter(PyObject *self);

Must return an asynchronous iterator object. See __anext__() for details.


This slot may be set to NULL if an object does not implement asynchronous iteration protocol.
unaryfunc PyAsyncMethods.am_anext
The signature of this function is:

PyObject *am_anext(PyObject *self);

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:

PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);

12.8. Async Object Structures 271


The Python/C API, 3.12.1

See PyIter_Send() for details. This slot may be set to NULL.


3.10 .

12.9 Slot Type typedefs

typedef PyObject *(*allocfunc)(PyTypeObject *cls, Py_ssize_t nitems)


ABI. The purpose of this function is to separate memory allocation from memory initialization.
It should return a pointer to a block of memory of adequate length for the instance, suitably aligned, and
initialized to zeros, but with ob_refcnt set to 1 and ob_type set to the type argument. If the type’s
tp_itemsize is non-zero, the object’s ob_size field should be initialized to nitems and the length of the al-
located memory block should be tp_basicsize + nitems*tp_itemsize, rounded up to a multiple
of sizeof(void*); otherwise, nitems is not used and the length of the block should be tp_basicsize.
This function should not do any other instance initialization, not even to allocate additional memory; that should
be done by tp_new.
typedef void (*destructor)(PyObject*)
ABI.
typedef void (*freefunc)(void*)
tp_free
typedef PyObject *(*newfunc)(PyObject*, PyObject*, PyObject*)
ABI. tp_new
typedef int (*initproc)(PyObject*, PyObject*, PyObject*)
ABI. tp_init
typedef PyObject *(*reprfunc)(PyObject*)
ABI. tp_repr
typedef PyObject *(*getattrfunc)(PyObject *self, char *attr)
ABI.
typedef int (*setattrfunc)(PyObject *self, char *attr, PyObject *value)
ABI. Set the value of the named attribute for the object. The value argument is set to NULL to
delete the attribute.
typedef PyObject *(*getattrofunc)(PyObject *self, PyObject *attr)
ABI.
tp_getattro
typedef int (*setattrofunc)(PyObject *self, PyObject *attr, PyObject *value)
ABI. Set the value of the named attribute for the object. The value argument is set to NULL to
delete the attribute.
tp_setattro
typedef PyObject *(*descrgetfunc)(PyObject*, PyObject*, PyObject*)
ABI. tp_descr_get
typedef int (*descrsetfunc)(PyObject*, PyObject*, PyObject*)
ABI. tp_descr_set
typedef Py_hash_t (*hashfunc)(PyObject*)
ABI. tp_hash
typedef PyObject *(*richcmpfunc)(PyObject*, PyObject*, int)
ABI. tp_richcompare

272 Chapter 12.


The Python/C API, 3.12.1

typedef PyObject *(*getiterfunc)(PyObject*)


ABI. tp_iter
typedef PyObject *(*iternextfunc)(PyObject*)
ABI. tp_iternext
typedef Py_ssize_t (*lenfunc)(PyObject*)
ABI.
typedef int (*getbufferproc)(PyObject*, Py_buffer*, int)
ABI 3.12 .
typedef void (*releasebufferproc)(PyObject*, Py_buffer*)
ABI 3.12 .
typedef PyObject *(*unaryfunc)(PyObject*)
ABI.
typedef PyObject *(*binaryfunc)(PyObject*, PyObject*)
ABI.
typedef PySendResult (*sendfunc)(PyObject*, PyObject*, PyObject**)
am_send
typedef PyObject *(*ternaryfunc)(PyObject*, PyObject*, PyObject*)
ABI.
typedef PyObject *(*ssizeargfunc)(PyObject*, Py_ssize_t)
ABI.
typedef int (*ssizeobjargproc)(PyObject*, Py_ssize_t, PyObject*)
ABI.
typedef int (*objobjproc)(PyObject*, PyObject*)
ABI.
typedef int (*objobjargproc)(PyObject*, PyObject*, PyObject*)
ABI.

12.10

Python
defining-new-types new-types-topics
:

typedef struct {
PyObject_HEAD
const char *data;
} MyObject;

static PyTypeObject MyObject_Type = {


PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "mymod.MyObject",
.tp_basicsize = sizeof(MyObject),
.tp_doc = PyDoc_STR("My objects"),
.tp_new = myobj_new,
.tp_dealloc = (destructor)myobj_dealloc,
.tp_repr = (reprfunc)myobj_repr,
};

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;

static PyTypeObject MyObject_Type = {


PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "mymod.MyObject",
.tp_basicsize = sizeof(MyObject),
.tp_doc = PyDoc_STR("My objects"),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_MANAGED_DICT |
Py_TPFLAGS_MANAGED_WEAKREF,
.tp_new = myobj_new,
.tp_traverse = (traverseproc)myobj_traverse,
.tp_clear = (inquiry)myobj_clear,
.tp_alloc = PyType_GenericNew,
.tp_dealloc = (destructor)myobj_dealloc,
( )

274 Chapter 12.


The Python/C API, 3.12.1

( )
.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;

static PyTypeObject MyStr_Type = {


PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "mymod.MyStr",
.tp_basicsize = sizeof(MyStr),
.tp_base = NULL, // set to &PyUnicode_Type in module init
.tp_doc = PyDoc_STR("my custom str"),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
.tp_repr = (reprfunc)myobj_repr,
};

typedef struct {
PyObject_HEAD
} MyObject;

static PyTypeObject MyObject_Type = {


PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "mymod.MyObject",
};

The simplest static type with variable-length instances:

typedef struct {
PyObject_VAR_HEAD
const char *data[1];
} MyObject;

static PyTypeObject MyObject_Type = {


PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "mymod.MyObject",
.tp_basicsize = sizeof(MyObject) - sizeof(char *),
.tp_itemsize = sizeof(char *),
};

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

PyObject_GC_New extra_size tp_basicsize


Python
Python

:
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

int PyObject_IS_GC(PyObject *obj)


0
0
int PyObject_GC_IsTracked(PyObject *op)
ABI 3.9 . op GC op
1 0
Python gc.is_tracked()
3.9 .

276 Chapter 12.


The Python/C API, 3.12.1

int PyObject_GC_IsFinalized(PyObject *op)


ABI 3.9 . op GC op
1 0
Python gc.is_finalized()
3.9 .
void PyObject_GC_Del(void *op)
ABI. PyObject_GC_New PyObject_GC_NewVar
void PyObject_GC_UnTrack(void *op)
ABI. op
PyObject_GC_Track() (tp_dealloc )
tp_traverse
3.8 : _PyObject_GC_TRACK() _PyObject_GC_UNTRACK() C API
tp_traverse
typedef int (*visitproc)(PyObject *object, void *arg)
ABI. tp_traverse object
tp_traverse arg Python

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;
}

tp_clear inquiry NULL


typedef int (*inquiry)(PyObject *self)
ABI.
Py_DECREF()

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

GC callback arg callback

3.12 .
typedef int (*gcvisitobjects_t)(PyObject *object, void *arg)
PyUnstable_GC_VisitObjects() arg
PyUnstable_GC_VisitObjects arg 0 1

3.12 .

278 Chapter 12.


CHAPTER 13

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

3.4.1a2 0x030401a2 3.10.0 0x030a00f0


#if PY_VERSION_HEX >= ...
Py_Version

279
The Python/C API, 3.12.1

const unsigned long Py_Version


ABI 3.11 . Python
PY_VERSION_HEX Python
3.11 .
Include/patchlevel.h

280 Chapter 13. API ABI


APPENDIX A

>>> Python
...
• Python

• Ellipsis
2to3 Python 2.x Python 3.x

2to3 lib2to3 Tools/scripts/2to3


2to3-reference
abstract base class -- ABC duck-typing
hasattr() ABC
isinstance() issubclass()
abc Python ABC collections.abc
numbers io importlib.abc
abc ABC
annotation --

__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

parameter PEP 362


asynchronous context manager -- __aenter__()
__aexit__() async with PEP 492
asynchronous generator -- asynchronous generator iterator async
def yield async for

await async for async with


asynchronous generator iterator -- asynchronous generator
asynchronous iterator __anext__()
yield
yield try
__anext__()
PEP 492 PEP 525
asynchronous iterable -- async for
__aiter__() asynchronous iterator PEP 492
asynchronous iterator -- __aiter__() __anext__()
__anext__() awaitable async for __anext__()
StopAsyncIteration PEP 492
attribute -- o
a o.a
identifiers
setattr() getattr()
awaitable -- await coroutine __await__()
PEP 492
BDFL Guido van Rossum Python
binary file -- file object ('rb',
'wb' 'rb+') sys.stdin.buffer sys.stdout.buffer io.BytesIO
gzip.GzipFile
text file str
borrowed reference -- Python C API

strong reference
borrowed reference Py_INCREF() strong reference
Py_NewRef() strong
reference
bytes-like object -- C-contiguous bytes
bytearray array.array memoryview

bytearray bytearray memoryview


(” ”) bytes bytes memoryview

282 Appendix A.
The Python/C API, 3.12.1

bytecode -- Python CPython Python


.pyc
” ” virtual machine
Python Python
dis
callable -- ( argument)
:

callable(argument1, argument2, argumentN)

function method __call__()

callback --
class --
class variable -- ( )
complex number --
-1 i j Python
j 3+1j math
cmath

context manager -- with __enter__() __exit__()


PEP 343
context variable --

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):
...

descriptor -- __get__(), __set__() __delete__()


a.b
a b b

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

extension module -- C C++ Python C API

f-string -- f- 'f' 'F' f-


PEP 498
file object -- API read() write()

/
: ,
io open()
file-like object -- file object
filesystem encoding and error handler -- Python
Unicode
128
API UnicodeError
sys.getfilesystemencoding() sys.getfilesystemencodeerrors()

filesystem encoding and error handler Python PyConfig_Read()


PyConfig filesystem_encoding filesystem_errors
locale encoding
finder -- loader
Python 3.3 : sys.meta_path path entry
finders sys.path_hooks

284 Appendix A.
The Python/C API, 3.12.1

PEP 302, PEP 420 PEP 451


floor division -- //
11 // 4 2 2.75 (-11)
// 4 -3 -2.75 PEP 238
function --
parameter, method function
function annotation -- annotation
int int :

def sum_two_numbers(a: int, b: int) -> int:


return a + b

function
variable annotation PEP 484 annotations-howto

__future__ future , from __future__ import <feature> Python


__future__ feature

>>> import __future__


>>> __future__.division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

garbage collection -- Python


gc
generator -- generator iterator yield
for- next()

generator iterator -- generator


yield try

generator expression --
for if
:

>>> sum(i*i for i in range(10)) # sum of squares 0, 1, 4, ... 81


285

generic function --

single dispatch functools.singledispatch() PEP 443


generic type -- type list dict
PEP 483 PEP 484 PEP 585 typing
GIL global interpreter lock
global interpreter lock -- CPython
Python bytecode dict
CPython

285
The Python/C API, 3.12.1

GIL I/O GIL

hash-based pyc -- pyc


pyc-invalidation
hashable -- __hash__()
__eq__()

Python
frozenset

id()
IDLE Python idle Python
immutable --

import path -- path based finder


sys.path
__path__
importing -- Python Python
importer -- finder loader
interactive -- Python
python
help(x)
interpreted -- Python

/
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__()

( list) iter() for

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()

keyword argument -- argument


lambda expression lambda
lambda [parameters]: expression
LBYL
EAFP if
LBYL
if key in mapping: return mapping[key] mapping
key EAFP
locale encoding -- Unix LC_CTYPE
locale.setlocale(locale.LC_CTYPE, new_locale)
Windows ANSI ( : "cp1252")
Android VxWorks Python "utf-8"
locale.getencoding()
filesystem encoding and error handler
list -- Python sequence
O(1)
list comprehension --
result = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0]
0 255 0x.. if
range(256)
loader -- load_module()
finder PEP 302 abstract base class importlib.abc.Loader
magic method -- special method
mapping -- collections.abc.Mapping collections.abc.
MutableMapping dict, collections.
defaultdict, collections.OrderedDict collections.Counter
meta path finder -- sys.meta_path finder path entry
finders
importlib.abc.MetaPathFinder
metaclass --
Python

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:

>>> sys.float_info[1] # indexed access


1024
>>> sys.float_info.max_exp # named field access
1024
>>> isinstance(sys.float_info, tuple) # kind of tuple
True

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

new-style class -- Python


Python __slots__
__getattribute__()
object -- object new-style class

package -- Python module __path__


Python
regular package namespace package
parameter -- function argument

288 Appendix A.
The Python/C API, 3.12.1

• positional-or-keyword
foo bar:

def func(foo, bar=None): ...

• positional-only
/ posonly1 posonly2:

def func(posonly1, posonly2, /, positional_or_keyword): ...

• keyword-only
*
kw_only1 kw_only2:

def func(arg, *, kw_only1, kw_only2): ...

• var-positional
* args:

def func(*args, **kwargs): ...

• var-keyword
** kwargs

argument inspect.Parameter function


PEP 362
path entry -- import path path based finder
path entry finder -- sys.path_hooks ( path entry hook)
finder path entry
importlib.abc.PathEntryFinder
path entry hook -- path entry
sys.path_hooks path entry finder
path based finder -- import path
path-like object -- str
bytes os.PathLike os.PathLike
os.fspath() str bytes os.
fsdecode() os.fsencode() str bytes
PEP 519
PEP Python PEP Python
Python PEP

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 :

for piece in food:


print(piece)

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:

>>> import email.mime.text


>>> email.mime.text.__name__
'email.mime.text'

reference count --
Python
CPython sys.getrefcount()

regular package -- package __init__.py


namespace package
__slots__

sequence -- iterable __getitem__()


__len__() list, str, tuple
bytes dict __getitem__() __len__()
immutable

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

Color = tuple[int, int, int]

def remove_gray_shades(colors: list[Color]) -> list[Color]:


pass

291
The Python/C API, 3.12.1

typing PEP 484


type hint -- annotation
Python
IDE
typing.get_type_hints()

typing PEP 484


universal newlines -- Unix
'\n' Windows '\r\n' Macintosh '\r' PEP 278 PEP
3116 bytes.splitlines()
variable annotation -- annotation
:

class C:
field: 'annotation'

int :

count: int = 0

annassign
function annotation, PEP 484 PEP 526 annotations-howto

virtual environment -- Python


Python Python
venv
virtual machine -- Python
bytecode
Zen of Python -- Python Python
”import this”

292 Appendix A.
APPENDIX B

Sphinx reStructuredText Sphinx Python

Python
reporting-bugs

• Fred L. Drake, Jr. Python


• reStructuredText Docutils Docutils
• Fredrik Lundh Alternative Python Reference Sphinx

B.1 Python

Python Python Python Python Misc/ACKS

Python Python

293
The Python/C API, 3.12.1

294 Appendix B.
APPENDIX C

C.1

Python CWI https://www.cwi.nl/ Guido van Rossum 1990


ABC Python Guido

1995 Guido CNRI https://www.cnri.reston.va.us/


Python
2000 Guido Python BeOpen.com BeOpen PythonLabs
PythonLabs Digital Creations ( Zope https://www.zope.org/) 2001 Python
(PSF https://www.python.org/psf/) Python
Zope Python
Python https://opensource.org/ Python
GPL

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

: GPL Python GPL GPL Python


GPL Python GPL

295
The Python/C API, 3.12.1

Guido

C.2 Python

Python PSF
Python 3.8.6 PSF BSD

Python

C.2.1 PYTHON 3.12.1 PSF

1. This LICENSE AGREEMENT is between the Python Software Foundation␣


,→("PSF"), and

the Individual or Organization ("Licensee") accessing and otherwise␣


,→using Python

3.12.1 software in source or binary form and its associated␣


,→documentation.

2. Subject to the terms and conditions of this License Agreement, PSF␣


,→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 3.12.1 alone or in any derivative


version, provided, however, that PSF's License Agreement and PSF's␣
,→notice of

copyright, i.e., "Copyright © 2001-2023 Python Software Foundation; All␣


,→Rights

Reserved" are retained in Python 3.12.1 alone or in any derivative␣


,→version

prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or


incorporates Python 3.12.1 or any part thereof, and wants to make the
derivative work available to others as provided herein, then Licensee␣
,→hereby

agrees to include in any such work a brief summary of the changes made␣
,→to Python

3.12.1.

4. PSF is making Python 3.12.1 available to Licensee on an "AS IS" basis.


PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY␣
,→OF

EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY␣


,→REPRESENTATION OR

WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR␣


,→THAT THE

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

MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.12.1, OR ANY␣


,→DERIVATIVE
THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material␣


,→breach of

its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any␣


,→relationship

of agency, partnership, or joint venture between PSF and Licensee. ␣


,→This License

Agreement does not grant permission to use PSF trademarks or trade name␣
,→in a

trademark sense to endorse or promote products or services of Licensee,␣


,→or any

third party.

8. By copying, installing or otherwise using Python 3.12.1, Licensee agrees


to be bound by the terms and conditions of this License Agreement.

C.2.2 PYTHON 2.0 BEOPEN.COM

BEOPEN PYTHON 1

1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at


160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
("Licensee") accessing and otherwise using this software in source or binary
form and its associated documentation ("the Software").

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.

3. BeOpen is making the Software available to Licensee on an "AS IS" basis.


BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF
EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

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.

5. This License Agreement will automatically terminate upon a material breach of


its terms and conditions.

6. This License Agreement shall be governed by and interpreted in all respects


by the law of the State of California, excluding conflict of law provisions.
Nothing in this License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between BeOpen and Licensee. This License
Agreement does not grant permission to use BeOpen trademarks or trade names in a
trademark sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the "BeOpen Python" logos available at
http://www.pythonlabs.com/logos.html may be used according to the permissions
( )

C.2. Python 297


The Python/C API, 3.12.1

( )
granted on that web page.

7. By copying, installing or otherwise using the software, Licensee agrees to be


bound by the terms and conditions of this License Agreement.

C.2.3 PYTHON 1.6.1 CNRI

1. This LICENSE AGREEMENT is between the Corporation for National Research


Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191
("CNRI"), and the Individual or Organization ("Licensee") accessing and
otherwise using Python 1.6.1 software in source or binary form and its
associated documentation.

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."

3. In the event Licensee prepares a derivative work that is based on or


incorporates Python 1.6.1 or any part thereof, and wants to make the derivative
work available to others as provided herein, then Licensee hereby agrees to
include in any such work a brief summary of the changes made to Python 1.6.1.

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.

6. This License Agreement will automatically terminate upon a material breach of


its terms and conditions.

7. This License Agreement shall be governed by the federal intellectual property


law of the United States, including without limitation the federal copyright
law, and, to the extent such U.S. federal law does not apply, by the law of the
Commonwealth of Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based on Python
1.6.1 that incorporate non-separable material that was previously distributed
under the GNU General Public License (GPL), the law of the Commonwealth of
Virginia shall govern this License Agreement only as to issues arising under or
with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in
this License Agreement shall be deemed to create any relationship of agency,
partnership, or joint venture between CNRI and Licensee. This License Agreement
does not grant permission to use CNRI trademarks or trade name in a trademark
( )

298 Appendix C.
The Python/C API, 3.12.1

( )
sense to endorse or promote products or services of Licensee, or any third
party.

8. By clicking on the "ACCEPT" button where indicated, or by copying, installing


or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and
conditions of this License Agreement.

C.2.4 PYTHON 0.9.0 1.2 CWI

Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The


Netherlands. All rights reserved.

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.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS


SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL STICHTING MATHEMATISCH 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.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.1 Mersenne Twister

random _random C http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/


MT2002/emt19937ar.html :

A C-program for MT19937, with initialization improved 2002/1/26.


Coded by Takuji Nishimura and Makoto Matsumoto.

Before using, initialize the state by using init_genrand(seed)


or init_by_array(init_key, key_length).

Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,


All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright


notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright


notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. The names of its contributors may not be used to endorse or promote


products derived from this software without specific prior written
permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.

Any feedback is very welcome.


http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)

C.3.2

socket getaddrinfo() getnameinfo() WIDE : https://www.wide.ad.


jp/

Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.


All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
( )

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 :

Copyright 1996 by Sam Rushing

All Rights Reserved

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 Sam
Rushing not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,


INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
NO EVENT SHALL SAM RUSHING 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.4 Cookie

http.cookies :

Copyright 2000 by Timothy O'Malley <[email protected]>

All Rights Reserved

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
Timothy O'Malley not be used in advertising or publicity
( )

C.3. 301
The Python/C API, 3.12.1

( )
pertaining to distribution of the software without specific, written
prior permission.

Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS


SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS, IN NO EVENT SHALL Timothy O'Malley 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.5

trace :

portions copyright 2001, Autonomous Zones Industries, Inc., all rights...


err... reserved and offered to the public under the terms of the
Python 2.2 license.
Author: Zooko O'Whielacronx
http://zooko.com/
mailto:[email protected]

Copyright 2000, Mojam Media, Inc., all rights reserved.


Author: Skip Montanaro

Copyright 1999, Bioreason, Inc., all rights reserved.


Author: Andrew Dalke

Copyright 1995-1997, Automatrix, Inc., all rights reserved.


Author: Skip Montanaro

Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.

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.

C.3.6 UUencode UUdecode

uu :

Copyright 1994 by Lance Ellinghouse


Cathedral City, California Republic, United States of America.
All Rights Reserved
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 Lance Ellinghouse
not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
( )

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.

Modified by Jack Jansen, CWI, July 1995:


- Use binascii module to do the actual line-by-line conversion
between ascii and binary. This results in a 1000-fold speedup. The C
version is still 5 times faster, though.
- Arguments more compliant with Python standard

C.3.7 XML

xmlrpc.client :

The XML-RPC client interface is

Copyright (c) 1999-2002 by Secret Labs AB


Copyright (c) 1999-2002 by Fredrik Lundh

By obtaining, using, and/or copying this software and/or its


associated documentation, you agree that you have read, understood,
and will comply with the following terms and conditions:

Permission to use, copy, modify, and distribute this software and


its associated documentation for any purpose and 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
Secret Labs AB or the author not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

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 :

Copyright (c) 2001-2006 Twisted Matrix Laboratories.

Permission is hereby granted, free of charge, to any person obtaining


a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
( )

C.3. 303
The Python/C API, 3.12.1

( )
the following conditions:

The above copyright notice and this permission notice shall be


included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,


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.9 Select kqueue

select kqueue :

Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
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.10 SipHash24

Python/pyhash.c Marek Majkowski’ Dan Bernstein SipHash24


:

<MIT License>
Copyright (c) 2013 Marek Majkowski <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy


of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

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/

Solution inspired by code from:


Samuel Neves (supercop/crypto_auth/siphash24/little)
djb (supercop/crypto_auth/siphash24/little2)
Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c)

C.3.11 strtod dtoa

Python/dtoa.c C dtoa strtod C


David M. Gay https://web.archive.org/web/20220517033456/http:
//www.netlib.org/fp/dtoa.c 2009 3 16 :

/****************************************************************
*
* 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

hashlib, posix, ssl, crypt OpenSSL


Python Windows macOS OpenSSL OpenSSL
OpenSSL 3.0 Apache v2:

Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by


the copyright owner that is granting the License.

"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.

"You" (or "Your") shall mean an individual or Legal Entity


exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.

"Object" form shall mean any form resulting from mechanical


transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or


Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object


form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including


the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity


on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of


this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of


this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
( )

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.

4. Redistribution. You may reproduce and distribute copies of the


Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:

(a) You must give any other recipients of the Work or


Derivative Works a copy of this License; and

(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

(d) If the Work includes a "NOTICE" text file as part of its


distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

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.

5. Submission of Contributions. Unless You explicitly state otherwise,


any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.

( )

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.

7. Disclaimer of Warranty. Unless required by applicable law or


agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,


whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing


the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

C.3.13 expat

pyexpat expat --with-system-expat:

Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
and Clark Cooper

Permission is hereby granted, free of charge, to any person obtaining


a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,


( )

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

ctypes _ctypes C libffi


--with-system-libffi:

Copyright (c) 1996-2008 Red Hat, Inc and others.

Permission is hereby granted, free of charge, to any person obtaining


a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,


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.15 zlib

zlib zlib zlib :

Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler

This software is provided 'as-is', without any express or implied


warranty. In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,


including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

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

( )

Jean-loup Gailly Mark Adler


[email protected] [email protected]

C.3.16 cfuhash

tracemalloc cfuhash :

Copyright (c) 2005 Don Owens


All rights reserved.

This code is released under the BSD license:

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

* Redistributions of source code must retain the above copyright


notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above


copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

* Neither the name of the author 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 COPYRIGHT HOLDERS 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
COPYRIGHT OWNER 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.17 libmpdec

decimal _decimal C libmpdec


--with-system-libmpdec:

Copyright (c) 2008-2020 Stefan Krah. All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright


notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright


( )

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.18 W3C C14N

test C14N 2.0 (Lib/test/xmltestdata/c14n-20/) W3C https://www.


w3.org/TR/xml-c14n2-testcases/ 3 BSD :

Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang),


All Rights Reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

* Redistributions of works must retain the original copyright notice,


this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the W3C nor the names of its contributors may be
used to endorse or promote products derived from this work without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT
OWNER 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

audioop SoX g771.c :

Programming the AdLib/Sound Blaster


FM Music Chips
Version 2.0 (24 Feb 1992)
Copyright (c) 1991, 1992 by Jeffrey S. Lee
[email protected]
Warranty and Copyright Policy
This document is provided on an "as-is" basis, and its author makes
no warranty or representation, express or implied, with respect to
its quality performance or fitness for a particular purpose. In no
event will the author of this document be liable for direct, indirect,
special, incidental, or consequential damages arising out of the use
or inability to use the information contained within. Use of this
document is at your own risk.
This file may be used and copied freely so long as the applicable
copyright notices are retained, and no modifications are made to the
text of the document. No money shall be charged for its distribution
beyond reasonable shipping, handling and duplication costs, nor shall
proprietary changes be made to this document so that it cannot be
distributed freely. This document may not be included in published
material or commercial packages without the written consent of its
author.

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

, 237 object -- , 166


, 98 class -- , 283
class variable -- , 283
( ), 98 close() (in module os), 195
CO_FUTURE_DIVISION (C var), 42
( ), 98 complex number --
object -- , 119
, 67 complex number -- , 283
, 186 context manager -- , 283
, 186 context variable -- , 283
contiguous -- , 101
object -- , 113 contiguous -- , 283
copyright ( sys ), 184
, 237 coroutine -- , 283
coroutine function -- , 283
method -- , 287 CPython, 283

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

ModuleType ( types ), 155 PEP, 289


MRO, 288 platform ( sys ), 184
mutable -- , 288 portion -- , 289
positional argument -- , 289
N pow
named tuple -- , 288 , 92, 94
namespace -- , 288 provisional API -- API, 289
namespace package -- , 288 provisional package -- , 290
nested scope -- , 288 Py_ABS (C macro), 4
new-style class -- , 288 Py_AddPendingCall (C function), 196
newfunc (C type), 272 Py_AddPendingCall(), 196
None Py_ALWAYS_INLINE (C macro), 4
object -- , 113 Py_AtExit (C function), 66
Py_AUDIT_READ (C macro), 239
O Py_BEGIN_ALLOW_THREADS, 186
object -- Py_BEGIN_ALLOW_THREADS (C macro), 189
bytearray, 122 Py_BLOCK_THREADS (C macro), 189
Capsule, 166 Py_buffer (C type), 99
code -- , 150 Py_buffer.buf (C member), 99
complex number -- , 119 Py_buffer.format (C member), 100
dictionary -- , 142 Py_buffer.internal (C member), 100
frozenset, 145 Py_buffer.itemsize (C member), 99
function -- , 147 Py_buffer.len (C member), 99
instancemethod, 149 Py_buffer.ndim (C member), 100
integer, 113 Py_buffer.obj (C member), 99
list, 141 Py_buffer.readonly (C member), 99
mapping -- , 142 Py_buffer.shape (C member), 100
memoryview, 165 Py_buffer.strides (C member), 100
method -- , 149 Py_buffer.suboffsets (C member), 100
module, 155 Py_BuildValue (C function), 75
None, 113 Py_BytesMain (C function), 39
sequence, 120 Py_BytesWarningFlag (C var), 178
set, 145 Py_CHARMASK (C macro), 5
type, 6, 107 Py_CLEAR (C function), 44
, 138 Py_CompileString (C function), 41
, 120 Py_CompileString(), 42
, 113 Py_CompileStringExFlags (C function), 41
, 154 Py_CompileStringFlags (C function), 41
, 117 Py_CompileStringObject (C function), 41
, 113 Py_complex (C type), 119
object -- , 288 Py_DebugFlag (C var), 178
objobjargproc (C type), 273 Py_DecodeLocale (C function), 62
objobjproc (C type), 273 Py_DECREF (C function), 44
OverflowError ( ), 114, 115 Py_DecRef (C function), 45
Py_DECREF(), 7
P Py_DEPRECATED (C macro), 5
Py_DontWriteBytecodeFlag (C var), 178
package -- , 288
Py_Ellipsis (C var), 165
parameter -- , 288
Py_EncodeLocale (C function), 63
PATH, 11
Py_END_ALLOW_THREADS, 186
path
Py_END_ALLOW_THREADS (C macro), 189
module , 11, 181, 183
Py_EndInterpreter (C function), 195
path ( sys ), 11, 181, 183
Py_EnterRecursiveCall (C function), 57
path based finder -- ,
Py_EQ (C macro), 259
289
Py_eval_input (C var), 42
path entry -- , 289
Py_Exit (C function), 66
path entry finder -- , 289
Py_ExitStatusException (C function), 203
path entry hook -- , 289
Py_False (C var), 116
path-like object -- , 289

318
The Python/C API, 3.12.1

Py_FatalError (C function), 66 Py_MEMBER_SIZE (C macro), 5


Py_FatalError(), 184 PY_MICRO_VERSION (C macro), 279
Py_FdIsInteractive (C function), 61 Py_MIN (C macro), 5
Py_file_input (C var), 42 PY_MINOR_VERSION (C macro), 279
Py_Finalize (C function), 181 Py_mod_create (C macro), 158
Py_FinalizeEx (C function), 181 Py_mod_exec (C macro), 158
Py_FinalizeEx(), 66, 181, 194, 195 Py_mod_multiple_interpreters (C macro),
Py_FrozenFlag (C var), 178 158
Py_GE (C macro), 259 Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED
Py_GenericAlias (C function), 175 (C macro), 158
Py_GenericAliasType (C var), 176 Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED
Py_GetArgcArgv (C function), 220 (C macro), 158
Py_GetBuildInfo (C function), 184 Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
Py_GetCompiler (C function), 184 (C macro), 158
Py_GetCopyright (C function), 184 Py_NE (C macro), 259
Py_GETENV (C macro), 5 Py_NewInterpreter (C function), 195
Py_GetExecPrefix (C function), 182 Py_NewInterpreterFromConfig (C function),
Py_GetExecPrefix(), 11 194
Py_GetPath (C function), 183 Py_NewRef (C function), 43
Py_GetPath(), 11, 182, 183 Py_NO_INLINE (C macro), 5
Py_GetPlatform (C function), 184 Py_None (C var), 113
Py_GetPrefix (C function), 182 Py_NoSiteFlag (C var), 180
Py_GetPrefix(), 11 Py_NotImplemented (C var), 83
Py_GetProgramFullPath (C function), 183 Py_NoUserSiteDirectory (C var), 180
Py_GetProgramFullPath(), 11 Py_OptimizeFlag (C var), 180
Py_GetProgramName (C function), 182 Py_PreInitialize (C function), 206
Py_GetPythonHome (C function), 185 Py_PreInitializeFromArgs (C function), 206
Py_GetVersion (C function), 184 Py_PreInitializeFromBytesArgs (C func-
Py_GT (C macro), 259 tion), 206
Py_HashRandomizationFlag (C var), 179 Py_PRINT_RAW, 155
Py_IgnoreEnvironmentFlag (C var), 179 Py_QuietFlag (C var), 180
Py_INCREF (C function), 43 Py_READONLY (C macro), 239
Py_IncRef (C function), 44 Py_REFCNT (C function), 43
Py_INCREF(), 7 Py_RELATIVE_OFFSET (C macro), 239
Py_Initialize (C function), 181 PY_RELEASE_LEVEL (C macro), 279
Py_Initialize(), 11, 182, 194 PY_RELEASE_SERIAL (C macro), 279
Py_InitializeEx (C function), 181 Py_ReprEnter (C function), 57
Py_InitializeFromConfig (C function), 217 Py_ReprLeave (C function), 57
Py_InspectFlag (C var), 179 Py_RETURN_FALSE (C macro), 116
Py_InteractiveFlag (C var), 179 Py_RETURN_NONE (C macro), 113
Py_Is (C function), 234 Py_RETURN_NOTIMPLEMENTED (C macro), 83
Py_IS_TYPE (C function), 235 Py_RETURN_RICHCOMPARE (C macro), 259
Py_IsFalse (C function), 234 Py_RETURN_TRUE (C macro), 116
Py_IsInitialized (C function), 181 Py_RunMain (C function), 220
Py_IsInitialized(), 11 Py_SET_REFCNT (C function), 43
Py_IsNone (C function), 234 Py_SET_SIZE (C function), 235
Py_IsolatedFlag (C var), 179 Py_SET_TYPE (C function), 235
Py_IsTrue (C function), 234 Py_SetPath (C function), 183
Py_LE (C macro), 259 Py_SetPath(), 183
Py_LeaveRecursiveCall (C function), 57 Py_SetProgramName (C function), 182
Py_LegacyWindowsFSEncodingFlag (C var), Py_SetProgramName(), 11, 181183
179 Py_SetPythonHome (C function), 185
Py_LegacyWindowsStdioFlag (C var), 180 Py_SETREF (C macro), 45
Py_LIMITED_API (C macro), 14 Py_SetStandardStreamEncoding (C function),
Py_LT (C macro), 259 182
Py_Main (C function), 39 Py_single_input (C var), 42
PY_MAJOR_VERSION (C macro), 279 Py_SIZE (C function), 235
Py_MAX (C macro), 5 Py_ssize_t (C type), 9

319
The Python/C API, 3.12.1

PY_SSIZE_T_MAX, 115 Py_UNBLOCK_THREADS (C macro), 190


Py_STRINGIFY (C macro), 5 Py_UnbufferedStdioFlag (C var), 180
Py_T_BOOL (C macro), 240 Py_UNICODE (C type), 123
Py_T_BYTE (C macro), 240 Py_UNICODE_IS_HIGH_SURROGATE (C function),
Py_T_CHAR (C macro), 240 126
Py_T_DOUBLE (C macro), 240 Py_UNICODE_IS_LOW_SURROGATE (C function),
Py_T_FLOAT (C macro), 240 126
Py_T_INT (C macro), 240 Py_UNICODE_IS_SURROGATE (C function), 126
Py_T_LONG (C macro), 240 Py_UNICODE_ISALNUM (C function), 125
Py_T_LONGLONG (C macro), 240 Py_UNICODE_ISALPHA (C function), 125
Py_T_OBJECT_EX (C macro), 240 Py_UNICODE_ISDECIMAL (C function), 125
Py_T_PYSSIZET (C macro), 240 Py_UNICODE_ISDIGIT (C function), 125
Py_T_SHORT (C macro), 240 Py_UNICODE_ISLINEBREAK (C function), 125
Py_T_STRING (C macro), 240 Py_UNICODE_ISLOWER (C function), 125
Py_T_STRING_INPLACE (C macro), 240 Py_UNICODE_ISNUMERIC (C function), 125
Py_T_UBYTE (C macro), 240 Py_UNICODE_ISPRINTABLE (C function), 125
Py_T_UINT (C macro), 240 Py_UNICODE_ISSPACE (C function), 125
Py_T_ULONG (C macro), 240 Py_UNICODE_ISTITLE (C function), 125
Py_T_ULONGLONG (C macro), 240 Py_UNICODE_ISUPPER (C function), 125
Py_T_USHORT (C macro), 240 Py_UNICODE_JOIN_SURROGATES (C function),
Py_TPFLAGS_BASE_EXC_SUBCLASS (C macro), 126
255 Py_UNICODE_TODECIMAL (C function), 126
Py_TPFLAGS_BASETYPE (C macro), 253 Py_UNICODE_TODIGIT (C function), 126
Py_TPFLAGS_BYTES_SUBCLASS (C macro), 255 Py_UNICODE_TOLOWER (C function), 125
Py_TPFLAGS_DEFAULT (C macro), 254 Py_UNICODE_TONUMERIC (C function), 126
Py_TPFLAGS_DICT_SUBCLASS (C macro), 255 Py_UNICODE_TOTITLE (C function), 126
Py_TPFLAGS_DISALLOW_INSTANTIATION (C Py_UNICODE_TOUPPER (C function), 125
macro), 255 Py_UNREACHABLE (C macro), 5
Py_TPFLAGS_HAVE_FINALIZE (C macro), 255 Py_UNUSED (C macro), 6
Py_TPFLAGS_HAVE_GC (C macro), 253 Py_VaBuildValue (C function), 77
Py_TPFLAGS_HAVE_VECTORCALL (C macro), 255 PY_VECTORCALL_ARGUMENTS_OFFSET (C
Py_TPFLAGS_HEAPTYPE (C macro), 253 macro), 88
Py_TPFLAGS_IMMUTABLETYPE (C macro), 255 Py_VerboseFlag (C var), 180
Py_TPFLAGS_ITEMS_AT_END (C macro), 254 Py_Version (C var), 279
Py_TPFLAGS_LIST_SUBCLASS (C macro), 255 PY_VERSION_HEX (C macro), 279
Py_TPFLAGS_LONG_SUBCLASS (C macro), 255 Py_VISIT (C function), 277
Py_TPFLAGS_MANAGED_DICT (C macro), 254 Py_XDECREF (C function), 44
Py_TPFLAGS_MANAGED_WEAKREF (C macro), 254 Py_XDECREF(), 11
Py_TPFLAGS_MAPPING (C macro), 256 Py_XINCREF (C function), 43
Py_TPFLAGS_METHOD_DESCRIPTOR (C macro), Py_XNewRef (C function), 44
254 Py_XSETREF (C macro), 45
Py_TPFLAGS_READY (C macro), 253 PyAIter_Check (C function), 97
Py_TPFLAGS_READYING (C macro), 253 PyAnySet_Check (C function), 146
Py_TPFLAGS_SEQUENCE (C macro), 256 PyAnySet_CheckExact (C function), 146
Py_TPFLAGS_TUPLE_SUBCLASS (C macro), 255 PyArg_Parse (C function), 74
Py_TPFLAGS_TYPE_SUBCLASS (C macro), 255 PyArg_ParseTuple (C function), 74
Py_TPFLAGS_UNICODE_SUBCLASS (C macro), PyArg_ParseTupleAndKeywords (C function),
255 74
Py_TPFLAGS_VALID_VERSION_TAG (C macro), PyArg_UnpackTuple (C function), 75
256 PyArg_ValidateKeywordArguments (C func-
Py_tracefunc (C type), 197 tion), 74
Py_True (C var), 116 PyArg_VaParse (C function), 74
Py_tss_NEEDS_INIT (C macro), 199 PyArg_VaParseTupleAndKeywords (C func-
Py_tss_t (C type), 199 tion), 74
Py_TYPE (C function), 235 PyASCIIObject (C type), 123
Py_UCS1 (C type), 123 PyAsyncMethods (C type), 271
Py_UCS2 (C type), 123 PyAsyncMethods.am_aiter (C member), 271
Py_UCS4 (C type), 123 PyAsyncMethods.am_anext (C member), 271

320
The Python/C API, 3.12.1

PyAsyncMethods.am_await (C member), 271 PyBytes_FromFormat (C function), 120


PyAsyncMethods.am_send (C member), 271 PyBytes_FromFormatV (C function), 121
PyBool_Check (C function), 116 PyBytes_FromObject (C function), 121
PyBool_FromLong (C function), 117 PyBytes_FromString (C function), 120
PyBool_Type (C var), 116 PyBytes_FromStringAndSize (C function), 120
PyBUF_ANY_CONTIGUOUS (C macro), 101 PyBytes_GET_SIZE (C function), 121
PyBUF_C_CONTIGUOUS (C macro), 101 PyBytes_Size (C function), 121
PyBUF_CONTIG (C macro), 102 PyBytes_Type (C var), 120
PyBUF_CONTIG_RO (C macro), 102 PyBytesObject (C type), 120
PyBUF_F_CONTIGUOUS (C macro), 101 PyCallable_Check (C function), 92
PyBUF_FORMAT (C macro), 101 PyCallIter_Check (C function), 162
PyBUF_FULL (C macro), 102 PyCallIter_New (C function), 162
PyBUF_FULL_RO (C macro), 102 PyCallIter_Type (C var), 162
PyBUF_INDIRECT (C macro), 101 PyCapsule (C type), 166
PyBUF_MAX_NDIM (C macro), 100 PyCapsule_CheckExact (C function), 166
PyBUF_ND (C macro), 101 PyCapsule_Destructor (C type), 166
PyBUF_RECORDS (C macro), 102 PyCapsule_GetContext (C function), 167
PyBUF_RECORDS_RO (C macro), 102 PyCapsule_GetDestructor (C function), 167
PyBUF_SIMPLE (C macro), 101 PyCapsule_GetName (C function), 167
PyBUF_STRIDED (C macro), 102 PyCapsule_GetPointer (C function), 167
PyBUF_STRIDED_RO (C macro), 102 PyCapsule_Import (C function), 167
PyBUF_STRIDES (C macro), 101 PyCapsule_IsValid (C function), 167
PyBUF_WRITABLE (C macro), 101 PyCapsule_New (C function), 166
PyBuffer_FillContiguousStrides (C func- PyCapsule_SetContext (C function), 167
tion), 104 PyCapsule_SetDestructor (C function), 167
PyBuffer_FillInfo (C function), 104 PyCapsule_SetName (C function), 167
PyBuffer_FromContiguous (C function), 104 PyCapsule_SetPointer (C function), 167
PyBuffer_GetPointer (C function), 104 PyCell_Check (C function), 150
PyBuffer_IsContiguous (C function), 104 PyCell_GET (C function), 150
PyBuffer_Release (C function), 103 PyCell_Get (C function), 150
PyBuffer_SizeFromFormat (C function), 104 PyCell_New (C function), 150
PyBuffer_ToContiguous (C function), 104 PyCell_SET (C function), 150
PyBufferProcs, 98 PyCell_Set (C function), 150
PyBufferProcs (C type), 270 PyCell_Type (C var), 150
PyBufferProcs.bf_getbuffer (C member), PyCellObject (C type), 150
270 PyCFunction (C type), 235
PyBufferProcs.bf_releasebuffer (C mem- PyCFunctionWithKeywords (C type), 235
ber), 270 PyCMethod (C type), 236
PyByteArray_AS_STRING (C function), 123 PyCode_Addr2Line (C function), 151
PyByteArray_AsString (C function), 122 PyCode_Addr2Location (C function), 152
PyByteArray_Check (C function), 122 PyCode_AddWatcher (C function), 152
PyByteArray_CheckExact (C function), 122 PyCode_Check (C function), 151
PyByteArray_Concat (C function), 122 PyCode_ClearWatcher (C function), 152
PyByteArray_FromObject (C function), 122 PyCode_GetCellvars (C function), 152
PyByteArray_FromStringAndSize (C func- PyCode_GetCode (C function), 152
tion), 122 PyCode_GetFreevars (C function), 152
PyByteArray_GET_SIZE (C function), 123 PyCode_GetNumFree (C function), 151
PyByteArray_Resize (C function), 122 PyCode_GetVarnames (C function), 152
PyByteArray_Size (C function), 122 PyCode_New, 151
PyByteArray_Type (C var), 122 PyCode_NewEmpty (C function), 151
PyByteArrayObject (C type), 122 PyCode_NewWithPosOnlyArgs, 151
PyBytes_AS_STRING (C function), 121 PyCode_Type (C var), 151
PyBytes_AsString (C function), 121 PyCode_WatchCallback (C type), 152
PyBytes_AsStringAndSize (C function), 121 PyCodec_BackslashReplaceErrors (C func-
PyBytes_Check (C function), 120 tion), 80
PyBytes_CheckExact (C function), 120 PyCodec_Decode (C function), 79
PyBytes_Concat (C function), 121 PyCodec_Decoder (C function), 79
PyBytes_ConcatAndDel (C function), 121 PyCodec_Encode (C function), 79

321
The Python/C API, 3.12.1

PyCodec_Encoder (C function), 79 PyConfig.exec_prefix (C member), 210


PyCodec_IgnoreErrors (C function), 80 PyConfig.executable (C member), 210
PyCodec_IncrementalDecoder (C function), 79 PyConfig.faulthandler (C member), 210
PyCodec_IncrementalEncoder (C function), 79 PyConfig.filesystem_encoding (C member),
PyCodec_KnownEncoding (C function), 79 210
PyCodec_LookupError (C function), 79 PyConfig.filesystem_errors (C member),
PyCodec_NameReplaceErrors (C function), 80 210
PyCodec_Register (C function), 78 PyConfig.hash_seed (C member), 211
PyCodec_RegisterError (C function), 79 PyConfig.home (C member), 211
PyCodec_ReplaceErrors (C function), 80 PyConfig.import_time (C member), 211
PyCodec_StreamReader (C function), 79 PyConfig.inspect (C member), 211
PyCodec_StreamWriter (C function), 79 PyConfig.install_signal_handlers (C
PyCodec_StrictErrors (C function), 80 member), 211
PyCodec_Unregister (C function), 78 PyConfig.int_max_str_digits (C member),
PyCodec_XMLCharRefReplaceErrors (C func- 211
tion), 80 PyConfig.interactive (C member), 211
PyCodeEvent (C type), 152 PyConfig.isolated (C member), 211
PyCodeObject (C type), 151 PyConfig.legacy_windows_stdio (C mem-
PyCompactUnicodeObject (C type), 123 ber), 212
PyCompilerFlags (C struct), 42 PyConfig.malloc_stats (C member), 212
PyCompilerFlags.cf_feature_version (C PyConfig.module_search_paths (C member),
member), 42 212
PyCompilerFlags.cf_flags (C member), 42 PyConfig.module_search_paths_set (C
PyComplex_AsCComplex (C function), 120 member), 212
PyComplex_Check (C function), 119 PyConfig.optimization_level (C member),
PyComplex_CheckExact (C function), 119 213
PyComplex_FromCComplex (C function), 119 PyConfig.orig_argv (C member), 213
PyComplex_FromDoubles (C function), 119 PyConfig.parse_argv (C member), 213
PyComplex_ImagAsDouble (C function), 120 PyConfig.parser_debug (C member), 213
PyComplex_RealAsDouble (C function), 120 PyConfig.pathconfig_warnings (C member),
PyComplex_Type (C var), 119 213
PyComplexObject (C type), 119 PyConfig.perf_profiling (C member), 215
PyConfig (C type), 207 PyConfig.platlibdir (C member), 212
PyConfig_Clear (C function), 207 PyConfig.prefix (C member), 213
PyConfig_InitIsolatedConfig (C function), PyConfig.program_name (C member), 214
207 PyConfig.pycache_prefix (C member), 214
PyConfig_InitPythonConfig (C function), 207 PyConfig.pythonpath_env (C member), 212
PyConfig_Read (C function), 207 PyConfig.quiet (C member), 214
PyConfig_SetArgv (C function), 207 PyConfig.run_command (C member), 214
PyConfig_SetBytesArgv (C function), 207 PyConfig.run_filename (C member), 214
PyConfig_SetBytesString (C function), 207 PyConfig.run_module (C member), 214
PyConfig_SetString (C function), 207 PyConfig.safe_path (C member), 208
PyConfig_SetWideStringList (C function), PyConfig.show_ref_count (C member), 214
207 PyConfig.site_import (C member), 215
PyConfig.argv (C member), 208 PyConfig.skip_source_first_line (C mem-
PyConfig.base_exec_prefix (C member), 208 ber), 215
PyConfig.base_executable (C member), 208 PyConfig.stdio_encoding (C member), 215
PyConfig.base_prefix (C member), 208 PyConfig.stdio_errors (C member), 215
PyConfig.buffered_stdio (C member), 208 PyConfig.tracemalloc (C member), 215
PyConfig.bytes_warning (C member), 209 PyConfig.use_environment (C member), 215
PyConfig.check_hash_pycs_mode (C mem- PyConfig.use_hash_seed (C member), 211
ber), 209 PyConfig.user_site_directory (C member),
PyConfig.code_debug_ranges (C member), 216
209 PyConfig.verbose (C member), 216
PyConfig.configure_c_stdio (C member), PyConfig.warn_default_encoding (C mem-
209 ber), 209
PyConfig.dev_mode (C member), 209 PyConfig.warnoptions (C member), 216
PyConfig.dump_refs (C member), 209 PyConfig.write_bytecode (C member), 216

322
The Python/C API, 3.12.1

PyConfig.xoptions (C member), 216 PyDateTime_Time (C type), 172


PyContext (C type), 171 PyDateTime_TIME_GET_FOLD (C function), 175
PyContext_CheckExact (C function), 171 PyDateTime_TIME_GET_HOUR (C function), 174
PyContext_Copy (C function), 171 PyDateTime_TIME_GET_MICROSECOND (C func-
PyContext_CopyCurrent (C function), 171 tion), 174
PyContext_Enter (C function), 171 PyDateTime_TIME_GET_MINUTE (C function),
PyContext_Exit (C function), 171 174
PyContext_New (C function), 171 PyDateTime_TIME_GET_SECOND (C function),
PyContext_Type (C var), 171 174
PyContextToken (C type), 171 PyDateTime_TIME_GET_TZINFO (C function),
PyContextToken_CheckExact (C function), 171 175
PyContextToken_Type (C var), 171 PyDateTime_TimeType (C var), 172
PyContextVar (C type), 171 PyDateTime_TimeZone_UTC (C var), 172
PyContextVar_CheckExact (C function), 171 PyDateTime_TZInfoType (C var), 172
PyContextVar_Get (C function), 171 PyDelta_Check (C function), 173
PyContextVar_New (C function), 171 PyDelta_CheckExact (C function), 173
PyContextVar_Reset (C function), 172 PyDelta_FromDSU (C function), 173
PyContextVar_Set (C function), 172 PyDescr_IsData (C function), 163
PyContextVar_Type (C var), 171 PyDescr_NewClassMethod (C function), 163
PyCoro_CheckExact (C function), 170 PyDescr_NewGetSet (C function), 163
PyCoro_New (C function), 170 PyDescr_NewMember (C function), 163
PyCoro_Type (C var), 170 PyDescr_NewMethod (C function), 163
PyCoroObject (C type), 170 PyDescr_NewWrapper (C function), 163
PyDate_Check (C function), 172 PyDict_AddWatcher (C function), 144
PyDate_CheckExact (C function), 173 PyDict_Check (C function), 142
PyDate_FromDate (C function), 173 PyDict_CheckExact (C function), 142
PyDate_FromTimestamp (C function), 175 PyDict_Clear (C function), 142
PyDateTime_Check (C function), 173 PyDict_ClearWatcher (C function), 144
PyDateTime_CheckExact (C function), 173 PyDict_Contains (C function), 142
PyDateTime_Date (C type), 172 PyDict_Copy (C function), 142
PyDateTime_DATE_GET_FOLD (C function), 174 PyDict_DelItem (C function), 143
PyDateTime_DATE_GET_HOUR (C function), 174 PyDict_DelItemString (C function), 143
PyDateTime_DATE_GET_MICROSECOND (C func- PyDict_GetItem (C function), 143
tion), 174 PyDict_GetItemString (C function), 143
PyDateTime_DATE_GET_MINUTE (C function), PyDict_GetItemWithError (C function), 143
174 PyDict_Items (C function), 143
PyDateTime_DATE_GET_SECOND (C function), PyDict_Keys (C function), 143
174 PyDict_Merge (C function), 144
PyDateTime_DATE_GET_TZINFO (C function), PyDict_MergeFromSeq2 (C function), 144
174 PyDict_New (C function), 142
PyDateTime_DateTime (C type), 172 PyDict_Next (C function), 143
PyDateTime_DateTimeType (C var), 172 PyDict_SetDefault (C function), 143
PyDateTime_DateType (C var), 172 PyDict_SetItem (C function), 142
PyDateTime_Delta (C type), 172 PyDict_SetItemString (C function), 142
PyDateTime_DELTA_GET_DAYS (C function), 175 PyDict_Size (C function), 143
PyDateTime_DELTA_GET_MICROSECONDS (C PyDict_Type (C var), 142
function), 175 PyDict_Unwatch (C function), 145
PyDateTime_DELTA_GET_SECONDS (C function), PyDict_Update (C function), 144
175 PyDict_Values (C function), 143
PyDateTime_DeltaType (C var), 172 PyDict_Watch (C function), 144
PyDateTime_FromDateAndTime (C function), PyDict_WatchCallback (C type), 145
173 PyDict_WatchEvent (C type), 145
PyDateTime_FromDateAndTimeAndFold (C PyDictObject (C type), 142
function), 173 PyDictProxy_New (C function), 142
PyDateTime_FromTimestamp (C function), 175 PyDoc_STR (C macro), 6
PyDateTime_GET_DAY (C function), 174 PyDoc_STRVAR (C macro), 6
PyDateTime_GET_MONTH (C function), 174 PyErr_BadArgument (C function), 48
PyDateTime_GET_YEAR (C function), 174 PyErr_BadInternalCall (C function), 50

323
The Python/C API, 3.12.1

PyErr_CheckSignals (C function), 54 PyErr_WarnExplicitObject (C function), 51


PyErr_Clear (C function), 47 PyErr_WarnFormat (C function), 51
PyErr_Clear(), 10, 11 PyErr_WriteUnraisable (C function), 48
PyErr_DisplayException (C function), 48 PyEval_AcquireLock (C function), 192
PyErr_ExceptionMatches (C function), 51 PyEval_AcquireThread (C function), 192
PyErr_ExceptionMatches(), 11 PyEval_AcquireThread(), 188
PyErr_Fetch (C function), 52 PyEval_EvalCode (C function), 42
PyErr_Format (C function), 48 PyEval_EvalCodeEx (C function), 42
PyErr_FormatV (C function), 48 PyEval_EvalFrame (C function), 42
PyErr_GetExcInfo (C function), 53 PyEval_EvalFrameEx (C function), 42
PyErr_GetHandledException (C function), 53 PyEval_GetBuiltins (C function), 78
PyErr_GetRaisedException (C function), 51 PyEval_GetFrame (C function), 78
PyErr_GivenExceptionMatches (C function), PyEval_GetFuncDesc (C function), 78
51 PyEval_GetFuncName (C function), 78
PyErr_NewException (C function), 55 PyEval_GetGlobals (C function), 78
PyErr_NewExceptionWithDoc (C function), 55 PyEval_GetLocals (C function), 78
PyErr_NoMemory (C function), 48 PyEval_InitThreads (C function), 188
PyErr_NormalizeException (C function), 52 PyEval_InitThreads(), 181
PyErr_Occurred (C function), 51 PyEval_MergeCompilerFlags (C function), 42
PyErr_Occurred(), 10 PyEval_ReleaseLock (C function), 193
PyErr_Print (C function), 47 PyEval_ReleaseThread (C function), 192
PyErr_PrintEx (C function), 47 PyEval_ReleaseThread(), 188
PyErr_ResourceWarning (C function), 51 PyEval_RestoreThread (C function), 188
PyErr_Restore (C function), 52 PyEval_RestoreThread(), 186, 188
PyErr_SetExcFromWindowsErr (C function), 49 PyEval_SaveThread (C function), 188
PyErr_SetExcFromWindowsErrWithFilename PyEval_SaveThread(), 186, 188
(C function), 50 PyEval_SetProfile (C function), 198
PyErr_SetExcFromWindowsErrWithFilenameObjectPyEval_SetProfileAllThreads (C function),
(C function), 49 198
PyErr_SetExcFromWindowsErrWithFilenameObjects
PyEval_SetTrace (C function), 198
(C function), 49 PyEval_SetTraceAllThreads (C function), 198
PyErr_SetExcInfo (C function), 53 PyEval_ThreadsInitialized (C function), 188
PyErr_SetFromErrno (C function), 48 PyExc_ArithmeticError, 57
PyErr_SetFromErrnoWithFilename (C func- PyExc_AssertionError, 57
tion), 49 PyExc_AttributeError, 57
PyErr_SetFromErrnoWithFilenameObject PyExc_BaseException, 57
(C function), 49 PyExc_BlockingIOError, 57
PyErr_SetFromErrnoWithFilenameObjects PyExc_BrokenPipeError, 57
(C function), 49 PyExc_BufferError, 57
PyErr_SetFromWindowsErr (C function), 49 PyExc_BytesWarning, 59
PyErr_SetFromWindowsErrWithFilename (C PyExc_ChildProcessError, 57
function), 49 PyExc_ConnectionAbortedError, 57
PyErr_SetHandledException (C function), 53 PyExc_ConnectionError, 57
PyErr_SetImportError (C function), 50 PyExc_ConnectionRefusedError, 57
PyErr_SetImportErrorSubclass (C function), PyExc_ConnectionResetError, 57
50 PyExc_DeprecationWarning, 59
PyErr_SetInterrupt (C function), 54 PyExc_EnvironmentError, 59
PyErr_SetInterruptEx (C function), 54 PyExc_EOFError, 57
PyErr_SetNone (C function), 48 PyExc_Exception, 57
PyErr_SetObject (C function), 48 PyExc_FileExistsError, 57
PyErr_SetRaisedException (C function), 52 PyExc_FileNotFoundError, 57
PyErr_SetString (C function), 48 PyExc_FloatingPointError, 57
PyErr_SetString(), 10 PyExc_FutureWarning, 59
PyErr_SyntaxLocation (C function), 50 PyExc_GeneratorExit, 57
PyErr_SyntaxLocationEx (C function), 50 PyExc_ImportError, 57
PyErr_SyntaxLocationObject (C function), 50 PyExc_ImportWarning, 59
PyErr_WarnEx (C function), 50 PyExc_IndentationError, 57
PyErr_WarnExplicit (C function), 51 PyExc_IndexError, 57

324
The Python/C API, 3.12.1

PyExc_InterruptedError, 57 PyFloat_FromDouble (C function), 117


PyExc_IOError, 59 PyFloat_FromString (C function), 117
PyExc_IsADirectoryError, 57 PyFloat_GetInfo (C function), 117
PyExc_KeyboardInterrupt, 57 PyFloat_GetMax (C function), 117
PyExc_KeyError, 57 PyFloat_GetMin (C function), 117
PyExc_LookupError, 57 PyFloat_Pack2 (C function), 118
PyExc_MemoryError, 57 PyFloat_Pack4 (C function), 118
PyExc_ModuleNotFoundError, 57 PyFloat_Pack8 (C function), 118
PyExc_NameError, 57 PyFloat_Type (C var), 117
PyExc_NotADirectoryError, 57 PyFloat_Unpack2 (C function), 118
PyExc_NotImplementedError, 57 PyFloat_Unpack4 (C function), 118
PyExc_OSError, 57 PyFloat_Unpack8 (C function), 118
PyExc_OverflowError, 57 PyFloatObject (C type), 117
PyExc_PendingDeprecationWarning, 59 PyFrame_Check (C function), 168
PyExc_PermissionError, 57 PyFrame_GetBack (C function), 168
PyExc_ProcessLookupError, 57 PyFrame_GetBuiltins (C function), 168
PyExc_RecursionError, 57 PyFrame_GetCode (C function), 168
PyExc_ReferenceError, 57 PyFrame_GetGenerator (C function), 168
PyExc_ResourceWarning, 59 PyFrame_GetGlobals (C function), 168
PyExc_RuntimeError, 57 PyFrame_GetLasti (C function), 168
PyExc_RuntimeWarning, 59 PyFrame_GetLineNumber (C function), 169
PyExc_StopAsyncIteration, 57 PyFrame_GetLocals (C function), 169
PyExc_StopIteration, 57 PyFrame_GetVar (C function), 168
PyExc_SyntaxError, 57 PyFrame_GetVarString (C function), 169
PyExc_SyntaxWarning, 59 PyFrame_Type (C var), 168
PyExc_SystemError, 57 PyFrameObject (C type), 168
PyExc_SystemExit, 57 PyFrozenSet_Check (C function), 146
PyExc_TabError, 57 PyFrozenSet_CheckExact (C function), 146
PyExc_TimeoutError, 57 PyFrozenSet_New (C function), 146
PyExc_TypeError, 57 PyFrozenSet_Type (C var), 146
PyExc_UnboundLocalError, 57 PyFunction_AddWatcher (C function), 148
PyExc_UnicodeDecodeError, 57 PyFunction_Check (C function), 147
PyExc_UnicodeEncodeError, 57 PyFunction_ClearWatcher (C function), 148
PyExc_UnicodeError, 57 PyFunction_GetAnnotations (C function), 148
PyExc_UnicodeTranslateError, 57 PyFunction_GetClosure (C function), 148
PyExc_UnicodeWarning, 59 PyFunction_GetCode (C function), 147
PyExc_UserWarning, 59 PyFunction_GetDefaults (C function), 148
PyExc_ValueError, 57 PyFunction_GetGlobals (C function), 147
PyExc_Warning, 59 PyFunction_GetModule (C function), 148
PyExc_WindowsError, 59 PyFunction_New (C function), 147
PyExc_ZeroDivisionError, 57 PyFunction_NewWithQualName (C function),
PyException_GetArgs (C function), 55 147
PyException_GetCause (C function), 55 PyFunction_SetAnnotations (C function), 148
PyException_GetContext (C function), 55 PyFunction_SetClosure (C function), 148
PyException_GetTraceback (C function), 55 PyFunction_SetDefaults (C function), 148
PyException_SetArgs (C function), 55 PyFunction_SetVectorcall (C function), 148
PyException_SetCause (C function), 55 PyFunction_Type (C var), 147
PyException_SetContext (C function), 55 PyFunction_WatchCallback (C type), 148
PyException_SetTraceback (C function), 55 PyFunction_WatchEvent (C type), 148
PyFile_FromFd (C function), 154 PyFunctionObject (C type), 147
PyFile_GetLine (C function), 154 PyGC_Collect (C function), 278
PyFile_SetOpenCodeHook (C function), 154 PyGC_Disable (C function), 278
PyFile_WriteObject (C function), 154 PyGC_Enable (C function), 278
PyFile_WriteString (C function), 155 PyGC_IsEnabled (C function), 278
PyFloat_AS_DOUBLE (C function), 117 PyGen_Check (C function), 170
PyFloat_AsDouble (C function), 117 PyGen_CheckExact (C function), 170
PyFloat_Check (C function), 117 PyGen_New (C function), 170
PyFloat_CheckExact (C function), 117 PyGen_NewWithQualName (C function), 170

325
The Python/C API, 3.12.1

PyGen_Type (C var), 170 PyInterpreterConfig.allow_exec (C mem-


PyGenObject (C type), 170 ber), 193
PyGetSetDef (C type), 241 PyInterpreterConfig.allow_fork (C mem-
PyGetSetDef.closure (C member), 241 ber), 193
PyGetSetDef.doc (C member), 241 PyInterpreterConfig.allow_threads (C
PyGetSetDef.get (C member), 241 member), 193
PyGetSetDef.name (C member), 241 PyInterpreterConfig.check_multi_interp_extensions
PyGetSetDef.set (C member), 241 (C member), 193
PyGILState_Check (C function), 189 PyInterpreterConfig.gil (C member), 194
PyGILState_Ensure (C function), 189 PyInterpreterConfig.use_main_obmalloc
PyGILState_GetThisThreadState (C func- (C member), 193
tion), 189 PyInterpreterState (C type), 188
PyGILState_Release (C function), 189 PyInterpreterState_Clear (C function), 190
PyImport_AddModule (C function), 67 PyInterpreterState_Delete (C function), 190
PyImport_AddModuleObject (C function), 67 PyInterpreterState_Get (C function), 191
PyImport_AppendInittab (C function), 69 PyInterpreterState_GetDict (C function),
PyImport_ExecCodeModule (C function), 67 191
PyImport_ExecCodeModuleEx (C function), 68 PyInterpreterState_GetID (C function), 191
PyImport_ExecCodeModuleObject (C func- PyInterpreterState_Head (C function), 198
tion), 68 PyInterpreterState_Main (C function), 198
PyImport_ExecCodeModuleWithPathnames PyInterpreterState_New (C function), 190
(C function), 68 PyInterpreterState_Next (C function), 198
PyImport_ExtendInittab (C function), 69 PyInterpreterState_ThreadHead (C func-
PyImport_FrozenModules (C var), 69 tion), 198
PyImport_GetImporter (C function), 68 PyIter_Check (C function), 97
PyImport_GetMagicNumber (C function), 68 PyIter_Next (C function), 97
PyImport_GetMagicTag (C function), 68 PyIter_Send (C function), 98
PyImport_GetModule (C function), 68 PyList_Append (C function), 141
PyImport_GetModuleDict (C function), 68 PyList_AsTuple (C function), 142
PyImport_Import (C function), 67 PyList_Check (C function), 141
PyImport_ImportFrozenModule (C function), PyList_CheckExact (C function), 141
69 PyList_GET_ITEM (C function), 141
PyImport_ImportFrozenModuleObject (C PyList_GET_SIZE (C function), 141
function), 68 PyList_GetItem (C function), 141
PyImport_ImportModule (C function), 66 PyList_GetItem(), 8
PyImport_ImportModuleEx (C function), 66 PyList_GetSlice (C function), 141
PyImport_ImportModuleLevel (C function), 67 PyList_Insert (C function), 141
PyImport_ImportModuleLevelObject (C PyList_New (C function), 141
function), 66 PyList_Reverse (C function), 142
PyImport_ImportModuleNoBlock (C function), PyList_SET_ITEM (C function), 141
66 PyList_SetItem (C function), 141
PyImport_ReloadModule (C function), 67 PyList_SetItem(), 7
PyIndex_Check (C function), 94 PyList_SetSlice (C function), 142
PyInstanceMethod_Check (C function), 149 PyList_Size (C function), 141
PyInstanceMethod_Function (C function), 149 PyList_Sort (C function), 142
PyInstanceMethod_GET_FUNCTION (C func- PyList_Type (C var), 141
tion), 149 PyListObject (C type), 141
PyInstanceMethod_New (C function), 149 PyLong_AsDouble (C function), 115
PyInstanceMethod_Type (C var), 149 PyLong_AsLong (C function), 114
PyInterpreterConfig (C type), 193 PyLong_AsLongAndOverflow (C function), 114
PyInterpreterConfig_DEFAULT_GIL (C PyLong_AsLongLong (C function), 114
macro), 194 PyLong_AsLongLongAndOverflow (C function),
PyInterpreterConfig_OWN_GIL (C macro), 114
194 PyLong_AsSize_t (C function), 115
PyInterpreterConfig_SHARED_GIL (C PyLong_AsSsize_t (C function), 115
macro), 194 PyLong_AsUnsignedLong (C function), 115
PyInterpreterConfig.allow_daemon_threads PyLong_AsUnsignedLongLong (C function), 115
(C member), 193

326
The Python/C API, 3.12.1

PyLong_AsUnsignedLongLongMask (C func- PyMem_GetAllocator (C function), 228


tion), 115 PyMem_Malloc (C function), 225
PyLong_AsUnsignedLongMask (C function), 115 PyMem_New (C macro), 225
PyLong_AsVoidPtr (C function), 116 PyMem_RawCalloc (C function), 224
PyLong_Check (C function), 113 PyMem_RawFree (C function), 225
PyLong_CheckExact (C function), 113 PyMem_RawMalloc (C function), 224
PyLong_FromDouble (C function), 114 PyMem_RawRealloc (C function), 224
PyLong_FromLong (C function), 113 PyMem_Realloc (C function), 225
PyLong_FromLongLong (C function), 113 PyMem_Resize (C macro), 225
PyLong_FromSize_t (C function), 113 PyMem_SetAllocator (C function), 228
PyLong_FromSsize_t (C function), 113 PyMem_SetupDebugHooks (C function), 228
PyLong_FromString (C function), 114 PyMemAllocatorDomain (C type), 227
PyLong_FromUnicodeObject (C function), 114 PyMemAllocatorEx (C type), 227
PyLong_FromUnsignedLong (C function), 113 PyMember_GetOne (C function), 238
PyLong_FromUnsignedLongLong (C function), PyMember_SetOne (C function), 238
113 PyMemberDef (C type), 238
PyLong_FromVoidPtr (C function), 114 PyMemberDef.doc (C member), 238
PyLong_Type (C var), 113 PyMemberDef.flags (C member), 238
PyLongObject (C type), 113 PyMemberDef.name (C member), 238
PyMapping_Check (C function), 96 PyMemberDef.offset (C member), 238
PyMapping_DelItem (C function), 97 PyMemberDef.type (C member), 238
PyMapping_DelItemString (C function), 97 PyMemoryView_Check (C function), 165
PyMapping_GetItemString (C function), 96 PyMemoryView_FromBuffer (C function), 165
PyMapping_HasKey (C function), 97 PyMemoryView_FromMemory (C function), 165
PyMapping_HasKeyString (C function), 97 PyMemoryView_FromObject (C function), 165
PyMapping_Items (C function), 97 PyMemoryView_GET_BASE (C function), 165
PyMapping_Keys (C function), 97 PyMemoryView_GET_BUFFER (C function), 165
PyMapping_Length (C function), 96 PyMemoryView_GetContiguous (C function),
PyMapping_SetItemString (C function), 96 165
PyMapping_Size (C function), 96 PyMethod_Check (C function), 149
PyMapping_Values (C function), 97 PyMethod_Function (C function), 150
PyMappingMethods (C type), 269 PyMethod_GET_FUNCTION (C function), 150
PyMappingMethods.mp_ass_subscript (C PyMethod_GET_SELF (C function), 150
member), 269 PyMethod_New (C function), 149
PyMappingMethods.mp_length (C member), PyMethod_Self (C function), 150
269 PyMethod_Type (C var), 149
PyMappingMethods.mp_subscript (C mem- PyMethodDef (C type), 236
ber), 269 PyMethodDef.ml_doc (C member), 236
PyMarshal_ReadLastObjectFromFile (C PyMethodDef.ml_flags (C member), 236
function), 70 PyMethodDef.ml_meth (C member), 236
PyMarshal_ReadLongFromFile (C function), 70 PyMethodDef.ml_name (C member), 236
PyMarshal_ReadObjectFromFile (C function), PyMODINIT_FUNC (C macro), 4
70 PyModule_AddFunctions (C function), 159
PyMarshal_ReadObjectFromString (C func- PyModule_AddIntConstant (C function), 161
tion), 70 PyModule_AddIntMacro (C macro), 161
PyMarshal_ReadShortFromFile (C function), PyModule_AddObject (C function), 160
70 PyModule_AddObjectRef (C function), 160
PyMarshal_WriteLongToFile (C function), 69 PyModule_AddStringConstant (C function),
PyMarshal_WriteObjectToFile (C function), 161
70 PyModule_AddStringMacro (C macro), 161
PyMarshal_WriteObjectToString (C func- PyModule_AddType (C function), 161
tion), 70 PyModule_Check (C function), 155
PyMem_Calloc (C function), 225 PyModule_CheckExact (C function), 155
PyMem_Del (C function), 226 PyModule_Create (C function), 157
PYMEM_DOMAIN_MEM (C macro), 228 PyModule_Create2 (C function), 157
PYMEM_DOMAIN_OBJ (C macro), 228 PyModule_ExecDef (C function), 159
PYMEM_DOMAIN_RAW (C macro), 227 PyModule_FromDefAndSpec (C function), 159
PyMem_Free (C function), 225 PyModule_FromDefAndSpec2 (C function), 159

327
The Python/C API, 3.12.1

PyModule_GetDef (C function), 155 PyNumber_Or (C function), 93


PyModule_GetDict (C function), 155 PyNumber_Positive (C function), 92
PyModule_GetFilename (C function), 156 PyNumber_Power (C function), 92
PyModule_GetFilenameObject (C function), PyNumber_Remainder (C function), 92
155 PyNumber_Rshift (C function), 93
PyModule_GetName (C function), 155 PyNumber_Subtract (C function), 92
PyModule_GetNameObject (C function), 155 PyNumber_ToBase (C function), 94
PyModule_GetState (C function), 155 PyNumber_TrueDivide (C function), 92
PyModule_New (C function), 155 PyNumber_Xor (C function), 93
PyModule_NewObject (C function), 155 PyNumberMethods (C type), 266
PyModule_SetDocString (C function), 159 PyNumberMethods.nb_absolute (C member),
PyModule_Type (C var), 155 267
PyModuleDef (C type), 156 PyNumberMethods.nb_add (C member), 267
PyModuleDef_Init (C function), 157 PyNumberMethods.nb_and (C member), 268
PyModuleDef_Slot (C type), 158 PyNumberMethods.nb_bool (C member), 268
PyModuleDef_Slot.slot (C member), 158 PyNumberMethods.nb_divmod (C member), 267
PyModuleDef_Slot.value (C member), 158 PyNumberMethods.nb_float (C member), 268
PyModuleDef.m_base (C member), 156 PyNumberMethods.nb_floor_divide (C mem-
PyModuleDef.m_clear (C member), 156 ber), 268
PyModuleDef.m_doc (C member), 156 PyNumberMethods.nb_index (C member), 268
PyModuleDef.m_free (C member), 157 PyNumberMethods.nb_inplace_add (C mem-
PyModuleDef.m_methods (C member), 156 ber), 268
PyModuleDef.m_name (C member), 156 PyNumberMethods.nb_inplace_and (C mem-
PyModuleDef.m_size (C member), 156 ber), 268
PyModuleDef.m_slots (C member), 156 PyNumberMethods.nb_inplace_floor_divide
PyModuleDef.m_slots.m_reload (C member), (C member), 268
156 PyNumberMethods.nb_inplace_lshift (C
PyModuleDef.m_traverse (C member), 156 member), 268
PyNumber_Absolute (C function), 92 PyNumberMethods.nb_inplace_matrix_multiply
PyNumber_Add (C function), 92 (C member), 268
PyNumber_And (C function), 93 PyNumberMethods.nb_inplace_multiply (C
PyNumber_AsSsize_t (C function), 94 member), 268
PyNumber_Check (C function), 92 PyNumberMethods.nb_inplace_or (C mem-
PyNumber_Divmod (C function), 92 ber), 268
PyNumber_Float (C function), 94 PyNumberMethods.nb_inplace_power (C
PyNumber_FloorDivide (C function), 92 member), 268
PyNumber_Index (C function), 94 PyNumberMethods.nb_inplace_remainder
PyNumber_InPlaceAdd (C function), 93 (C member), 268
PyNumber_InPlaceAnd (C function), 94 PyNumberMethods.nb_inplace_rshift (C
PyNumber_InPlaceFloorDivide (C function), member), 268
93 PyNumberMethods.nb_inplace_subtract (C
PyNumber_InPlaceLshift (C function), 94 member), 268
PyNumber_InPlaceMatrixMultiply (C func- PyNumberMethods.nb_inplace_true_divide
tion), 93 (C member), 268
PyNumber_InPlaceMultiply (C function), 93 PyNumberMethods.nb_inplace_xor (C mem-
PyNumber_InPlaceOr (C function), 94 ber), 268
PyNumber_InPlacePower (C function), 93 PyNumberMethods.nb_int (C member), 268
PyNumber_InPlaceRemainder (C function), 93 PyNumberMethods.nb_invert (C member), 268
PyNumber_InPlaceRshift (C function), 94 PyNumberMethods.nb_lshift (C member), 268
PyNumber_InPlaceSubtract (C function), 93 PyNumberMethods.nb_matrix_multiply (C
PyNumber_InPlaceTrueDivide (C function), 93 member), 268
PyNumber_InPlaceXor (C function), 94 PyNumberMethods.nb_multiply (C member),
PyNumber_Invert (C function), 93 267
PyNumber_Long (C function), 94 PyNumberMethods.nb_negative (C member),
PyNumber_Lshift (C function), 93 267
PyNumber_MatrixMultiply (C function), 92 PyNumberMethods.nb_or (C member), 268
PyNumber_Multiply (C function), 92 PyNumberMethods.nb_positive (C member),
PyNumber_Negative (C function), 92 267

328
The Python/C API, 3.12.1

PyNumberMethods.nb_power (C member), 267 PyObject_GetBuffer (C function), 103


PyNumberMethods.nb_remainder (C member), PyObject_GetItem (C function), 86
267 PyObject_GetItemData (C function), 87
PyNumberMethods.nb_reserved (C member), PyObject_GetIter (C function), 86
268 PyObject_GetTypeData (C function), 87
PyNumberMethods.nb_rshift (C member), 268 PyObject_HasAttr (C function), 83
PyNumberMethods.nb_subtract (C member), PyObject_HasAttrString (C function), 83
267 PyObject_Hash (C function), 86
PyNumberMethods.nb_true_divide (C mem- PyObject_HashNotImplemented (C function),
ber), 268 86
PyNumberMethods.nb_xor (C member), 268 PyObject_HEAD (C macro), 234
PyObject (C type), 234 PyObject_HEAD_INIT (C macro), 235
PyObject_AsCharBuffer (C function), 104 PyObject_Init (C function), 233
PyObject_ASCII (C function), 85 PyObject_InitVar (C function), 233
PyObject_AsFileDescriptor (C function), 154 PyObject_IS_GC (C function), 276
PyObject_AsReadBuffer (C function), 105 PyObject_IsInstance (C function), 85
PyObject_AsWriteBuffer (C function), 105 PyObject_IsSubclass (C function), 85
PyObject_Bytes (C function), 85 PyObject_IsTrue (C function), 86
PyObject_Call (C function), 89 PyObject_Length (C function), 86
PyObject_CallFunction (C function), 90 PyObject_LengthHint (C function), 86
PyObject_CallFunctionObjArgs (C function), PyObject_Malloc (C function), 226
90 PyObject_New (C macro), 233
PyObject_CallMethod (C function), 90 PyObject_NewVar (C macro), 233
PyObject_CallMethodNoArgs (C function), 91 PyObject_Not (C function), 86
PyObject_CallMethodObjArgs (C function), 91 PyObject._ob_next (C member), 248
PyObject_CallMethodOneArg (C function), 91 PyObject._ob_prev (C member), 248
PyObject_CallNoArgs (C function), 90 PyObject_Print (C function), 83
PyObject_CallObject (C function), 90 PyObject_Realloc (C function), 226
PyObject_Calloc (C function), 226 PyObject_Repr (C function), 85
PyObject_CallOneArg (C function), 90 PyObject_RichCompare (C function), 84
PyObject_CheckBuffer (C function), 103 PyObject_RichCompareBool (C function), 85
PyObject_CheckReadBuffer (C function), 105 PyObject_SetArenaAllocator (C function),
PyObject_ClearWeakRefs (C function), 166 230
PyObject_CopyData (C function), 104 PyObject_SetAttr (C function), 84
PyObject_Del (C function), 233 PyObject_SetAttrString (C function), 84
PyObject_DelAttr (C function), 84 PyObject_SetItem (C function), 86
PyObject_DelAttrString (C function), 84 PyObject_Size (C function), 86
PyObject_DelItem (C function), 86 PyObject_Str (C function), 85
PyObject_Dir (C function), 86 PyObject_Type (C function), 86
PyObject_Format (C function), 85 PyObject_TypeCheck (C function), 86
PyObject_Free (C function), 226 PyObject_VAR_HEAD (C macro), 234
PyObject_GC_Del (C function), 277 PyObject_Vectorcall (C function), 91
PyObject_GC_IsFinalized (C function), 277 PyObject_VectorcallDict (C function), 91
PyObject_GC_IsTracked (C function), 276 PyObject_VectorcallMethod (C function), 91
PyObject_GC_New (C macro), 276 PyObjectArenaAllocator (C type), 230
PyObject_GC_NewVar (C macro), 276 PyObject.ob_refcnt (C member), 247
PyObject_GC_Resize (C function), 276 PyObject.ob_type (C member), 247
PyObject_GC_Track (C function), 276 PyOS_AfterFork (C function), 62
PyObject_GC_UnTrack (C function), 277 PyOS_AfterFork_Child (C function), 62
PyObject_GenericGetAttr (C function), 84 PyOS_AfterFork_Parent (C function), 61
PyObject_GenericGetDict (C function), 84 PyOS_BeforeFork (C function), 61
PyObject_GenericSetAttr (C function), 84 PyOS_CheckStack (C function), 62
PyObject_GenericSetDict (C function), 84 PyOS_double_to_string (C function), 77
PyObject_GetAIter (C function), 87 PyOS_FSPath (C function), 61
PyObject_GetArenaAllocator (C function), PyOS_getsig (C function), 62
230 PyOS_InputHook (C var), 40
PyObject_GetAttr (C function), 83 PyOS_ReadlineFunctionPointer (C var), 40
PyObject_GetAttrString (C function), 84 PyOS_setsig (C function), 62

329
The Python/C API, 3.12.1

PyOS_snprintf (C function), 77 PySequence_Fast_ITEMS (C function), 96


PyOS_stricmp (C function), 78 PySequence_GetItem (C function), 95
PyOS_string_to_double (C function), 77 PySequence_GetItem(), 8
PyOS_strnicmp (C function), 78 PySequence_GetSlice (C function), 95
PyOS_vsnprintf (C function), 77 PySequence_Index (C function), 95
PyPreConfig (C type), 204 PySequence_InPlaceConcat (C function), 95
PyPreConfig_InitIsolatedConfig (C func- PySequence_InPlaceRepeat (C function), 95
tion), 204 PySequence_ITEM (C function), 96
PyPreConfig_InitPythonConfig (C function), PySequence_Length (C function), 95
204 PySequence_List (C function), 96
PyPreConfig.allocator (C member), 204 PySequence_Repeat (C function), 95
PyPreConfig.coerce_c_locale (C member), PySequence_SetItem (C function), 95
204 PySequence_SetSlice (C function), 95
PyPreConfig.coerce_c_locale_warn (C PySequence_Size (C function), 95
member), 205 PySequence_Tuple (C function), 96
PyPreConfig.configure_locale (C member), PySequenceMethods (C type), 269
204 PySequenceMethods.sq_ass_item (C mem-
PyPreConfig.dev_mode (C member), 205 ber), 269
PyPreConfig.isolated (C member), 205 PySequenceMethods.sq_concat (C member),
PyPreConfig.legacy_windows_fs_encoding 269
(C member), 205 PySequenceMethods.sq_contains (C mem-
PyPreConfig.parse_argv (C member), 205 ber), 269
PyPreConfig.use_environment (C member), PySequenceMethods.sq_inplace_concat (C
205 member), 269
PyPreConfig.utf8_mode (C member), 205 PySequenceMethods.sq_inplace_repeat (C
PyProperty_Type (C var), 163 member), 270
PyRun_AnyFile (C function), 39 PySequenceMethods.sq_item (C member), 269
PyRun_AnyFileEx (C function), 39 PySequenceMethods.sq_length (C member),
PyRun_AnyFileExFlags (C function), 39 269
PyRun_AnyFileFlags (C function), 39 PySequenceMethods.sq_repeat (C member),
PyRun_File (C function), 41 269
PyRun_FileEx (C function), 41 PySet_Add (C function), 146
PyRun_FileExFlags (C function), 41 PySet_Check (C function), 146
PyRun_FileFlags (C function), 41 PySet_CheckExact (C function), 146
PyRun_InteractiveLoop (C function), 40 PySet_Clear (C function), 147
PyRun_InteractiveLoopFlags (C function), 40 PySet_Contains (C function), 146
PyRun_InteractiveOne (C function), 40 PySet_Discard (C function), 147
PyRun_InteractiveOneFlags (C function), 40 PySet_GET_SIZE (C function), 146
PyRun_SimpleFile (C function), 40 PySet_New (C function), 146
PyRun_SimpleFileEx (C function), 40 PySet_Pop (C function), 147
PyRun_SimpleFileExFlags (C function), 40 PySet_Size (C function), 146
PyRun_SimpleString (C function), 40 PySet_Type (C var), 146
PyRun_SimpleStringFlags (C function), 40 PySetObject (C type), 145
PyRun_String (C function), 41 PySignal_SetWakeupFd (C function), 54
PyRun_StringFlags (C function), 41 PySlice_AdjustIndices (C function), 164
PySendResult (C type), 98 PySlice_Check (C function), 163
PySeqIter_Check (C function), 162 PySlice_GetIndices (C function), 163
PySeqIter_New (C function), 162 PySlice_GetIndicesEx (C function), 163
PySeqIter_Type (C var), 162 PySlice_New (C function), 163
PySequence_Check (C function), 95 PySlice_Type (C var), 163
PySequence_Concat (C function), 95 PySlice_Unpack (C function), 164
PySequence_Contains (C function), 95 PyState_AddModule (C function), 162
PySequence_Count (C function), 95 PyState_FindModule (C function), 162
PySequence_DelItem (C function), 95 PyState_RemoveModule (C function), 162
PySequence_DelSlice (C function), 95 PyStatus (C type), 203
PySequence_Fast (C function), 96 PyStatus_Error (C function), 203
PySequence_Fast_GET_ITEM (C function), 96 PyStatus_Exception (C function), 203
PySequence_Fast_GET_SIZE (C function), 96 PyStatus_Exit (C function), 203

330
The Python/C API, 3.12.1

PyStatus_IsError (C function), 203 PEP 362, 282, 289


PyStatus_IsExit (C function), 203 PEP 383, 130
PyStatus_NoMemory (C function), 203 PEP 387, 13
PyStatus_Ok (C function), 203 PEP 393, 123
PyStatus.err_msg (C member), 203 PEP 411, 290
PyStatus.exitcode (C member), 203 PEP 420, 285, 288, 289
PyStatus.func (C member), 203 PEP 432, 221
PyStructSequence_Desc (C type), 140 PEP 442, 265
PyStructSequence_Desc.doc (C member), 140 PEP 443, 285
PyStructSequence_Desc.fields (C member), PEP 451, 158, 285
140 PEP 483, 285
PyStructSequence_Desc.n_in_sequence (C PEP 484, 281, 285, 292
member), 140 PEP 489, 194
PyStructSequence_Desc.name (C member), PEP 492, 282, 283
140 PEP 498, 284
PyStructSequence_Field (C type), 140 PEP 519, 289
PyStructSequence_Field.doc (C member), PEP 523, 191, 192
140 PEP 525, 282
PyStructSequence_Field.name (C member), PEP 526, 281, 292
140 PEP 528, 180, 212
PyStructSequence_GET_ITEM (C function), 140 PEP 529, 130, 179
PyStructSequence_GetItem (C function), 140 PEP 538, 219
PyStructSequence_InitType (C function), 139 PEP 539, 199
PyStructSequence_InitType2 (C function), PEP 540, 219
139 PEP 552, 209
PyStructSequence_New (C function), 140 PEP 554, 195
PyStructSequence_NewType (C function), 139 PEP 578, 65
PyStructSequence_SET_ITEM (C function), 140 PEP 585, 285
PyStructSequence_SetItem (C function), 140 PEP 587, 201
PyStructSequence_UnnamedField (C var), PEP 590, 88
140 PEP 623, 123
PySys_AddAuditHook (C function), 65 PEP 634, 256
PySys_AddWarnOption (C function), 64 PEP 3116, 292
PySys_AddWarnOptionUnicode (C function), 64 PEP 3119, 85
PySys_AddXOption (C function), 65 PEP 3121, 156
PySys_Audit (C function), 65 PEP 3147, 68
PySys_FormatStderr (C function), 65 PEP 3151, 58
PySys_FormatStdout (C function), 64 PEP 3155, 290
PySys_GetObject (C function), 64 PYTHONCOERCECLOCALE, 219
PySys_GetXOptions (C function), 65 PYTHONDEBUG, 178, 213
PySys_ResetWarnOptions (C function), 64 PYTHONDEVMODE, 209
PySys_SetArgv (C function), 185 PYTHONDONTWRITEBYTECODE, 178, 216
PySys_SetArgv(), 181 PYTHONDUMPREFS, 210, 248
PySys_SetArgvEx (C function), 184 PYTHONEXECUTABLE, 214
PySys_SetArgvEx(), 181 PYTHONFAULTHANDLER, 210
PySys_SetObject (C function), 64 PYTHONHASHSEED, 179, 211
PySys_SetPath (C function), 64 PYTHONHOME, 11, 179, 185, 211
PySys_WriteStderr (C function), 64 Pythonic, 290
PySys_WriteStdout (C function), 64 PYTHONINSPECT, 179, 211
Python 3000, 290 PYTHONINTMAXSTRDIGITS, 211
Python PYTHONIOENCODING, 182, 215
PEP 1, 289 PYTHONLEGACYWINDOWSFSENCODING, 179, 205
PEP 7, 3, 6 PYTHONLEGACYWINDOWSSTDIO, 180, 212
PEP 238, 42, 285 PYTHONMALLOC, 224, 227, 229
PEP 278, 292 PYTHONMALLOC`
PEP 302, 285, 287 ``PYTHONMALLOC=malloc`, 230
PEP 343, 283 PYTHONMALLOCSTATS, 212, 224
PEP 353, 9 PYTHONNODEBUGRANGES, 209

331
The Python/C API, 3.12.1

PYTHONNOUSERSITE, 180, 216 PyTrace_EXCEPTION (C var), 197


PYTHONOPTIMIZE, 180, 213 PyTrace_LINE (C var), 197
PYTHONPATH, 11, 179, 212 PyTrace_OPCODE (C var), 197
PYTHONPERFSUPPORT, 215 PyTrace_RETURN (C var), 197
PYTHONPLATLIBDIR, 212 PyTraceMalloc_Track (C function), 231
PYTHONPROFILEIMPORTTIME, 211 PyTraceMalloc_Untrack (C function), 231
PYTHONPYCACHEPREFIX, 214 PyTuple_Check (C function), 138
PYTHONSAFEPATH, 208 PyTuple_CheckExact (C function), 138
PYTHONTRACEMALLOC, 215 PyTuple_GET_ITEM (C function), 139
PYTHONUNBUFFERED, 180, 209 PyTuple_GET_SIZE (C function), 139
PYTHONUTF8, 205, 219 PyTuple_GetItem (C function), 139
PYTHONVERBOSE, 181, 216 PyTuple_GetSlice (C function), 139
PYTHONWARNINGS, 216 PyTuple_New (C function), 138
PyThread_create_key (C function), 200 PyTuple_Pack (C function), 138
PyThread_delete_key (C function), 200 PyTuple_SET_ITEM (C function), 139
PyThread_delete_key_value (C function), 200 PyTuple_SetItem (C function), 139
PyThread_get_key_value (C function), 200 PyTuple_SetItem(), 7
PyThread_ReInitTLS (C function), 200 PyTuple_Size (C function), 139
PyThread_set_key_value (C function), 200 PyTuple_Type (C var), 138
PyThread_tss_alloc (C function), 199 PyTupleObject (C type), 138
PyThread_tss_create (C function), 200 PyType_AddWatcher (C function), 108
PyThread_tss_delete (C function), 200 PyType_Check (C function), 107
PyThread_tss_free (C function), 199 PyType_CheckExact (C function), 107
PyThread_tss_get (C function), 200 PyType_ClearCache (C function), 107
PyThread_tss_is_created (C function), 200 PyType_ClearWatcher (C function), 108
PyThread_tss_set (C function), 200 PyType_FromMetaclass (C function), 110
PyThreadState, 186 PyType_FromModuleAndSpec (C function), 111
PyThreadState (C type), 188 PyType_FromSpec (C function), 111
PyThreadState_Clear (C function), 190 PyType_FromSpecWithBases (C function), 111
PyThreadState_Delete (C function), 190 PyType_GenericAlloc (C function), 109
PyThreadState_DeleteCurrent (C function), PyType_GenericNew (C function), 109
190 PyType_GetDict (C function), 108
PyThreadState_EnterTracing (C function), PyType_GetFlags (C function), 107
191 PyType_GetModule (C function), 109
PyThreadState_Get (C function), 188 PyType_GetModuleByDef (C function), 110
PyThreadState_GetDict (C function), 192 PyType_GetModuleState (C function), 109
PyThreadState_GetFrame (C function), 190 PyType_GetName (C function), 109
PyThreadState_GetID (C function), 190 PyType_GetQualName (C function), 109
PyThreadState_GetInterpreter (C function), PyType_GetSlot (C function), 109
191 PyType_GetTypeDataSize (C function), 87
PyThreadState_LeaveTracing (C function), PyType_HasFeature (C function), 108
191 PyType_IS_GC (C function), 108
PyThreadState_New (C function), 190 PyType_IsSubtype (C function), 108
PyThreadState_Next (C function), 198 PyType_Modified (C function), 108
PyThreadState_SetAsyncExc (C function), 192 PyType_Ready (C function), 109
PyThreadState_Swap (C function), 188 PyType_Slot (C type), 112
PyThreadState.interp (C member), 188 PyType_Slot.pfunc (C member), 112
PyTime_Check (C function), 173 PyType_Slot.slot (C member), 112
PyTime_CheckExact (C function), 173 PyType_Spec (C type), 111
PyTime_FromTime (C function), 173 PyType_Spec.basicsize (C member), 111
PyTime_FromTimeAndFold (C function), 173 PyType_Spec.flags (C member), 112
PyTimeZone_FromOffset (C function), 174 PyType_Spec.itemsize (C member), 111
PyTimeZone_FromOffsetAndName (C function), PyType_Spec.name (C member), 111
174 PyType_Spec.slots (C member), 112
PyTrace_C_CALL (C var), 197 PyType_Type (C var), 107
PyTrace_C_EXCEPTION (C var), 197 PyType_Watch (C function), 108
PyTrace_C_RETURN (C var), 197 PyType_WatchCallback (C type), 108
PyTrace_CALL (C var), 197 PyTypeObject (C type), 107

332
The Python/C API, 3.12.1

PyTypeObject.tp_alloc (C member), 263 PyTZInfo_Check (C function), 173


PyTypeObject.tp_as_async (C member), 250 PyTZInfo_CheckExact (C function), 173
PyTypeObject.tp_as_buffer (C member), 252 PyUnicode_1BYTE_DATA (C function), 124
PyTypeObject.tp_as_mapping (C member), PyUnicode_1BYTE_KIND (C macro), 124
251 PyUnicode_2BYTE_DATA (C function), 124
PyTypeObject.tp_as_number (C member), 251 PyUnicode_2BYTE_KIND (C macro), 124
PyTypeObject.tp_as_sequence (C member), PyUnicode_4BYTE_DATA (C function), 124
251 PyUnicode_4BYTE_KIND (C macro), 124
PyTypeObject.tp_base (C member), 261 PyUnicode_AsASCIIString (C function), 135
PyTypeObject.tp_bases (C member), 264 PyUnicode_AsCharmapString (C function), 136
PyTypeObject.tp_basicsize (C member), 248 PyUnicode_AsEncodedString (C function), 132
PyTypeObject.tp_cache (C member), 264 PyUnicode_AsLatin1String (C function), 135
PyTypeObject.tp_call (C member), 251 PyUnicode_AsMBCSString (C function), 136
PyTypeObject.tp_clear (C member), 257 PyUnicode_AsRawUnicodeEscapeString (C
PyTypeObject.tp_dealloc (C member), 249 function), 135
PyTypeObject.tp_del (C member), 265 PyUnicode_AsUCS4 (C function), 129
PyTypeObject.tp_descr_get (C member), 261 PyUnicode_AsUCS4Copy (C function), 129
PyTypeObject.tp_descr_set (C member), 261 PyUnicode_AsUnicodeEscapeString (C func-
PyTypeObject.tp_dict (C member), 261 tion), 135
PyTypeObject.tp_dictoffset (C member), PyUnicode_AsUTF8 (C function), 133
262 PyUnicode_AsUTF8AndSize (C function), 132
PyTypeObject.tp_doc (C member), 256 PyUnicode_AsUTF8String (C function), 132
PyTypeObject.tp_finalize (C member), 265 PyUnicode_AsUTF16String (C function), 134
PyTypeObject.tp_flags (C member), 253 PyUnicode_AsUTF32String (C function), 133
PyTypeObject.tp_free (C member), 263 PyUnicode_AsWideChar (C function), 131
PyTypeObject.tp_getattr (C member), 250 PyUnicode_AsWideCharString (C function),
PyTypeObject.tp_getattro (C member), 252 131
PyTypeObject.tp_getset (C member), 260 PyUnicode_Check (C function), 123
PyTypeObject.tp_hash (C member), 251 PyUnicode_CheckExact (C function), 123
PyTypeObject.tp_init (C member), 262 PyUnicode_Compare (C function), 137
PyTypeObject.tp_is_gc (C member), 264 PyUnicode_CompareWithASCIIString (C
PyTypeObject.tp_itemsize (C member), 248 function), 138
PyTypeObject.tp_iter (C member), 260 PyUnicode_Concat (C function), 137
PyTypeObject.tp_iternext (C member), 260 PyUnicode_Contains (C function), 138
PyTypeObject.tp_members (C member), 260 PyUnicode_CopyCharacters (C function), 129
PyTypeObject.tp_methods (C member), 260 PyUnicode_Count (C function), 137
PyTypeObject.tp_mro (C member), 264 PyUnicode_DATA (C function), 124
PyTypeObject.tp_name (C member), 248 PyUnicode_Decode (C function), 132
PyTypeObject.tp_new (C member), 263 PyUnicode_DecodeASCII (C function), 135
PyTypeObject.tp_repr (C member), 250 PyUnicode_DecodeCharmap (C function), 136
PyTypeObject.tp_richcompare (C member), PyUnicode_DecodeFSDefault (C function), 131
258 PyUnicode_DecodeFSDefaultAndSize (C
PyTypeObject.tp_setattr (C member), 250 function), 131
PyTypeObject.tp_setattro (C member), 252 PyUnicode_DecodeLatin1 (C function), 135
PyTypeObject.tp_str (C member), 252 PyUnicode_DecodeLocale (C function), 130
PyTypeObject.tp_subclasses (C member), PyUnicode_DecodeLocaleAndSize (C func-
264 tion), 130
PyTypeObject.tp_traverse (C member), 257 PyUnicode_DecodeMBCS (C function), 136
PyTypeObject.tp_vectorcall (C member), PyUnicode_DecodeMBCSStateful (C function),
266 136
PyTypeObject.tp_vectorcall_offset (C PyUnicode_DecodeRawUnicodeEscape (C
member), 250 function), 135
PyTypeObject.tp_version_tag (C member), PyUnicode_DecodeUnicodeEscape (C func-
265 tion), 135
PyTypeObject.tp_watched (C member), 266 PyUnicode_DecodeUTF7 (C function), 134
PyTypeObject.tp_weaklist (C member), 264 PyUnicode_DecodeUTF7Stateful (C function),
PyTypeObject.tp_weaklistoffset (C mem- 134
ber), 259 PyUnicode_DecodeUTF8 (C function), 132

333
The Python/C API, 3.12.1

PyUnicode_DecodeUTF8Stateful (C function), PyUnicodeDecodeError_GetObject (C func-


132 tion), 56
PyUnicode_DecodeUTF16 (C function), 134 PyUnicodeDecodeError_GetReason (C func-
PyUnicode_DecodeUTF16Stateful (C func- tion), 56
tion), 134 PyUnicodeDecodeError_GetStart (C func-
PyUnicode_DecodeUTF32 (C function), 133 tion), 56
PyUnicode_DecodeUTF32Stateful (C func- PyUnicodeDecodeError_SetEnd (C function),
tion), 133 56
PyUnicode_EncodeCodePage (C function), 136 PyUnicodeDecodeError_SetReason (C func-
PyUnicode_EncodeFSDefault (C function), 131 tion), 56
PyUnicode_EncodeLocale (C function), 130 PyUnicodeDecodeError_SetStart (C func-
PyUnicode_Fill (C function), 129 tion), 56
PyUnicode_Find (C function), 137 PyUnicodeEncodeError_GetEncoding (C
PyUnicode_FindChar (C function), 137 function), 56
PyUnicode_Format (C function), 138 PyUnicodeEncodeError_GetEnd (C function),
PyUnicode_FromEncodedObject (C function), 56
128 PyUnicodeEncodeError_GetObject (C func-
PyUnicode_FromFormat (C function), 127 tion), 56
PyUnicode_FromFormatV (C function), 128 PyUnicodeEncodeError_GetReason (C func-
PyUnicode_FromKindAndData (C function), 126 tion), 56
PyUnicode_FromObject (C function), 128 PyUnicodeEncodeError_GetStart (C func-
PyUnicode_FromString (C function), 127 tion), 56
PyUnicode_FromStringAndSize (C function), PyUnicodeEncodeError_SetEnd (C function),
126 56
PyUnicode_FromWideChar (C function), 131 PyUnicodeEncodeError_SetReason (C func-
PyUnicode_FSConverter (C function), 130 tion), 56
PyUnicode_FSDecoder (C function), 131 PyUnicodeEncodeError_SetStart (C func-
PyUnicode_GET_LENGTH (C function), 124 tion), 56
PyUnicode_GetLength (C function), 129 PyUnicodeObject (C type), 123
PyUnicode_InternFromString (C function), PyUnicodeTranslateError_GetEnd (C func-
138 tion), 56
PyUnicode_InternInPlace (C function), 138 PyUnicodeTranslateError_GetObject (C
PyUnicode_IsIdentifier (C function), 125 function), 56
PyUnicode_Join (C function), 137 PyUnicodeTranslateError_GetReason (C
PyUnicode_KIND (C function), 124 function), 56
PyUnicode_MAX_CHAR_VALUE (C function), 124 PyUnicodeTranslateError_GetStart (C
PyUnicode_New (C function), 126 function), 56
PyUnicode_READ (C function), 124 PyUnicodeTranslateError_SetEnd (C func-
PyUnicode_READ_CHAR (C function), 124 tion), 56
PyUnicode_ReadChar (C function), 129 PyUnicodeTranslateError_SetReason (C
PyUnicode_READY (C function), 124 function), 56
PyUnicode_Replace (C function), 137 PyUnicodeTranslateError_SetStart (C
PyUnicode_RichCompare (C function), 138 function), 56
PyUnicode_Split (C function), 137 PyUnstable, 13
PyUnicode_Splitlines (C function), 137 PyUnstable_Code_GetExtra (C function), 153
PyUnicode_Substring (C function), 129 PyUnstable_Code_New (C function), 151
PyUnicode_Tailmatch (C function), 137 PyUnstable_Code_NewWithPosOnlyArgs (C
PyUnicode_Translate (C function), 136 function), 151
PyUnicode_Type (C var), 123 PyUnstable_Code_SetExtra (C function), 153
PyUnicode_WRITE (C function), 124 PyUnstable_Eval_RequestCodeExtraIndex
PyUnicode_WriteChar (C function), 129 (C function), 153
PyUnicodeDecodeError_Create (C function), PyUnstable_Exc_PrepReraiseStar (C func-
56 tion), 55
PyUnicodeDecodeError_GetEncoding (C PyUnstable_GC_VisitObjects (C function),
function), 56 278
PyUnicodeDecodeError_GetEnd (C function), PyUnstable_InterpreterFrame_GetCode (C
56 function), 169
PyUnstable_InterpreterFrame_GetLasti

334
The Python/C API, 3.12.1

(C function), 169 sequence -- , 290


PyUnstable_InterpreterFrame_GetLine (C set
function), 169 object -- , 145
PyUnstable_Long_CompactValue (C function), set comprehension -- , 291
116 set_all(), 8
PyUnstable_Long_IsCompact (C function), 116 setattrfunc (C type), 272
PyUnstable_Object_GC_NewWithExtraData setattrofunc (C type), 272
(C function), 276 setswitchinterval() ( sys ), 186
PyUnstable_PerfMapState_Fini (C function), SIGINT, 54
81 signal
PyUnstable_PerfMapState_Init (C function), module, 54
80 single dispatch -- , 291
PyUnstable_Type_AssignVersionTag (C SIZE_MAX, 115
function), 110 slice -- , 291
PyUnstable_WritePerfMapEntry (C function), special method -- , 291
80 ssizeargfunc (C type), 273
PyVarObject (C type), 234 ssizeobjargproc (C type), 273
PyVarObject_HEAD_INIT (C macro), 235 statement -- , 291
PyVarObject.ob_size (C member), 248 static type checker -- ,
PyVectorcall_Call (C function), 89 291
PyVectorcall_Function (C function), 89 stderr ( sys ), 194, 195
PyVectorcall_NARGS (C function), 89 stdin
PyWeakref_Check (C function), 165 stdout sdterr, 182
PyWeakref_CheckProxy (C function), 165 stdin ( sys ), 194, 195
PyWeakref_CheckRef (C function), 165 stdout
PyWeakref_GET_OBJECT (C function), 166 sdterr, stdin, 182
PyWeakref_GetObject (C function), 166 stdout ( sys ), 194, 195
PyWeakref_NewProxy (C function), 166 strerror(), 49
PyWeakref_NewRef (C function), 165 string
PyWideStringList (C type), 202 PyObject_Str (C ), 85
PyWideStringList_Append (C function), 202 strong reference -- , 291
PyWideStringList_Insert (C function), 202 structmember.h, 241
PyWideStringList.items (C member), 202 sum_list(), 9
PyWideStringList.length (C member), 202 sum_sequence(), 9, 10
PyWrapper_New (C function), 163 sys
module, 11, 181, 194, 195
Q SystemError ( ), 155
qualified name -- , 290
T
R T_BOOL, 241
READ_RESTRICTED, 239 T_BYTE, 241
READONLY, 239 T_CHAR, 241
realloc(), 223 T_DOUBLE, 241
reference count -- , 290 T_FLOAT, 241
regular package -- , 290 T_INT, 241
releasebufferproc (C type), 273 T_LONG, 241
repr T_LONGLONG, 241
, 85, 250 T_NONE (C macro), 241
reprfunc (C type), 272 T_OBJECT (C macro), 241
RESTRICTED, 239 T_OBJECT_EX, 241
richcmpfunc (C type), 272 T_PYSSIZET, 241
T_SHORT, 241
S T_STRING, 241
sdterr T_STRING_INPLACE, 241
stdin stdout, 182 T_UBYTE, 241
sendfunc (C type), 273 T_UINT, 241
sequence T_ULONG, 241
object -- , 120 T_ULONGULONG, 241

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

You might also like