Debian Codegraph @

Doc/c-api/intro.rst

raw
1 .. highlight:: c
2
3
4 .. _api-intro:
5
6 ************
7 Introduction
8 ************
9
10 The Application Programmer's Interface to Python gives C and C++ programmers
11 access to the Python interpreter at a variety of levels. The API is equally
12 usable from C++, but for brevity it is generally referred to as the Python/C
13 API. There are two fundamentally different reasons for using the Python/C API.
14 The first reason is to write *extension modules* for specific purposes; these
15 are C modules that extend the Python interpreter. This is probably the most
16 common use. The second reason is to use Python as a component in a larger
17 application; this technique is generally referred to as :dfn:`embedding` Python
18 in an application.
19
20 Writing an extension module is a relatively well-understood process, where a
21 "cookbook" approach works well. There are several tools that automate the
22 process to some extent. While people have embedded Python in other
23 applications since its early existence, the process of embedding Python is
24 less straightforward than writing an extension.
25
26 Many API functions are useful independent of whether you're embedding or
27 extending Python; moreover, most applications that embed Python will need to
28 provide a custom extension as well, so it's probably a good idea to become
29 familiar with writing an extension before attempting to embed Python in a real
30 application.
31
32
33 Coding standards
34 ================
35
36 If you're writing C code for inclusion in CPython, you **must** follow the
37 guidelines and standards defined in :PEP:`7`. These guidelines apply
38 regardless of the version of Python you are contributing to. Following these
39 conventions is not necessary for your own third party extension modules,
40 unless you eventually expect to contribute them to Python.
41
42
43 .. _api-includes:
44
45 Include Files
46 =============
47
48 All function, type and macro definitions needed to use the Python/C API are
49 included in your code by the following line::
50
51 #define PY_SSIZE_T_CLEAN
52 #include <Python.h>
53
54 This implies inclusion of the following standard headers: ``<stdio.h>``,
55 ``<string.h>``, ``<errno.h>``, ``<limits.h>``, ``<assert.h>`` and ``<stdlib.h>``
56 (if available).
57
58 .. note::
59
60 Since Python may define some pre-processor definitions which affect the standard
61 headers on some systems, you *must* include :file:`Python.h` before any standard
62 headers are included.
63
64 It is recommended to always define ``PY_SSIZE_T_CLEAN`` before including
65 ``Python.h``. See :ref:`arg-parsing` for a description of this macro.
66
67 All user visible names defined by Python.h (except those defined by the included
68 standard headers) have one of the prefixes ``Py`` or ``_Py``. Names beginning
69 with ``_Py`` are for internal use by the Python implementation and should not be
70 used by extension writers. Structure member names do not have a reserved prefix.
71
72 .. note::
73
74 User code should never define names that begin with ``Py`` or ``_Py``. This
75 confuses the reader, and jeopardizes the portability of the user code to
76 future Python versions, which may define additional names beginning with one
77 of these prefixes.
78
79 The header files are typically installed with Python. On Unix, these are
80 located in the directories :file:`{prefix}/include/pythonversion/` and
81 :file:`{exec_prefix}/include/pythonversion/`, where :option:`prefix <--prefix>` and
82 :option:`exec_prefix <--exec-prefix>` are defined by the corresponding parameters to Python's
83 :program:`configure` script and *version* is
84 ``'%d.%d' % sys.version_info[:2]``. On Windows, the headers are installed
85 in :file:`{prefix}/include`, where ``prefix`` is the installation
86 directory specified to the installer.
87
88 To include the headers, place both directories (if different) on your compiler's
89 search path for includes. Do *not* place the parent directories on the search
90 path and then use ``#include <pythonX.Y/Python.h>``; this will break on
91 multi-platform builds since the platform independent headers under
92 :option:`prefix <--prefix>` include the platform specific headers from
93 :option:`exec_prefix <--exec-prefix>`.
94
95 C++ users should note that although the API is defined entirely using C, the
96 header files properly declare the entry points to be ``extern "C"``. As a result,
97 there is no need to do anything special to use the API from C++.
98
99
100 Useful macros
101 =============
102
103 Several useful macros are defined in the Python header files. Many are
104 defined closer to where they are useful (e.g. :c:macro:`Py_RETURN_NONE`).
105 Others of a more general utility are defined here. This is not necessarily a
106 complete listing.
107
108 .. c:macro:: PyMODINIT_FUNC
109
110 Declare an extension module ``PyInit`` initialization function. The function
111 return type is :c:expr:`PyObject*`. The macro declares any special linkage
112 declarations required by the platform, and for C++ declares the function as
113 ``extern "C"``.
114
115 The initialization function must be named :samp:`PyInit_{name}`, where
116 *name* is the name of the module, and should be the only non-\ ``static``
117 item defined in the module file. Example::
118
119 static struct PyModuleDef spam_module = {
120 .m_base = PyModuleDef_HEAD_INIT,
121 .m_name = "spam",
122 ...
123 };
124
125 PyMODINIT_FUNC
126 PyInit_spam(void)
127 {
128 return PyModuleDef_Init(&spam_module);
129 }
130
131
132 .. c:macro:: Py_ABS(x)
133
134 Return the absolute value of ``x``.
135
136 If the result cannot be represented (for example, if ``x`` has
137 :c:macro:`!INT_MIN` value for :c:expr:`int` type), the behavior is
138 undefined.
139
140 .. versionadded:: 3.3
141
142 .. c:macro:: Py_ALWAYS_INLINE
143
144 Ask the compiler to always inline a static inline function. The compiler can
145 ignore it and decide to not inline the function.
146
147 It can be used to inline performance critical static inline functions when
148 building Python in debug mode with function inlining disabled. For example,
149 MSC disables function inlining when building in debug mode.
150
151 Marking blindly a static inline function with Py_ALWAYS_INLINE can result in
152 worse performances (due to increased code size for example). The compiler is
153 usually smarter than the developer for the cost/benefit analysis.
154
155 If Python is :ref:`built in debug mode <debug-build>` (if the :c:macro:`Py_DEBUG`
156 macro is defined), the :c:macro:`Py_ALWAYS_INLINE` macro does nothing.
157
158 It must be specified before the function return type. Usage::
159
160 static inline Py_ALWAYS_INLINE int random(void) { return 4; }
161
162 .. versionadded:: 3.11
163
164 .. c:macro:: Py_CHARMASK(c)
165
166 Argument must be a character or an integer in the range [-128, 127] or [0,
167 255]. This macro returns ``c`` cast to an ``unsigned char``.
168
169 .. c:macro:: Py_DEPRECATED(version)
170
171 Use this for deprecated declarations. The macro must be placed before the
172 symbol name.
173
174 Example::
175
176 Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
177
178 .. versionchanged:: 3.8
179 MSVC support was added.
180
181 .. c:macro:: Py_GETENV(s)
182
183 Like ``getenv(s)``, but returns ``NULL`` if :option:`-E` was passed on the
184 command line (see :c:member:`PyConfig.use_environment`).
185
186 .. c:macro:: Py_LOCAL(type)
187
188 Declare a function returning the specified *type* using a fast-calling
189 qualifier for functions that are local to the current file.
190 Semantically, this is equivalent to ``static type``.
191
192 .. c:macro:: Py_LOCAL_INLINE(type)
193
194 Equivalent to :c:macro:`Py_LOCAL` but additionally requests the function
195 be inlined.
196
197 .. c:macro:: Py_LOCAL_SYMBOL
198
199 Macro used to declare a symbol as local to the shared library (hidden).
200 On supported platforms, it ensures the symbol is not exported.
201
202 On compatible versions of GCC/Clang, it
203 expands to ``__attribute__((visibility("hidden")))``.
204
205 .. c:macro:: Py_MAX(x, y)
206
207 Return the maximum value between ``x`` and ``y``.
208
209 .. versionadded:: 3.3
210
211 .. c:macro:: Py_MEMBER_SIZE(type, member)
212
213 Return the size of a structure (``type``) ``member`` in bytes.
214
215 .. versionadded:: 3.6
216
217 .. c:macro:: Py_MIN(x, y)
218
219 Return the minimum value between ``x`` and ``y``.
220
221 .. versionadded:: 3.3
222
223 .. c:macro:: Py_NO_INLINE
224
225 Disable inlining on a function. For example, it reduces the C stack
226 consumption: useful on LTO+PGO builds which heavily inline code (see
227 :issue:`33720`).
228
229 Usage::
230
231 Py_NO_INLINE static int random(void) { return 4; }
232
233 .. versionadded:: 3.11
234
235 .. c:macro:: Py_STRINGIFY(x)
236
237 Convert ``x`` to a C string. E.g. ``Py_STRINGIFY(123)`` returns
238 ``"123"``.
239
240 .. versionadded:: 3.4
241
242 .. c:macro:: Py_UNREACHABLE()
243
244 Use this when you have a code path that cannot be reached by design.
245 For example, in the ``default:`` clause in a ``switch`` statement for which
246 all possible values are covered in ``case`` statements. Use this in places
247 where you might be tempted to put an ``assert(0)`` or ``abort()`` call.
248
249 In release mode, the macro helps the compiler to optimize the code, and
250 avoids a warning about unreachable code. For example, the macro is
251 implemented with ``__builtin_unreachable()`` on GCC in release mode.
252
253 A use for ``Py_UNREACHABLE()`` is following a call a function that
254 never returns but that is not declared :c:macro:`_Py_NO_RETURN`.
255
256 If a code path is very unlikely code but can be reached under exceptional
257 case, this macro must not be used. For example, under low memory condition
258 or if a system call returns a value out of the expected range. In this
259 case, it's better to report the error to the caller. If the error cannot
260 be reported to caller, :c:func:`Py_FatalError` can be used.
261
262 .. versionadded:: 3.7
263
264 .. c:macro:: Py_UNUSED(arg)
265
266 Use this for unused arguments in a function definition to silence compiler
267 warnings. Example: ``int func(int a, int Py_UNUSED(b)) { return a; }``.
268
269 .. versionadded:: 3.4
270
271 .. c:macro:: Py_BUILD_ASSERT(cond)
272
273 Asserts a compile-time condition *cond*, as a statement.
274 The build will fail if the condition is false or cannot be evaluated at compile time.
275
276 For example::
277
278 Py_BUILD_ASSERT(sizeof(PyTime_t) == sizeof(int64_t));
279
280 .. versionadded:: 3.3
281
282 .. c:macro:: Py_BUILD_ASSERT_EXPR(cond)
283
284 Asserts a compile-time condition *cond*, as an expression that evaluates to ``0``.
285 The build will fail if the condition is false or cannot be evaluated at compile time.
286
287 For example::
288
289 #define foo_to_char(foo) \
290 ((char *)(foo) + Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0))
291
292 .. versionadded:: 3.3
293
294 .. c:macro:: PyDoc_STRVAR(name, str)
295
296 Creates a variable with name *name* that can be used in docstrings.
297 If Python is built without docstrings, the value will be empty.
298
299 Use :c:macro:`PyDoc_STRVAR` for docstrings to support building
300 Python without docstrings, as specified in :pep:`7`.
301
302 Example::
303
304 PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
305
306 static PyMethodDef deque_methods[] = {
307 // ...
308 {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
309 // ...
310 }
311
312 .. c:macro:: PyDoc_STR(str)
313
314 Creates a docstring for the given input string or an empty string
315 if docstrings are disabled.
316
317 Use :c:macro:`PyDoc_STR` in specifying docstrings to support
318 building Python without docstrings, as specified in :pep:`7`.
319
320 Example::
321
322 static PyMethodDef pysqlite_row_methods[] = {
323 {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
324 PyDoc_STR("Returns the keys of the row.")},
325 {NULL, NULL}
326 };
327
328 .. c:macro:: PyDoc_VAR(name)
329
330 Declares a static character array variable with the given name *name*.
331
332 For example::
333
334 PyDoc_VAR(python_doc) = PyDoc_STR("A genus of constricting snakes in the Pythonidae family native "
335 "to the tropics and subtropics of the Eastern Hemisphere.");
336
337 .. c:macro:: Py_ARRAY_LENGTH(array)
338
339 Compute the length of a statically allocated C array at compile time.
340
341 The *array* argument must be a C array with a size known at compile time.
342 Passing an array with an unknown size, such as a heap-allocated array,
343 will result in a compilation error on some compilers, or otherwise produce
344 incorrect results.
345
346 This is roughly equivalent to::
347
348 sizeof(array) / sizeof((array)[0])
349
350
351 .. c:macro:: Py_EXPORTED_SYMBOL
352
353 Macro used to declare a symbol (function or data) as exported.
354 On Windows, this expands to ``__declspec(dllexport)``.
355 On compatible versions of GCC/Clang, it
356 expands to ``__attribute__((visibility("default")))``.
357 This macro is for defining the C API itself; extension modules should not use it.
358
359
360 .. c:macro:: Py_IMPORTED_SYMBOL
361
362 Macro used to declare a symbol as imported.
363 On Windows, this expands to ``__declspec(dllimport)``.
364 This macro is for defining the C API itself; extension modules should not use it.
365
366
367 .. c:macro:: PyAPI_FUNC(type)
368
369 Macro used by CPython to declare a function as part of the C API.
370 Its expansion depends on the platform and build configuration.
371 This macro is intended for defining CPython's C API itself;
372 extension modules should not use it for their own symbols.
373
374
375 .. c:macro:: PyAPI_DATA(type)
376
377 Macro used by CPython to declare a public global variable as part of the C API.
378 Its expansion depends on the platform and build configuration.
379 This macro is intended for defining CPython's C API itself;
380 extension modules should not use it for their own symbols.
381
382
383 .. _api-objects:
384
385 Objects, Types and Reference Counts
386 ===================================
387
388 .. index:: pair: object; type
389
390 Most Python/C API functions have one or more arguments as well as a return value
391 of type :c:expr:`PyObject*`. This type is a pointer to an opaque data type
392 representing an arbitrary Python object. Since all Python object types are
393 treated the same way by the Python language in most situations (e.g.,
394 assignments, scope rules, and argument passing), it is only fitting that they
395 should be represented by a single C type. Almost all Python objects live on the
396 heap: you never declare an automatic or static variable of type
397 :c:type:`PyObject`, only pointer variables of type :c:expr:`PyObject*` can be
398 declared. The sole exception are the type objects; since these must never be
399 deallocated, they are typically static :c:type:`PyTypeObject` objects.
400
401 All Python objects (even Python integers) have a :dfn:`type` and a
402 :dfn:`reference count`. An object's type determines what kind of object it is
403 (e.g., an integer, a list, or a user-defined function; there are many more as
404 explained in :ref:`types`). For each of the well-known types there is a macro
405 to check whether an object is of that type; for instance, ``PyList_Check(a)`` is
406 true if (and only if) the object pointed to by *a* is a Python list.
407
408
409 .. _api-refcounts:
410
411 Reference Counts
412 ----------------
413
414 The reference count is important because today's computers have a finite
415 (and often severely limited) memory size; it counts how many different
416 places there are that have a :term:`strong reference` to an object.
417 Such a place could be another object, or a global (or static) C variable,
418 or a local variable in some C function.
419 When the last :term:`strong reference` to an object is released
420 (i.e. its reference count becomes zero), the object is deallocated.
421 If it contains references to other objects, those references are released.
422 Those other objects may be deallocated in turn, if there are no more
423 references to them, and so on. (There's an obvious problem with
424 objects that reference each other here; for now, the solution
425 is "don't do that.")
426
427 .. index::
428 single: Py_INCREF (C function)
429 single: Py_DECREF (C function)
430
431 Reference counts are always manipulated explicitly. The normal way is
432 to use the macro :c:func:`Py_INCREF` to take a new reference to an
433 object (i.e. increment its reference count by one),
434 and :c:func:`Py_DECREF` to release that reference (i.e. decrement the
435 reference count by one). The :c:func:`Py_DECREF` macro
436 is considerably more complex than the incref one, since it must check whether
437 the reference count becomes zero and then cause the object's deallocator to be
438 called. The deallocator is a function pointer contained in the object's type
439 structure. The type-specific deallocator takes care of releasing references
440 for other objects contained in the object if this is a compound
441 object type, such as a list, as well as performing any additional finalization
442 that's needed. There's no chance that the reference count can overflow; at
443 least as many bits are used to hold the reference count as there are distinct
444 memory locations in virtual memory (assuming ``sizeof(Py_ssize_t) >= sizeof(void*)``).
445 Thus, the reference count increment is a simple operation.
446
447 It is not necessary to hold a :term:`strong reference` (i.e. increment
448 the reference count) for every local variable that contains a pointer
449 to an object. In theory, the object's
450 reference count goes up by one when the variable is made to point to it and it
451 goes down by one when the variable goes out of scope. However, these two
452 cancel each other out, so at the end the reference count hasn't changed. The
453 only real reason to use the reference count is to prevent the object from being
454 deallocated as long as our variable is pointing to it. If we know that there
455 is at least one other reference to the object that lives at least as long as
456 our variable, there is no need to take a new :term:`strong reference`
457 (i.e. increment the reference count) temporarily.
458 An important situation where this arises is in objects that are passed as
459 arguments to C functions in an extension module that are called from Python;
460 the call mechanism guarantees to hold a reference to every argument for the
461 duration of the call.
462
463 However, a common pitfall is to extract an object from a list and hold on to it
464 for a while without taking a new reference. Some other operation might
465 conceivably remove the object from the list, releasing that reference,
466 and possibly deallocating it. The real danger is that innocent-looking
467 operations may invoke arbitrary Python code which could do this; there is a code
468 path which allows control to flow back to the user from a :c:func:`Py_DECREF`, so
469 almost any operation is potentially dangerous.
470
471 A safe approach is to always use the generic operations (functions whose name
472 begins with ``PyObject_``, ``PyNumber_``, ``PySequence_`` or ``PyMapping_``).
473 These operations always create a new :term:`strong reference`
474 (i.e. increment the reference count) of the object they return.
475 This leaves the caller with the responsibility to call :c:func:`Py_DECREF` when
476 they are done with the result; this soon becomes second nature.
477
478
479 .. _api-refcountdetails:
480
481 Reference Count Details
482 ^^^^^^^^^^^^^^^^^^^^^^^
483
484 The reference count behavior of functions in the Python/C API is best explained
485 in terms of *ownership of references*. Ownership pertains to references, never
486 to objects (objects are not owned: they are always shared). "Owning a
487 reference" means being responsible for calling Py_DECREF on it when the
488 reference is no longer needed. Ownership can also be transferred, meaning that
489 the code that receives ownership of the reference then becomes responsible for
490 eventually releasing it by calling :c:func:`Py_DECREF` or :c:func:`Py_XDECREF`
491 when it's no longer needed---or passing on this responsibility (usually to its
492 caller). When a function passes ownership of a reference on to its caller, the
493 caller is said to receive a *new* reference. When no ownership is transferred,
494 the caller is said to *borrow* the reference. Nothing needs to be done for a
495 :term:`borrowed reference`.
496
497 Conversely, when a calling function passes in a reference to an object, there
498 are two possibilities: the function *steals* a reference to the object, or it
499 does not. *Stealing a reference* means that when you pass a reference to a
500 function, that function assumes that it now owns that reference, and you are not
501 responsible for it any longer.
502
503 .. index::
504 single: PyList_SetItem (C function)
505 single: PyTuple_SetItem (C function)
506
507 Few functions steal references; the two notable exceptions are
508 :c:func:`PyList_SetItem` and :c:func:`PyTuple_SetItem`, which steal a reference
509 to the item (but not to the tuple or list into which the item is put!). These
510 functions were designed to steal a reference because of a common idiom for
511 populating a tuple or list with newly created objects; for example, the code to
512 create the tuple ``(1, 2, "three")`` could look like this (forgetting about
513 error handling for the moment; a better way to code this is shown below)::
514
515 PyObject *t;
516
517 t = PyTuple_New(3);
518 PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
519 PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
520 PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));
521
522 Here, :c:func:`PyLong_FromLong` returns a new reference which is immediately
523 stolen by :c:func:`PyTuple_SetItem`. When you want to keep using an object
524 although the reference to it will be stolen, use :c:func:`Py_INCREF` to grab
525 another reference before calling the reference-stealing function.
526
527 Incidentally, :c:func:`PyTuple_SetItem` is the *only* way to set tuple items;
528 :c:func:`PySequence_SetItem` and :c:func:`PyObject_SetItem` refuse to do this
529 since tuples are an immutable data type. You should only use
530 :c:func:`PyTuple_SetItem` for tuples that you are creating yourself.
531
532 Equivalent code for populating a list can be written using :c:func:`PyList_New`
533 and :c:func:`PyList_SetItem`.
534
535 However, in practice, you will rarely use these ways of creating and populating
536 a tuple or list. There's a generic function, :c:func:`Py_BuildValue`, that can
537 create most common objects from C values, directed by a :dfn:`format string`.
538 For example, the above two blocks of code could be replaced by the following
539 (which also takes care of the error checking)::
540
541 PyObject *tuple, *list;
542
543 tuple = Py_BuildValue("(iis)", 1, 2, "three");
544 list = Py_BuildValue("[iis]", 1, 2, "three");
545
546 It is much more common to use :c:func:`PyObject_SetItem` and friends with items
547 whose references you are only borrowing, like arguments that were passed in to
548 the function you are writing. In that case, their behaviour regarding references
549 is much saner, since you don't have to take a new reference just so you
550 can give that reference away ("have it be stolen"). For example, this function
551 sets all items of a list (actually, any mutable sequence) to a given item::
552
553 int
554 set_all(PyObject *target, PyObject *item)
555 {
556 Py_ssize_t i, n;
557
558 n = PyObject_Length(target);
559 if (n < 0)
560 return -1;
561 for (i = 0; i < n; i++) {
562 PyObject *index = PyLong_FromSsize_t(i);
563 if (!index)
564 return -1;
565 if (PyObject_SetItem(target, index, item) < 0) {
566 Py_DECREF(index);
567 return -1;
568 }
569 Py_DECREF(index);
570 }
571 return 0;
572 }
573
574 .. index:: single: set_all()
575
576 The situation is slightly different for function return values. While passing
577 a reference to most functions does not change your ownership responsibilities
578 for that reference, many functions that return a reference to an object give
579 you ownership of the reference. The reason is simple: in many cases, the
580 returned object is created on the fly, and the reference you get is the only
581 reference to the object. Therefore, the generic functions that return object
582 references, like :c:func:`PyObject_GetItem` and :c:func:`PySequence_GetItem`,
583 always return a new reference (the caller becomes the owner of the reference).
584
585 It is important to realize that whether you own a reference returned by a
586 function depends on which function you call only --- *the plumage* (the type of
587 the object passed as an argument to the function) *doesn't enter into it!*
588 Thus, if you extract an item from a list using :c:func:`PyList_GetItem`, you
589 don't own the reference --- but if you obtain the same item from the same list
590 using :c:func:`PySequence_GetItem` (which happens to take exactly the same
591 arguments), you do own a reference to the returned object.
592
593 .. index::
594 single: PyList_GetItem (C function)
595 single: PySequence_GetItem (C function)
596
597 Here is an example of how you could write a function that computes the sum of
598 the items in a list of integers; once using :c:func:`PyList_GetItem`, and once
599 using :c:func:`PySequence_GetItem`. ::
600
601 long
602 sum_list(PyObject *list)
603 {
604 Py_ssize_t i, n;
605 long total = 0, value;
606 PyObject *item;
607
608 n = PyList_Size(list);
609 if (n < 0)
610 return -1; /* Not a list */
611 for (i = 0; i < n; i++) {
612 item = PyList_GetItem(list, i); /* Can't fail */
613 if (!PyLong_Check(item)) continue; /* Skip non-integers */
614 value = PyLong_AsLong(item);
615 if (value == -1 && PyErr_Occurred())
616 /* Integer too big to fit in a C long, bail out */
617 return -1;
618 total += value;
619 }
620 return total;
621 }
622
623 .. index:: single: sum_list()
624
625 ::
626
627 long
628 sum_sequence(PyObject *sequence)
629 {
630 Py_ssize_t i, n;
631 long total = 0, value;
632 PyObject *item;
633 n = PySequence_Length(sequence);
634 if (n < 0)
635 return -1; /* Has no length */
636 for (i = 0; i < n; i++) {
637 item = PySequence_GetItem(sequence, i);
638 if (item == NULL)
639 return -1; /* Not a sequence, or other failure */
640 if (PyLong_Check(item)) {
641 value = PyLong_AsLong(item);
642 Py_DECREF(item);
643 if (value == -1 && PyErr_Occurred())
644 /* Integer too big to fit in a C long, bail out */
645 return -1;
646 total += value;
647 }
648 else {
649 Py_DECREF(item); /* Discard reference ownership */
650 }
651 }
652 return total;
653 }
654
655 .. index:: single: sum_sequence()
656
657
658 .. _api-types:
659
660 Types
661 -----
662
663 There are few other data types that play a significant role in the Python/C
664 API; most are simple C types such as :c:expr:`int`, :c:expr:`long`,
665 :c:expr:`double` and :c:expr:`char*`. A few structure types are used to
666 describe static tables used to list the functions exported by a module or the
667 data attributes of a new object type, and another is used to describe the value
668 of a complex number. These will be discussed together with the functions that
669 use them.
670
671 .. c:type:: Py_ssize_t
672
673 A signed integral type such that ``sizeof(Py_ssize_t) == sizeof(size_t)``.
674 C99 doesn't define such a thing directly (size_t is an unsigned integral type).
675 See :pep:`353` for details. ``PY_SSIZE_T_MAX`` is the largest positive value
676 of type :c:type:`Py_ssize_t`.
677
678
679 .. _api-exceptions:
680
681 Exceptions
682 ==========
683
684 The Python programmer only needs to deal with exceptions if specific error
685 handling is required; unhandled exceptions are automatically propagated to the
686 caller, then to the caller's caller, and so on, until they reach the top-level
687 interpreter, where they are reported to the user accompanied by a stack
688 traceback.
689
690 .. index:: single: PyErr_Occurred (C function)
691
692 For C programmers, however, error checking always has to be explicit. All
693 functions in the Python/C API can raise exceptions, unless an explicit claim is
694 made otherwise in a function's documentation. In general, when a function
695 encounters an error, it sets an exception, discards any object references that
696 it owns, and returns an error indicator. If not documented otherwise, this
697 indicator is either ``NULL`` or ``-1``, depending on the function's return type.
698 A few functions return a Boolean true/false result, with false indicating an
699 error. Very few functions return no explicit error indicator or have an
700 ambiguous return value, and require explicit testing for errors with
701 :c:func:`PyErr_Occurred`. These exceptions are always explicitly documented.
702
703 .. index::
704 single: PyErr_SetString (C function)
705 single: PyErr_Clear (C function)
706
707 Exception state is maintained in per-thread storage (this is equivalent to
708 using global storage in an unthreaded application). A thread can be in one of
709 two states: an exception has occurred, or not. The function
710 :c:func:`PyErr_Occurred` can be used to check for this: it returns a borrowed
711 reference to the exception type object when an exception has occurred, and
712 ``NULL`` otherwise. There are a number of functions to set the exception state:
713 :c:func:`PyErr_SetString` is the most common (though not the most general)
714 function to set the exception state, and :c:func:`PyErr_Clear` clears the
715 exception state.
716
717 The full exception state consists of three objects (all of which can be
718 ``NULL``): the exception type, the corresponding exception value, and the
719 traceback. These have the same meanings as the Python result of
720 ``sys.exc_info()``; however, they are not the same: the Python objects represent
721 the last exception being handled by a Python :keyword:`try` ...
722 :keyword:`except` statement, while the C level exception state only exists while
723 an exception is being passed on between C functions until it reaches the Python
724 bytecode interpreter's main loop, which takes care of transferring it to
725 ``sys.exc_info()`` and friends.
726
727 .. index:: single: exc_info (in module sys)
728
729 Note that starting with Python 1.5, the preferred, thread-safe way to access the
730 exception state from Python code is to call the function :func:`sys.exc_info`,
731 which returns the per-thread exception state for Python code. Also, the
732 semantics of both ways to access the exception state have changed so that a
733 function which catches an exception will save and restore its thread's exception
734 state so as to preserve the exception state of its caller. This prevents common
735 bugs in exception handling code caused by an innocent-looking function
736 overwriting the exception being handled; it also reduces the often unwanted
737 lifetime extension for objects that are referenced by the stack frames in the
738 traceback.
739
740 As a general principle, a function that calls another function to perform some
741 task should check whether the called function raised an exception, and if so,
742 pass the exception state on to its caller. It should discard any object
743 references that it owns, and return an error indicator, but it should *not* set
744 another exception --- that would overwrite the exception that was just raised,
745 and lose important information about the exact cause of the error.
746
747 .. index:: single: sum_sequence()
748
749 A simple example of detecting exceptions and passing them on is shown in the
750 :c:func:`!sum_sequence` example above. It so happens that this example doesn't
751 need to clean up any owned references when it detects an error. The following
752 example function shows some error cleanup. First, to remind you why you like
753 Python, we show the equivalent Python code::
754
755 def incr_item(dict, key):
756 try:
757 item = dict[key]
758 except KeyError:
759 item = 0
760 dict[key] = item + 1
761
762 .. index:: single: incr_item()
763
764 Here is the corresponding C code, in all its glory::
765
766 int
767 incr_item(PyObject *dict, PyObject *key)
768 {
769 /* Objects all initialized to NULL for Py_XDECREF */
770 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
771 int rv = -1; /* Return value initialized to -1 (failure) */
772
773 item = PyObject_GetItem(dict, key);
774 if (item == NULL) {
775 /* Handle KeyError only: */
776 if (!PyErr_ExceptionMatches(PyExc_KeyError))
777 goto error;
778
779 /* Clear the error and use zero: */
780 PyErr_Clear();
781 item = PyLong_FromLong(0L);
782 if (item == NULL)
783 goto error;
784 }
785 const_one = PyLong_FromLong(1L);
786 if (const_one == NULL)
787 goto error;
788
789 incremented_item = PyNumber_Add(item, const_one);
790 if (incremented_item == NULL)
791 goto error;
792
793 if (PyObject_SetItem(dict, key, incremented_item) < 0)
794 goto error;
795 rv = 0; /* Success */
796 /* Continue with cleanup code */
797
798 error:
799 /* Cleanup code, shared by success and failure path */
800
801 /* Use Py_XDECREF() to ignore NULL references */
802 Py_XDECREF(item);
803 Py_XDECREF(const_one);
804 Py_XDECREF(incremented_item);
805
806 return rv; /* -1 for error, 0 for success */
807 }
808
809 .. index:: single: incr_item()
810
811 .. index::
812 single: PyErr_ExceptionMatches (C function)
813 single: PyErr_Clear (C function)
814 single: Py_XDECREF (C function)
815
816 This example represents an endorsed use of the ``goto`` statement in C!
817 It illustrates the use of :c:func:`PyErr_ExceptionMatches` and
818 :c:func:`PyErr_Clear` to handle specific exceptions, and the use of
819 :c:func:`Py_XDECREF` to dispose of owned references that may be ``NULL`` (note the
820 ``'X'`` in the name; :c:func:`Py_DECREF` would crash when confronted with a
821 ``NULL`` reference). It is important that the variables used to hold owned
822 references are initialized to ``NULL`` for this to work; likewise, the proposed
823 return value is initialized to ``-1`` (failure) and only set to success after
824 the final call made is successful.
825
826
827 .. _api-embedding:
828
829 Embedding Python
830 ================
831
832 The one important task that only embedders (as opposed to extension writers) of
833 the Python interpreter have to worry about is the initialization, and possibly
834 the finalization, of the Python interpreter. Most functionality of the
835 interpreter can only be used after the interpreter has been initialized.
836
837 .. index::
838 single: Py_Initialize (C function)
839 pair: module; builtins
840 pair: module; __main__
841 pair: module; sys
842 triple: module; search; path
843 single: path (in module sys)
844
845 The basic initialization function is :c:func:`Py_Initialize`. This initializes
846 the table of loaded modules, and creates the fundamental modules
847 :mod:`builtins`, :mod:`__main__`, and :mod:`sys`. It also
848 initializes the module search path (``sys.path``).
849
850 :c:func:`Py_Initialize` does not set the "script argument list" (``sys.argv``).
851 If this variable is needed by Python code that will be executed later, setting
852 :c:member:`PyConfig.argv` and :c:member:`PyConfig.parse_argv` must be set: see
853 :ref:`Python Initialization Configuration <init-config>`.
854
855 On most systems (in particular, on Unix and Windows, although the details are
856 slightly different), :c:func:`Py_Initialize` calculates the module search path
857 based upon its best guess for the location of the standard Python interpreter
858 executable, assuming that the Python library is found in a fixed location
859 relative to the Python interpreter executable. In particular, it looks for a
860 directory named :file:`lib/python{X.Y}` relative to the parent directory
861 where the executable named :file:`python` is found on the shell command search
862 path (the environment variable :envvar:`PATH`).
863
864 For instance, if the Python executable is found in
865 :file:`/usr/local/bin/python`, it will assume that the libraries are in
866 :file:`/usr/local/lib/python{X.Y}`. (In fact, this particular path is also
867 the "fallback" location, used when no executable file named :file:`python` is
868 found along :envvar:`PATH`.) The user can override this behavior by setting the
869 environment variable :envvar:`PYTHONHOME`, or insert additional directories in
870 front of the standard path by setting :envvar:`PYTHONPATH`.
871
872 .. index::
873 single: Py_GetPath (C function)
874 single: Py_GetPrefix (C function)
875 single: Py_GetExecPrefix (C function)
876 single: Py_GetProgramFullPath (C function)
877
878 The embedding application can steer the search by setting
879 :c:member:`PyConfig.program_name` *before* calling
880 :c:func:`Py_InitializeFromConfig`. Note that
881 :envvar:`PYTHONHOME` still overrides this and :envvar:`PYTHONPATH` is still
882 inserted in front of the standard path. An application that requires total
883 control has to provide its own implementation of :c:func:`Py_GetPath`,
884 :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, and
885 :c:func:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`).
886
887 .. index:: single: Py_IsInitialized (C function)
888
889 Sometimes, it is desirable to "uninitialize" Python. For instance, the
890 application may want to start over (make another call to
891 :c:func:`Py_Initialize`) or the application is simply done with its use of
892 Python and wants to free memory allocated by Python. This can be accomplished
893 by calling :c:func:`Py_FinalizeEx`. The function :c:func:`Py_IsInitialized` returns
894 true if Python is currently in the initialized state. More information about
895 these functions is given in a later chapter. Notice that :c:func:`Py_FinalizeEx`
896 does *not* free all memory allocated by the Python interpreter, e.g. memory
897 allocated by extension modules currently cannot be released.
898
899
900 .. _api-debugging:
901
902 Debugging Builds
903 ================
904
905 Python can be built with several macros to enable extra checks of the
906 interpreter and extension modules. These checks tend to add a large amount of
907 overhead to the runtime so they are not enabled by default.
908
909 A full list of the various types of debugging builds is in the file
910 :file:`Misc/SpecialBuilds.txt` in the Python source distribution. Builds are
911 available that support tracing of reference counts, debugging the memory
912 allocator, or low-level profiling of the main interpreter loop. Only the most
913 frequently used builds will be described in the remainder of this section.
914
915 .. c:macro:: Py_DEBUG
916
917 Compiling the interpreter with the :c:macro:`!Py_DEBUG` macro defined produces
918 what is generally meant by :ref:`a debug build of Python <debug-build>`.
919 :c:macro:`!Py_DEBUG` is enabled in the Unix build by adding
920 :option:`--with-pydebug` to the :file:`./configure` command.
921 It is also implied by the presence of the
922 not-Python-specific :c:macro:`!_DEBUG` macro. When :c:macro:`!Py_DEBUG` is enabled
923 in the Unix build, compiler optimization is disabled.
924
925 In addition to the reference count debugging described below, extra checks are
926 performed, see :ref:`Python Debug Build <debug-build>`.
927
928 Defining :c:macro:`Py_TRACE_REFS` enables reference tracing
929 (see the :option:`configure --with-trace-refs option <--with-trace-refs>`).
930 When defined, a circular doubly linked list of active objects is maintained by adding two extra
931 fields to every :c:type:`PyObject`. Total allocations are tracked as well. Upon
932 exit, all existing references are printed. (In interactive mode this happens
933 after every statement run by the interpreter.)
934
935 Please refer to :file:`Misc/SpecialBuilds.txt` in the Python source distribution
936 for more detailed information.
937
938
939 .. _c-api-tools:
940
941 Recommended third party tools
942 =============================
943
944 The following third party tools offer both simpler and more sophisticated
945 approaches to creating C, C++ and Rust extensions for Python:
946
947 * `Cython <https://cython.org/>`_
948 * `cffi <https://cffi.readthedocs.io>`_
949 * `HPy <https://hpyproject.org/>`_
950 * `nanobind <https://github.com/wjakob/nanobind>`_ (C++)
951 * `Numba <https://numba.pydata.org/>`_
952 * `pybind11 <https://pybind11.readthedocs.io/>`_ (C++)
953 * `PyO3 <https://pyo3.rs/>`_ (Rust)
954 * `SWIG <https://www.swig.org>`_
955
956 Using tools such as these can help avoid writing code that is tightly bound to
957 a particular version of CPython, avoid reference counting errors, and focus
958 more on your own code than on using the CPython API. In general, new versions
959 of Python can be supported by updating the tool, and your code will often use
960 newer and more efficient APIs automatically. Some tools also support compiling
961 for other implementations of Python from a single set of sources.
962
963 These projects are not supported by the same people who maintain Python, and
964 issues need to be raised with the projects directly. Remember to check that the
965 project is still maintained and supported, as the list above may become
966 outdated.
967
968 .. seealso::
969
970 `Python Packaging User Guide: Binary Extensions <https://packaging.python.org/guides/packaging-binary-extensions/>`_
971 The Python Packaging User Guide not only covers several available
972 tools that simplify the creation of binary extensions, but also
973 discusses the various reasons why creating an extension module may be
974 desirable in the first place.