Python provides such a facility at the C level in the form of the :ref:`buffer
protocol <bufferobjects>`. This protocol has two sides:
-.. index:: single: PyBufferProcs
+.. index:: single: PyBufferProcs (C type)
- on the producer side, a type can export a "buffer interface" which allows
objects of that type to expose information about their underlying buffer.
.. c:function:: PyObject* PyErr_SetFromErrno(PyObject *type)
- .. index:: single: strerror()
+ .. index:: single: strerror (C function)
This is a convenience function to raise an exception when a C library function
has returned an error and set the C variable :c:data:`errno`. It constructs a
.. index::
pair: module; signal
- single: SIGINT
+ single: SIGINT (C macro)
single: KeyboardInterrupt (built-in exception)
This function interacts with Python's signal handling.
.. index::
pair: module; signal
- single: SIGINT
+ single: SIGINT (C macro)
single: KeyboardInterrupt (built-in exception)
Simulate the effect of a :c:macro:`!SIGINT` signal arriving.
the variables:
.. index::
- single: PyExc_BaseException
- single: PyExc_Exception
- single: PyExc_ArithmeticError
- single: PyExc_AssertionError
- single: PyExc_AttributeError
- single: PyExc_BlockingIOError
- single: PyExc_BrokenPipeError
- single: PyExc_BufferError
- single: PyExc_ChildProcessError
- single: PyExc_ConnectionAbortedError
- single: PyExc_ConnectionError
- single: PyExc_ConnectionRefusedError
- single: PyExc_ConnectionResetError
- single: PyExc_EOFError
- single: PyExc_FileExistsError
- single: PyExc_FileNotFoundError
- single: PyExc_FloatingPointError
- single: PyExc_GeneratorExit
- single: PyExc_ImportError
- single: PyExc_IndentationError
- single: PyExc_IndexError
- single: PyExc_InterruptedError
- single: PyExc_IsADirectoryError
- single: PyExc_KeyError
- single: PyExc_KeyboardInterrupt
- single: PyExc_LookupError
- single: PyExc_MemoryError
- single: PyExc_ModuleNotFoundError
- single: PyExc_NameError
- single: PyExc_NotADirectoryError
- single: PyExc_NotImplementedError
- single: PyExc_OSError
- single: PyExc_OverflowError
- single: PyExc_PermissionError
- single: PyExc_ProcessLookupError
- single: PyExc_RecursionError
- single: PyExc_ReferenceError
- single: PyExc_RuntimeError
- single: PyExc_StopAsyncIteration
- single: PyExc_StopIteration
- single: PyExc_SyntaxError
- single: PyExc_SystemError
- single: PyExc_SystemExit
- single: PyExc_TabError
- single: PyExc_TimeoutError
- single: PyExc_TypeError
- single: PyExc_UnboundLocalError
- single: PyExc_UnicodeDecodeError
- single: PyExc_UnicodeEncodeError
- single: PyExc_UnicodeError
- single: PyExc_UnicodeTranslateError
- single: PyExc_ValueError
- single: PyExc_ZeroDivisionError
+ single: PyExc_BaseException (C var)
+ single: PyExc_Exception (C var)
+ single: PyExc_ArithmeticError (C var)
+ single: PyExc_AssertionError (C var)
+ single: PyExc_AttributeError (C var)
+ single: PyExc_BlockingIOError (C var)
+ single: PyExc_BrokenPipeError (C var)
+ single: PyExc_BufferError (C var)
+ single: PyExc_ChildProcessError (C var)
+ single: PyExc_ConnectionAbortedError (C var)
+ single: PyExc_ConnectionError (C var)
+ single: PyExc_ConnectionRefusedError (C var)
+ single: PyExc_ConnectionResetError (C var)
+ single: PyExc_EOFError (C var)
+ single: PyExc_FileExistsError (C var)
+ single: PyExc_FileNotFoundError (C var)
+ single: PyExc_FloatingPointError (C var)
+ single: PyExc_GeneratorExit (C var)
+ single: PyExc_ImportError (C var)
+ single: PyExc_IndentationError (C var)
+ single: PyExc_IndexError (C var)
+ single: PyExc_InterruptedError (C var)
+ single: PyExc_IsADirectoryError (C var)
+ single: PyExc_KeyError (C var)
+ single: PyExc_KeyboardInterrupt (C var)
+ single: PyExc_LookupError (C var)
+ single: PyExc_MemoryError (C var)
+ single: PyExc_ModuleNotFoundError (C var)
+ single: PyExc_NameError (C var)
+ single: PyExc_NotADirectoryError (C var)
+ single: PyExc_NotImplementedError (C var)
+ single: PyExc_OSError (C var)
+ single: PyExc_OverflowError (C var)
+ single: PyExc_PermissionError (C var)
+ single: PyExc_ProcessLookupError (C var)
+ single: PyExc_RecursionError (C var)
+ single: PyExc_ReferenceError (C var)
+ single: PyExc_RuntimeError (C var)
+ single: PyExc_StopAsyncIteration (C var)
+ single: PyExc_StopIteration (C var)
+ single: PyExc_SyntaxError (C var)
+ single: PyExc_SystemError (C var)
+ single: PyExc_SystemExit (C var)
+ single: PyExc_TabError (C var)
+ single: PyExc_TimeoutError (C var)
+ single: PyExc_TypeError (C var)
+ single: PyExc_UnboundLocalError (C var)
+ single: PyExc_UnicodeDecodeError (C var)
+ single: PyExc_UnicodeEncodeError (C var)
+ single: PyExc_UnicodeError (C var)
+ single: PyExc_UnicodeTranslateError (C var)
+ single: PyExc_ValueError (C var)
+ single: PyExc_ZeroDivisionError (C var)
+-----------------------------------------+---------------------------------+----------+
| C Name | Python Name | Notes |
These are compatibility aliases to :c:data:`PyExc_OSError`:
.. index::
- single: PyExc_EnvironmentError
- single: PyExc_IOError
- single: PyExc_WindowsError
+ single: PyExc_EnvironmentError (C var)
+ single: PyExc_IOError (C var)
+ single: PyExc_WindowsError (C var)
+-------------------------------------+----------+
| C Name | Notes |
the variables:
.. index::
- single: PyExc_Warning
- single: PyExc_BytesWarning
- single: PyExc_DeprecationWarning
- single: PyExc_FutureWarning
- single: PyExc_ImportWarning
- single: PyExc_PendingDeprecationWarning
- single: PyExc_ResourceWarning
- single: PyExc_RuntimeWarning
- single: PyExc_SyntaxWarning
- single: PyExc_UnicodeWarning
- single: PyExc_UserWarning
+ single: PyExc_Warning (C var)
+ single: PyExc_BytesWarning (C var)
+ single: PyExc_DeprecationWarning (C var)
+ single: PyExc_FutureWarning (C var)
+ single: PyExc_ImportWarning (C var)
+ single: PyExc_PendingDeprecationWarning (C var)
+ single: PyExc_ResourceWarning (C var)
+ single: PyExc_RuntimeWarning (C var)
+ single: PyExc_SyntaxWarning (C var)
+ single: PyExc_UnicodeWarning (C var)
+ single: PyExc_UserWarning (C var)
+------------------------------------------+---------------------------------+----------+
| C Name | Python Name | Notes |
.. c:function:: int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
- .. index:: single: Py_PRINT_RAW
+ .. index:: single: Py_PRINT_RAW (C macro)
Write object *obj* to file object *p*. The only supported flag for *flags* is
:c:macro:`Py_PRINT_RAW`; if given, the :func:`str` of the object is written
pair: module; __main__
pair: module; sys
triple: module; search; path
- single: PySys_SetArgv()
- single: PySys_SetArgvEx()
- single: Py_FinalizeEx()
+ single: PySys_SetArgv (C function)
+ single: PySys_SetArgvEx (C function)
+ single: Py_FinalizeEx (C function)
Initialize the Python interpreter. In an application embedding Python,
this should be called before using any other Python/C API functions; see
two threads simultaneously increment the reference count of the same object, the
reference count could end up being incremented only once instead of twice.
-.. index:: single: setswitchinterval() (in module sys)
+.. index:: single: setswitchinterval (in module sys)
Therefore, the rule exists that only the thread that has acquired the
:term:`GIL` may operate on Python objects or call Python/C API functions.
a file, so that other Python threads can run in the meantime.
.. index::
- single: PyThreadState
- single: PyThreadState
+ single: PyThreadState (C type)
The Python interpreter keeps some thread-specific bookkeeping information
inside a data structure called :c:type:`PyThreadState`. There's also one
Py_END_ALLOW_THREADS
.. index::
- single: Py_BEGIN_ALLOW_THREADS
- single: Py_END_ALLOW_THREADS
+ single: Py_BEGIN_ALLOW_THREADS (C macro)
+ single: Py_END_ALLOW_THREADS (C macro)
The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
hidden local variable; the :c:macro:`Py_END_ALLOW_THREADS` macro closes the
PyEval_RestoreThread(_save);
.. index::
- single: PyEval_RestoreThread()
- single: PyEval_SaveThread()
+ single: PyEval_RestoreThread (C function)
+ single: PyEval_SaveThread (C function)
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,
entry.)
.. index::
- single: Py_FinalizeEx()
- single: Py_Initialize()
+ single: Py_FinalizeEx (C function)
+ single: Py_Initialize (C function)
Extension modules are shared between (sub-)interpreters as follows:
As with multi-phase initialization, this means that only C-level static
and global variables are shared between these modules.
- .. index:: single: close() (in module os)
+ .. index:: single: close (in module os)
.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
- .. index:: single: Py_FinalizeEx()
+ .. index:: single: Py_FinalizeEx (C function)
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
.. c:function:: int Py_AddPendingCall(int (*func)(void *), void *arg)
- .. index:: single: Py_AddPendingCall()
-
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.
is "don't do that.")
.. index::
- single: Py_INCREF()
- single: Py_DECREF()
+ single: Py_INCREF (C function)
+ single: Py_DECREF (C function)
Reference counts are always manipulated explicitly. The normal way is
to use the macro :c:func:`Py_INCREF` to take a new reference to an
responsible for it any longer.
.. index::
- single: PyList_SetItem()
- single: PyTuple_SetItem()
+ single: PyList_SetItem (C function)
+ single: PyTuple_SetItem (C function)
Few functions steal references; the two notable exceptions are
:c:func:`PyList_SetItem` and :c:func:`PyTuple_SetItem`, which steal a reference
arguments), you do own a reference to the returned object.
.. index::
- single: PyList_GetItem()
- single: PySequence_GetItem()
+ single: PyList_GetItem (C function)
+ single: PySequence_GetItem (C function)
Here is an example of how you could write a function that computes the sum of
the items in a list of integers; once using :c:func:`PyList_GetItem`, and once
interpreter, where they are reported to the user accompanied by a stack
traceback.
-.. index:: single: PyErr_Occurred()
+.. index:: single: PyErr_Occurred (C function)
For C programmers, however, error checking always has to be explicit. All
functions in the Python/C API can raise exceptions, unless an explicit claim is
:c:func:`PyErr_Occurred`. These exceptions are always explicitly documented.
.. index::
- single: PyErr_SetString()
- single: PyErr_Clear()
+ single: PyErr_SetString (C function)
+ single: PyErr_Clear (C function)
Exception state is maintained in per-thread storage (this is equivalent to
using global storage in an unthreaded application). A thread can be in one of
bytecode interpreter's main loop, which takes care of transferring it to
``sys.exc_info()`` and friends.
-.. index:: single: exc_info() (in module sys)
+.. index:: single: exc_info (in module sys)
Note that starting with Python 1.5, the preferred, thread-safe way to access the
exception state from Python code is to call the function :func:`sys.exc_info`,
.. index:: single: incr_item()
.. index::
- single: PyErr_ExceptionMatches()
- single: PyErr_Clear()
- single: Py_XDECREF()
+ single: PyErr_ExceptionMatches (C function)
+ single: PyErr_Clear (C function)
+ single: Py_XDECREF (C function)
This example represents an endorsed use of the ``goto`` statement in C!
It illustrates the use of :c:func:`PyErr_ExceptionMatches` and
interpreter can only be used after the interpreter has been initialized.
.. index::
- single: Py_Initialize()
+ single: Py_Initialize (C function)
pair: module; builtins
pair: module; __main__
pair: module; sys
front of the standard path by setting :envvar:`PYTHONPATH`.
.. index::
- single: Py_SetProgramName()
- single: Py_GetPath()
- single: Py_GetPrefix()
- single: Py_GetExecPrefix()
- single: Py_GetProgramFullPath()
+ single: Py_SetProgramName (C function)
+ single: Py_GetPath (C function)
+ single: Py_GetPrefix (C function)
+ single: Py_GetExecPrefix (C function)
+ single: Py_GetProgramFullPath (C function)
The embedding application can steer the search by calling
``Py_SetProgramName(file)`` *before* calling :c:func:`Py_Initialize`. Note that
:c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, and
:c:func:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`).
-.. index:: single: Py_IsInitialized()
+.. index:: single: Py_IsInitialized (C function)
Sometimes, it is desirable to "uninitialize" Python. For instance, the
application may want to start over (make another call to
.. c:function:: long PyLong_AsLong(PyObject *obj)
.. index::
- single: LONG_MAX
+ single: LONG_MAX (C macro)
single: OverflowError (built-in exception)
Return a C :c:expr:`long` representation of *obj*. If *obj* is not an
.. c:function:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)
.. index::
- single: PY_SSIZE_T_MAX
+ single: PY_SSIZE_T_MAX (C macro)
single: OverflowError (built-in exception)
Return a C :c:type:`Py_ssize_t` representation of *pylong*. *pylong* must
.. c:function:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong)
.. index::
- single: ULONG_MAX
+ single: ULONG_MAX (C macro)
single: OverflowError (built-in exception)
Return a C :c:expr:`unsigned long` representation of *pylong*. *pylong*
.. c:function:: size_t PyLong_AsSize_t(PyObject *pylong)
.. index::
- single: SIZE_MAX
+ single: SIZE_MAX (C macro)
single: OverflowError (built-in exception)
Return a C :c:type:`size_t` representation of *pylong*. *pylong* must be
API functions listed in this document.
.. index::
- single: malloc()
- single: calloc()
- single: realloc()
- single: free()
+ single: malloc (C function)
+ single: calloc (C function)
+ single: realloc (C function)
+ single: free (C function)
To avoid memory corruption, extension writers should never try to operate on
Python objects with the functions exported by the C library: :c:func:`malloc`,
.. c:function:: void Py_FatalError(const char *message)
- .. index:: single: abort()
+ .. index:: single: abort (C function)
Print a fatal error message and kill the process. No cleanup is performed.
This function should only be invoked when a condition is detected that would
.. c:function:: void Py_Exit(int status)
.. index::
- single: Py_FinalizeEx()
- single: exit()
+ single: Py_FinalizeEx (C function)
+ single: exit (C function)
Exit the current process. This calls :c:func:`Py_FinalizeEx` and then calls the
standard C library function ``exit(status)``. If :c:func:`Py_FinalizeEx`
.. c:function:: int Py_AtExit(void (*func) ())
.. index::
- single: Py_FinalizeEx()
+ single: Py_FinalizeEx (C function)
single: cleanup functions
Register a cleanup function to be called by :c:func:`Py_FinalizeEx`. The cleanup
.. c:var:: int Py_eval_input
- .. index:: single: Py_CompileString()
+ .. index:: single: Py_CompileString (C function)
The start symbol from the Python grammar for isolated expressions; for use with
:c:func:`Py_CompileString`.
.. c:var:: int Py_file_input
- .. index:: single: Py_CompileString()
+ .. index:: single: Py_CompileString (C function)
The start symbol from the Python grammar for sequences of statements as read
from a file or other source; for use with :c:func:`Py_CompileString`. This is
.. c:var:: int Py_single_input
- .. index:: single: Py_CompileString()
+ .. index:: single: Py_CompileString (C function)
The start symbol from the Python grammar for a single statement; for use with
:c:func:`Py_CompileString`. This is the symbol used for the interactive
(but note that *temp* will not be ``NULL`` in this context). More info on them
in section :ref:`refcounts`.
-.. index:: single: PyObject_CallObject()
+.. index:: single: PyObject_CallObject (C function)
Later, when it is time to call the function, you call the C function
:c:func:`PyObject_CallObject`. This function has two arguments, both pointers to
Extracting Parameters in Extension Functions
============================================
-.. index:: single: PyArg_ParseTuple()
+.. index:: single: PyArg_ParseTuple (C function)
The :c:func:`PyArg_ParseTuple` function is declared as follows::
Keyword Parameters for Extension Functions
==========================================
-.. index:: single: PyArg_ParseTupleAndKeywords()
+.. index:: single: PyArg_ParseTupleAndKeywords (C function)
The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows::
}
.. index::
- single: PyErr_Fetch()
- single: PyErr_Restore()
+ single: PyErr_Fetch (C function)
+ single: PyErr_Restore (C function)
One important requirement of the deallocator function is that it leaves any
pending exceptions alone. This is important since deallocators are frequently
Simulating scanf()
^^^^^^^^^^^^^^^^^^
-.. index:: single: scanf()
+.. index:: single: scanf (C function)
Python does not currently have an equivalent to :c:func:`!scanf`. Regular
expressions are generally more powerful, though also more verbose, than